@promptframe/creation 0.2.7 → 0.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.
@@ -1,129 +1,157 @@
1
- import { CreationClientError } from "./credentials.mjs";
1
+ import {createHash} from 'node:crypto';
2
+ import {CreationClientError} from './credentials.mjs';
3
+ import {hostParameters,resolveHostIdentity} from './host-identity.mjs';
4
+ import {assertMcpResponseBudget} from './content-budget.mjs';
5
+ export {hostParameters} from './host-identity.mjs';
2
6
 
3
- const observations = new Set([
4
- "platform_list_projects", "platform_read_onboarding", "platform_list_sessions", "platform_read_session",
5
- "platform_list_tools", "platform_describe_tool", "platform_list_tasks",
6
- "platform_task", "platform_read_budget",
7
- ]);
8
- const threadFormat = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
9
-
10
- export function hostParameters(params) {
11
- const thread = params._meta?.threadId;
12
- if (thread === undefined) {
13
- if (observations.has(params.name)) return params;
14
- throw new CreationClientError("creation.host_identity_required");
15
- }
16
- if (typeof thread !== "string" || !threadFormat.test(thread))
17
- throw new CreationClientError("creation.host_identity_invalid");
18
- return params;
19
- }
20
-
21
- const controlled = new Set([
22
- "platform_call_tool", "platform_save_brief", "platform_release_control", "platform_handoff",
23
- ]);
24
- // Candidates only: the platform still checks its current registry isReadOnly
25
- // flag and built-in allowlist. A model-supplied readOnly flag grants nothing.
26
- const independentReads = new Set([
27
- "read_spec", "read_creative_plan", "get_creative_plan", "list_assets", "read_creation_consumption",
28
- "skills_list", "read_skill",
29
- ]);
30
- const isIndependentRead = (params) => independentReads.has(params.arguments.tool)
31
- || params.arguments.tool === "skill_view"
32
- && [undefined, "view", "none"].includes(params.arguments.arguments?.usage);
33
- const authorityReads = new Set([
34
- "platform_create_session", "platform_read_session", "platform_request_control",
35
- "platform_release_control", "platform_handoff",
36
- ]);
37
- const data = (result) => {
38
- const text = result.content?.find((part) => part.type === "text")?.text;
39
- try { return text ? JSON.parse(text) : null; } catch { return null; }
7
+ const digestPattern=/^sha256:[a-f0-9]{64}$/;
8
+ const accesses=new Set(['independent-read','controlled','authority']);
9
+ const digest=value=>'sha256:'+createHash('sha256').update(value).digest('hex');
10
+ const canonical=value=>{
11
+ if(value===null||typeof value==='string'||typeof value==='boolean'||typeof value==='number'&&Number.isFinite(value))return JSON.stringify(value);
12
+ if(Array.isArray(value))return '['+value.map(canonical).join(',')+']';
13
+ if(value&&typeof value==='object'&&[Object.prototype,null].includes(Object.getPrototypeOf(value)))
14
+ return '{'+Object.keys(value).sort().map(key=>JSON.stringify(key)+':'+canonical(value[key])).join(',')+'}';
15
+ throw new CreationClientError('creation.request_invalid');
40
16
  };
17
+ const argumentsDigest=value=>digest(canonical(value));
18
+ const boundedSet=(map,key,value)=>{if(!map.has(key)&&map.size>=1024)map.delete(map.keys().next().value);map.set(key,value);};
41
19
 
42
- /** A bridge process freezes its endpoint/account/installation credentials at
43
- * startup. Inside that boundary each host thread and work has its own approved
44
- * generation cache. Cache loss only causes an authoritative ownership read;
45
- * neither that read nor a schema refresh requests or grants control. */
46
- export function createHostCallBridge(client) {
47
- const versions = new Map();
48
- const keyFor = (params) => {
49
- const { projectId, sessionId } = params.arguments ?? {};
50
- if (typeof projectId !== "string" || typeof sessionId !== "string"
51
- || !projectId || !sessionId || projectId.length > 160 || sessionId.length > 160)
52
- return null;
53
- return JSON.stringify([params._meta?.threadId?.toLowerCase(), projectId, sessionId]);
54
- };
55
- const remember = (params, result) => {
56
- if (!authorityReads.has(params.name)) return;
57
- const value = data(result);
58
- if (result.isError || !value) return;
59
- const target = params.name === "platform_create_session"
60
- && value.projectId === params.arguments?.projectId && typeof value.sessionId === "string"
61
- ? { ...params, arguments: { ...params.arguments, sessionId: value.sessionId } } : params;
62
- const key = keyFor(target);
63
- if (!key || !value.control) return;
64
- if (params.name === "platform_read_session" && value.sessionId !== params.arguments.sessionId) {
65
- versions.delete(key);
66
- return;
20
+ /** The authenticated platform owns classification and editor authority.
21
+ * Business text and model annotations never populate this cache. */
22
+ export function createHostCallBridge(client,{credentials,host=resolveHostIdentity(),onCatalogChange=()=>{},onKnowledgeChange=()=>{}}={}){
23
+ if(!credentials?.endpoint||!credentials.clientId)throw new CreationClientError('creation.bridge_identity_required');
24
+ const installationDigest=digest(credentials.clientId);
25
+ const versions=new Map(),controllers=new Map(),catalogs=new Map(),inflight=new Map();
26
+ const knowledgeVersions=new Map(),upstream=client.getServerCapabilities?.()??{};
27
+ let platformDigest,accountDigest,directory,directoryRead,sequence=0;
28
+ function catalog(channel,version,order){
29
+ if(typeof version!=='string'||!digestPattern.test(version))return;
30
+ const old=catalogs.get(channel);if(old&&old.order>order)return;
31
+ boundedSet(catalogs,channel,{version,order});
32
+ if(old&&old.version!==version)Promise.resolve().then(onCatalogChange).catch(()=>{});
33
+ }
34
+ function keyFor(params){
35
+ const {projectId,sessionId}=params.arguments??{},thread=params._meta?.threadId;
36
+ return typeof thread==='string'&&[projectId,sessionId].every(v=>typeof v==='string'&&v.length>0&&v.length<=160)
37
+ ?JSON.stringify([thread.toLowerCase(),projectId,sessionId]):null;
38
+ }
39
+ function metadata(params,result){
40
+ const v=result?._meta?.['promptframe.creation'];
41
+ if(!v||v.contractVersion!=='creation-transport-metadata/v1'||!digestPattern.test(v.platformDigest)
42
+ ||platformDigest&&v.platformDigest!==platformDigest
43
+ ||v.installationDigest!==installationDigest||!digestPattern.test(v.accountDigest)||!digestPattern.test(v.controllerDigest))return null;
44
+ const thread=params._meta?.threadId?.toLowerCase();
45
+ if(thread?v.host?.kind!==host.kind||v.host.threadDigest!==digest(thread):v.host?.kind!=='legacy')return null;
46
+ for(const field of ['projectId','sessionId'])if(params.arguments?.[field]!==undefined&&v[field]!==params.arguments[field])return null;
47
+ if(accountDigest&&accountDigest!==v.accountDigest)return null;
48
+ const controllerKey=thread??'legacy',prior=controllers.get(controllerKey);
49
+ if(prior&&prior!==v.controllerDigest)return null;
50
+ // The connection URL can be a supported alias. Pin the canonical identity
51
+ // received outside business text on this one authenticated connection.
52
+ platformDigest??=v.platformDigest;accountDigest??=v.accountDigest;boundedSet(controllers,controllerKey,v.controllerDigest);return v;
53
+ }
54
+ function remember(params,result,order){
55
+ const v=metadata(params,result);if(!v)return null;
56
+ catalog(JSON.stringify([v.projectId??null,v.sessionId??null]),v.catalogVersion,order);
57
+ const target=v.sessionId&&!params.arguments?.sessionId?{...params,arguments:{...params.arguments,sessionId:v.sessionId}}:params;
58
+ const key=keyFor(target),c=v.control;
59
+ if(!key||!c||!Number.isSafeInteger(c.controlVersion)||c.controlVersion<=0||!['web','client'].includes(c.editor?.kind)
60
+ ||typeof c.editor.isCurrentClient!=='boolean'||c.editor.kind==='web'&&c.editor.isCurrentClient)return v;
61
+ const old=versions.get(key),version=c.controlVersion,owned=c.editor.kind==='client'&&c.editor.isCurrentClient;
62
+ const authorityRead=directory?.tools.get(params.name)?._meta?.['promptframe.role']==='control-read';
63
+ if(!old||version>old.version)boundedSet(versions,key,{version,owned,needsRead:false,authorityOrder:order});
64
+ else if(version===old.version&&order>=(old.authorityOrder??0)){
65
+ const freshRead=!result.isError&&authorityRead&&order>(old.invalidatedAt??0);
66
+ if(freshRead)boundedSet(versions,key,{version,owned,needsRead:false,authorityOrder:order});
67
+ else if(old.owned!==owned)boundedSet(versions,key,{...old,owned:false,needsRead:true,invalidatedAt:++sequence});
68
+ // A normal same-generation result cannot erase a newer error or conflict.
67
69
  }
68
- const control = value.control;
69
- if (control.editor?.kind === "client" && control.editor.isCurrentClient === true
70
- && Number.isSafeInteger(control.controlVersion) && control.controlVersion > 0) {
71
- versions.delete(key);
72
- if (versions.size >= 1024) versions.delete(versions.keys().next().value);
73
- versions.set(key, control.controlVersion);
74
- } else versions.delete(key);
75
- };
76
- const send = (params) => client.callTool(params, undefined, { timeout: 60_000 });
77
- return {
78
- async listTools() {
79
- const result = await client.listTools();
80
- return { ...result, tools: result.tools.map((tool) => {
81
- if (!controlled.has(tool.name)) return tool;
82
- const { controlVersion: _managed, ...properties } = tool.inputSchema.properties ?? {};
83
- return { ...tool, inputSchema: { ...tool.inputSchema, properties,
84
- ...(tool.inputSchema.required ? {
85
- required: tool.inputSchema.required.filter((name) => name !== "controlVersion"),
86
- } : {}),
87
- } };
88
- }) };
89
- },
90
- async call(raw) {
91
- const params = hostParameters(raw);
92
- for (const field of ["threadId", "controller", "clientDigest", "token", "controlVersion"])
93
- if (Object.hasOwn(params.arguments ?? {}, field))
94
- throw new CreationClientError("creation.transport_authority_managed_by_bridge");
95
- const key = keyFor(params);
96
- let outgoing = params;
97
- if (controlled.has(params.name)) {
98
- if (!key) throw new CreationClientError("creation.request_invalid");
99
- let controlVersion = versions.get(key);
100
- if (!controlVersion) {
101
- const read = { name: "platform_read_session", _meta: params._meta,
102
- arguments: { projectId: params.arguments.projectId, sessionId: params.arguments.sessionId, pageSize: 1 } };
103
- const result = await send(read);
104
- if (result.isError) return result;
105
- remember(read, result);
106
- controlVersion = versions.get(key);
107
- if (params.name === "platform_call_tool" && isIndependentRead(params)) {
108
- const observed = data(result);
109
- if (observed?.sessionId !== params.arguments.sessionId
110
- || !["web", "client"].includes(observed.control?.editor?.kind)
111
- || !Number.isSafeInteger(observed.control?.controlVersion) || observed.control.controlVersion <= 0)
112
- throw new CreationClientError("creation.control_unverified");
113
- // This is scoped read metadata, never an owned editor cache entry.
114
- controlVersion = observed.control.controlVersion;
115
- }
116
- if (!controlVersion) {
117
- if (!data(result)?.control) throw new CreationClientError("creation.control_unverified");
118
- throw new CreationClientError("creation.editor_not_current");
119
- }
120
- }
121
- outgoing = { ...params, arguments: { ...params.arguments, controlVersion } };
70
+ return v;
71
+ }
72
+ async function send(params){
73
+ const order=++sequence,result=assertMcpResponseBudget(await client.callTool(params,undefined,{timeout:60000}));
74
+ return {result,trusted:remember(params,result,order)};
75
+ }
76
+ async function listTools(){
77
+ const order=++sequence,result=assertMcpResponseBudget(await client.listTools());
78
+ if(result.tools.some(tool=>!accesses.has(tool._meta?.['promptframe.access'])))throw new CreationClientError('creation.upgrade_required');
79
+ if(!directory||order>=directory.order)directory={tools:new Map(result.tools.map(t=>[t.name,t])),order};
80
+ catalog('outer',result._meta?.['promptframe.catalogVersion'],order);
81
+ return {...result,tools:result.tools.map(tool=>{
82
+ const p=tool.inputSchema.properties;if(!Object.hasOwn(p??{},'controlVersion'))return tool;
83
+ const {controlVersion:_managed,...properties}=p;
84
+ return {...tool,inputSchema:{...tool.inputSchema,properties,...(tool.inputSchema.required
85
+ ?{required:tool.inputSchema.required.filter(name=>name!=='controlVersion')}:{})}};
86
+ })};
87
+ }
88
+ async function ensureDirectory(){
89
+ if(!directory){directoryRead??=listTools().finally(()=>{directoryRead=undefined;});await directoryRead;}
90
+ }
91
+ function role(name){
92
+ const found=[...directory.tools.values()].filter(t=>t._meta?.['promptframe.role']===name);
93
+ if(found.length!==1)throw new CreationClientError('creation.upgrade_required');return found[0].name;
94
+ }
95
+ async function controlRead(params,key){
96
+ if(!inflight.has(key))inflight.set(key,send({name:role('control-read'),_meta:params._meta,
97
+ arguments:{projectId:params.arguments.projectId,sessionId:params.arguments.sessionId,pageSize:1}}).finally(()=>{inflight.delete(key);}));
98
+ const observation=await inflight.get(key);if(observation.result.isError)return observation.result;
99
+ if(!observation.trusted||!versions.has(key)||versions.get(key).needsRead)throw new CreationClientError('creation.control_unverified');
100
+ }
101
+ async function knowledgeRead(kind,method,raw={}){
102
+ if(!upstream[kind])throw new CreationClientError('creation.knowledge_unsupported');
103
+ const params=hostParameters(raw,host,'independent-read'),order=++sequence;
104
+ const result=assertMcpResponseBudget(await client[method](params,undefined,{timeout:60000}));
105
+ const version=result._meta?.[kind==='resources'&&method==='listResources'
106
+ ?'promptframe.guideDirectoryVersion':'promptframe.guideVersion'];
107
+ const key=JSON.stringify([kind,method,raw.uri??raw.arguments?.projectId??null]);
108
+ if(digestPattern.test(version??'')){
109
+ const old=knowledgeVersions.get(key);
110
+ if(!old||order>=old.order){
111
+ boundedSet(knowledgeVersions,key,{version,order});
112
+ if(old&&old.version!==version)Promise.resolve().then(()=>onKnowledgeChange(kind)).catch(()=>{});
122
113
  }
123
- const result = await send(outgoing);
124
- if (result.isError && key) versions.delete(key);
125
- else remember(params, result);
126
- return result;
127
- },
128
- };
114
+ }
115
+ return result;
116
+ }
117
+ return {listTools,knowledgeCapabilities:{...(upstream.resources?{resources:{listChanged:true}}:{}),
118
+ ...(upstream.prompts?{prompts:{listChanged:true}}:{})},
119
+ listResources:params=>knowledgeRead('resources','listResources',params),
120
+ listResourceTemplates:params=>knowledgeRead('resources','listResourceTemplates',params),
121
+ readResource:params=>knowledgeRead('resources','readResource',params),
122
+ listPrompts:params=>knowledgeRead('prompts','listPrompts',params),
123
+ getPrompt:params=>knowledgeRead('prompts','getPrompt',params),async call(raw){
124
+ for(const field of ['threadId','controller','clientDigest','token','controlVersion'])if(Object.hasOwn(raw.arguments??{},field))
125
+ throw new CreationClientError('creation.transport_authority_managed_by_bridge');
126
+ await ensureDirectory();const definition=directory.tools.get(raw.name);
127
+ if(!definition)throw new CreationClientError('creation.tool_unavailable');
128
+ const access=definition._meta['promptframe.access'],managed=Object.hasOwn(definition.inputSchema.properties??{},'controlVersion');
129
+ const params=hostParameters(raw,host,managed?'controlled':access);let effectiveAccess=access;
130
+ if(definition._meta['promptframe.resolveAccess']==='target'){
131
+ const {projectId,sessionId,tool,arguments:input}=params.arguments??{};
132
+ if(typeof tool!=='string'||!input||typeof input!=='object'||Array.isArray(input))throw new CreationClientError('creation.request_invalid');
133
+ const observed=await send({name:role('describe-target'),_meta:params._meta,arguments:{projectId,sessionId,tool,arguments:input}});
134
+ if(observed.result.isError)return observed.result;
135
+ const resolved=observed.trusted?.resolvedAccess;
136
+ if(resolved?.tool!==tool||resolved.argumentsDigest!==argumentsDigest(input)||!accesses.has(resolved.access))throw new CreationClientError('creation.access_unverified');
137
+ effectiveAccess=resolved.access;
138
+ }
139
+ const key=keyFor(params);let outgoing=params;
140
+ if(managed){
141
+ if(!key)throw new CreationClientError('creation.request_invalid');let entry=versions.get(key);
142
+ if(!entry||entry.needsRead){const denied=await controlRead(params,key);if(denied)return denied;entry=versions.get(key);}
143
+ if(effectiveAccess!=='independent-read'&&!entry.owned)throw new CreationClientError('creation.editor_not_current');
144
+ outgoing={...params,arguments:{...params.arguments,controlVersion:entry.version}};
145
+ }
146
+ const dispatched=key&&versions.get(key);
147
+ const invalidate=()=>{
148
+ const current=key&&versions.get(key);
149
+ if(dispatched&&current&&current.version<=dispatched.version)
150
+ boundedSet(versions,key,{...current,needsRead:true,invalidatedAt:++sequence});
151
+ };
152
+ let response;
153
+ try{response=await send(outgoing);}catch(error){invalidate();throw error;}
154
+ if(response.result.isError)invalidate();
155
+ return response.result;
156
+ }};
129
157
  }
@@ -0,0 +1,35 @@
1
+ import {randomUUID} from 'node:crypto';
2
+ import {CreationClientError} from './credentials.mjs';
3
+
4
+ export function hostClientName(savedName,host){
5
+ return ['Codex PromptFrame','Claude Code PromptFrame'].includes(savedName)
6
+ ?host.kind==='claude-code'?'Claude Code PromptFrame':'Codex PromptFrame':savedName;
7
+ }
8
+
9
+ export const threadFormat=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
10
+
11
+ // Resolved once at startup. Desktop resume supplies the same session UUID.
12
+ export function resolveHostIdentity({host,env=process.env,uuid=randomUUID}={}){
13
+ const kind=host??(env.CLAUDECODE==='1'?'claude-code':'codex');
14
+ if(!['codex','claude-code'].includes(kind))throw new CreationClientError('creation.host_unsupported');
15
+ if(kind==='codex')return Object.freeze({kind});
16
+ const threadId=env.CLAUDE_CODE_SESSION_ID??uuid();
17
+ if(typeof threadId!=='string'||!threadFormat.test(threadId))throw new CreationClientError('creation.host_identity_invalid');
18
+ return Object.freeze({kind,threadId:threadId.toLowerCase()});
19
+ }
20
+
21
+ export function hostParameters(params,host,access){
22
+ const meta=params._meta??{};
23
+ if(Object.keys(meta).some(key=>key.startsWith('promptframe.')||['controlVersion','controller','clientDigest','token','catalogVersion','platformDigest'].includes(key)))
24
+ throw new CreationClientError('creation.transport_authority_managed_by_bridge');
25
+ if(host.kind==='claude-code'){
26
+ if(Object.hasOwn(meta,'threadId'))throw new CreationClientError('creation.transport_authority_managed_by_bridge');
27
+ return {...params,_meta:{...meta,threadId:host.threadId}};
28
+ }
29
+ if(meta.threadId===undefined){
30
+ if(access==='independent-read')return params;
31
+ throw new CreationClientError('creation.host_identity_required');
32
+ }
33
+ if(typeof meta.threadId!=='string'||!threadFormat.test(meta.threadId))throw new CreationClientError('creation.host_identity_invalid');
34
+ return params;
35
+ }
@@ -0,0 +1,208 @@
1
+ import {createHash,randomBytes} from 'node:crypto';
2
+ import {gunzipSync} from 'node:zlib';
3
+ import {list as listTar} from 'tar';
4
+ import {lstat,mkdir,open,readFile,readdir,rename,rm,statfs} from 'node:fs/promises';
5
+ import {execFile} from 'node:child_process';
6
+ import {promisify} from 'node:util';
7
+ import path from 'node:path';
8
+ import {CreationClientError} from './credentials.mjs';
9
+ import {compareBridgeVersions,assertBridgeCompatible,readPlatformBridgePolicy} from './bridge-negotiation.mjs';
10
+ import {inspectRuntimePackage,RUNTIME_PACKAGE_ENTRIES,OPTIONAL_HOST_ENTRIES} from './runtime-package.mjs';
11
+
12
+ const PACKAGE='@promptframe/creation',REGISTRY='https://registry.npmjs.org';
13
+ const MAX_ARCHIVE=8*1024*1024,MAX_PAYLOAD=32*1024*1024,MAX_TAR=36*1024*1024;
14
+ const hash=b=>createHash('sha256').update(b).digest('hex'),execute=promisify(execFile);
15
+ const error=code=>new CreationClientError('creation.'+code);
16
+ const version=v=>{compareBridgeVersions(v,v);return v;};
17
+ const pause=ms=>new Promise(resolve=>setTimeout(resolve,ms));
18
+ const roots=new Set([...RUNTIME_PACKAGE_ENTRIES,...OPTIONAL_HOST_ENTRIES,'.agents']);
19
+ class RuntimeSelectionError extends CreationClientError{
20
+ constructor(code,currentVersion,lockedVersion,policy,action){
21
+ super('creation.'+code);this.runtimeFacts=Object.freeze({currentVersion,...(lockedVersion?{lockedVersion}:{}),
22
+ ...(policy?{minimumVersion:policy.minBridge,recommendedVersion:policy.recommendedBridge}:{}),action});
23
+ }
24
+ }
25
+ export const runtimeErrorDetails=error=>error instanceof RuntimeSelectionError?error.runtimeFacts:undefined;
26
+ const snapshot=payload=>({version:payload.version,hosts:payload.hosts,payloadDigest:payload.payloadDigest,
27
+ files:payload.files.map(({path,bytes,sha256})=>({path,bytes,sha256}))});
28
+ async function info(file){try{return await lstat(file);}catch(e){if(e.code==='ENOENT')return null;throw e;}}
29
+ async function privateDirectory(dir){
30
+ await mkdir(dir,{recursive:true,mode:0o700});const s=await lstat(dir);
31
+ if(!s.isDirectory()||s.isSymbolicLink()||s.uid!==process.getuid?.()||(s.mode&0o077))throw error('runtime_cache_owner_invalid');
32
+ }
33
+ async function privateJSON(file){
34
+ const s=await info(file);if(!s)return null;
35
+ if(!s.isFile()||s.isSymbolicLink()||s.uid!==process.getuid?.()||(s.mode&0o077)||s.size>512*1024)throw error('runtime_cache_invalid');
36
+ return JSON.parse(await readFile(file,'utf8'));
37
+ }
38
+ async function syncDirectory(dir){const fd=await open(dir,'r');try{await fd.sync();}finally{await fd.close();}}
39
+ async function exclusiveJSON(file,value){
40
+ const fd=await open(file,'wx',0o600);try{await fd.writeFile(JSON.stringify(value)+'\n');await fd.sync();}finally{await fd.close();}
41
+ }
42
+
43
+ /** Only the fixed public package/version is resolved. Metadata never supplies
44
+ * executable arguments, an alternative registry, credentials or a download command. */
45
+ export function checkedRuntimeMetadata(value,expectedVersion){
46
+ version(expectedVersion);
47
+ const tarball=REGISTRY+'/@promptframe/creation/-/creation-'+expectedVersion+'.tgz';
48
+ if(value?.name!==PACKAGE||value.version!==expectedVersion||value.dist?.tarball!==tarball
49
+ ||typeof value.dist.integrity!=='string'||!/^sha512-[A-Za-z0-9+/]{86}==$/.test(value.dist.integrity))
50
+ throw error('runtime_registry_identity_invalid');
51
+ const encoded=value.dist.integrity.slice(7);
52
+ if(Buffer.from(encoded,'base64').toString('base64')!==encoded)throw error('runtime_registry_identity_invalid');
53
+ return{version:expectedVersion,integrity:value.dist.integrity,tarball};
54
+ }
55
+
56
+ async function boundedGet(url,{fetchImpl=fetch,signal,maxBytes,timeoutMs}){
57
+ const controller=new AbortController(),abort=()=>controller.abort(),timer=setTimeout(abort,timeoutMs);
58
+ signal?.addEventListener('abort',abort,{once:true});if(signal?.aborted)abort();let response;
59
+ try{
60
+ response=await fetchImpl(url,{signal:controller.signal,redirect:'error'});
61
+ if(response.status!==200||Number(response.headers.get('content-length')??0)>maxBytes||!response.body)throw error('runtime_fetch_unavailable');
62
+ const chunks=[];let count=0;
63
+ for await(const chunk of response.body){count+=chunk.length;if(count>maxBytes)throw error('runtime_download_capacity');chunks.push(Buffer.from(chunk));}
64
+ return Buffer.concat(chunks,count);
65
+ }catch(e){await response?.body?.cancel().catch(()=>{});if(e instanceof CreationClientError)throw e;throw error('runtime_fetch_unavailable');}
66
+ finally{clearTimeout(timer);signal?.removeEventListener('abort',abort);}
67
+ }
68
+
69
+ /** tar handles archive parsing, while this function only creates regular files
70
+ * itself. Links, special entries, duplicate/escaping paths and expansion bombs
71
+ * are rejected before any payload is written to a private staging directory. */
72
+ export async function readRuntimeArchive(archive,metadata){
73
+ if(!Buffer.isBuffer(archive)||archive.length>MAX_ARCHIVE
74
+ ||'sha512-'+createHash('sha512').update(archive).digest('base64')!==metadata.integrity)throw error('runtime_integrity_invalid');
75
+ let raw;try{raw=gunzipSync(archive,{maxOutputLength:MAX_TAR});}catch{throw error('runtime_archive_invalid');}
76
+ const files=[],names=new Set();let total=0,entries=0,failure;
77
+ const parser=listTar({strict:true,onReadEntry:entry=>{
78
+ const name=entry.path;
79
+ if(++entries>2048||!['File','Directory'].includes(entry.type)||!Number.isSafeInteger(entry.size)||entry.size<0
80
+ ||entry.size>MAX_PAYLOAD||typeof name!=='string'||name.length>240||!name.startsWith('package/')
81
+ ||name.includes('\\')||/[\x00-\x1f\x7f]/.test(name))failure=error('runtime_archive_invalid');
82
+ const relative=name.slice(8).replace(/\/$/,'');
83
+ if(relative&&(relative.normalize('NFC')!==relative||/[<>:"|?*]/.test(relative)
84
+ ||relative.split('/').some(p=>!p||p==='.'||p==='..'||/[. ]$/.test(p)
85
+ ||/^(?:con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\.|$)/i.test(p)
86
+ ||p==='node_modules'||p==='credentials.json'||p.startsWith('.env'))||!roots.has(relative.split('/')[0])))
87
+ failure=error('runtime_archive_invalid');
88
+ const portableName=relative.toLowerCase();
89
+ if(names.has(portableName))failure=error('runtime_archive_invalid');names.add(portableName);
90
+ if(entry.type==='Directory'){if(entry.size!==0)failure=error('runtime_archive_invalid');return;}
91
+ total+=entry.size;if(total>MAX_PAYLOAD||files.length>=1024||!relative)failure=error('runtime_archive_capacity');
92
+ const chunks=[];let bytes=0;
93
+ entry.on('data',chunk=>{bytes+=chunk.length;if(bytes>entry.size)failure=error('runtime_archive_invalid');if(!failure)chunks.push(Buffer.from(chunk));});
94
+ entry.on('end',()=>{if(bytes!==entry.size)failure=error('runtime_archive_invalid');if(!failure)files.push({path:relative,body:Buffer.concat(chunks,bytes)});});
95
+ }});
96
+ await new Promise((resolve,reject)=>{parser.once('error',()=>reject(error('runtime_archive_invalid')));parser.once('end',resolve);parser.end(raw);});
97
+ if(failure)throw failure;
98
+ if(!files.length||files.length>1024)throw error('runtime_archive_invalid');
99
+ return files;
100
+ }
101
+
102
+ async function cacheLock(root,signal){
103
+ const name=path.join(root,'prepare.lock'),end=Date.now()+5000;let fd;
104
+ while(!fd){
105
+ signal?.throwIfAborted();
106
+ try{fd=await open(name,'wx',0o600);}catch(e){if(e.code!=='EEXIST')throw e;if(Date.now()>=end)throw error('runtime_cache_busy');await pause(50);}
107
+ }
108
+ const owned=await fd.stat();
109
+ try{await fd.writeFile(JSON.stringify({pid:process.pid,createdAt:new Date().toISOString()})+'\n');await fd.sync();await syncDirectory(root);}
110
+ catch(e){await fd.close();const now=await info(name);if(now&&now.dev===owned.dev&&now.ino===owned.ino)await rm(name);throw e;}
111
+ return async()=>{const now=await info(name);await fd.close();if(!now||now.dev!==owned.dev||now.ino!==owned.ino)throw error('runtime_lock_changed');await rm(name);};
112
+ }
113
+ async function verifyCached(target,metadata,hostKind){
114
+ if(!await info(target))return null;
115
+ await privateDirectory(target);
116
+ const manifest=await privateJSON(path.join(target,'runtime.json'));
117
+ if(!manifest||manifest.contractVersion!=='creation-verified-runtime/v1'||manifest.version!==metadata.version||manifest.integrity!==metadata.integrity)
118
+ throw error('runtime_cache_invalid');
119
+ // Runtime caches verify every archived root, including plugin discovery
120
+ // metadata. User-level installation still copies its original payload roots.
121
+ const names=(await readdir(target)).filter(name=>name!=='runtime.json').sort();
122
+ if(names.some(name=>!roots.has(name))||RUNTIME_PACKAGE_ENTRIES.some(name=>!names.includes(name)))throw error('runtime_cache_invalid');
123
+ const payload=await inspectRuntimePackage(target,{entries:names});
124
+ if(!payload.hosts.includes(hostKind))throw error('runtime_host_unsupported');
125
+ if(JSON.stringify(snapshot(payload))!==JSON.stringify(manifest.payload))throw error('runtime_cache_invalid');
126
+ return{version:payload.version,root:target,integrity:metadata.integrity,reused:true};
127
+ }
128
+ async function checkedVersionIndex(cacheRoot,metadata){
129
+ const old=await privateJSON(path.join(cacheRoot,'version-'+metadata.version+'.json'));
130
+ if(old&&JSON.stringify(old)!==JSON.stringify(metadata))throw error('runtime_registry_identity_conflict');
131
+ return old;
132
+ }
133
+
134
+ export async function prepareVerifiedRuntime(metadata,{cacheRoot,fetchImpl=fetch,signal,checkRuntime,hostKind='codex'}={}){
135
+ if(!['codex','claude-code'].includes(hostKind))throw error('runtime_host_unsupported');
136
+ if(!path.isAbsolute(cacheRoot??''))throw error('runtime_cache_owner_invalid');
137
+ metadata=checkedRuntimeMetadata({name:PACKAGE,version:metadata.version,dist:metadata},metadata.version);
138
+ await privateDirectory(cacheRoot);
139
+ await checkedVersionIndex(cacheRoot,metadata);
140
+ const target=path.join(cacheRoot,metadata.version+'-'+hash(metadata.integrity)),existing=await verifyCached(target,metadata,hostKind);
141
+ if(existing)return existing;
142
+ const archive=await boundedGet(metadata.tarball,{fetchImpl,signal,maxBytes:MAX_ARCHIVE,timeoutMs:15000});
143
+ const files=await readRuntimeArchive(archive,metadata),release=await cacheLock(cacheRoot,signal);
144
+ const temporary=path.join(cacheRoot,'.partial-'+randomBytes(12).toString('hex'));
145
+ try{
146
+ const index=await checkedVersionIndex(cacheRoot,metadata);
147
+ const found=await verifyCached(target,metadata,hostKind);if(found)return found;
148
+ const space=await statfs(cacheRoot,{bigint:true}),needed=BigInt(files.reduce((n,f)=>n+f.body.length,0)+4*1024*1024);
149
+ if(space.bavail*space.bsize<needed)throw error('runtime_cache_capacity');
150
+ await mkdir(temporary,{mode:0o700});
151
+ for(const file of files){signal?.throwIfAborted();const dest=path.join(temporary,...file.path.split('/'));
152
+ await mkdir(path.dirname(dest),{recursive:true,mode:0o700});const fd=await open(dest,'wx',0o600);
153
+ try{await fd.writeFile(file.body);await fd.sync();}finally{await fd.close();}}
154
+ const entries=[...new Set(files.map(file=>file.path.split('/')[0]))].sort();
155
+ if(RUNTIME_PACKAGE_ENTRIES.some(name=>!entries.includes(name)))throw error('runtime_package_incomplete');
156
+ const payload=await inspectRuntimePackage(temporary,{entries});
157
+ if(!payload.hosts.includes(hostKind))throw error('runtime_host_unsupported');
158
+ if(payload.version!==metadata.version)throw error('runtime_package_version_invalid');
159
+ const pkg=JSON.parse(payload.files.find(f=>f.path==='package.json').body);
160
+ if(pkg.repository?.url!=='git+https://github.com/ty-teams/promptframe-creation.git'||pkg.private===true)throw error('runtime_package_identity_invalid');
161
+ if(checkRuntime)await checkRuntime(temporary,metadata.version);
162
+ else{
163
+ const result=await execute(process.execPath,[path.join(temporary,'bin/promptframe-creation.mjs'),'--version'],
164
+ {timeout:5000,maxBuffer:65536,windowsHide:true,signal,env:{...process.env,
165
+ PROMPTFRAME_CREATION_CONFIG:path.join(temporary,'no-credentials.json')}});
166
+ if(result.stdout.trim()!==metadata.version||result.stderr.trim())throw error('runtime_package_version_invalid');
167
+ }
168
+ signal?.throwIfAborted();
169
+ await exclusiveJSON(path.join(temporary,'runtime.json'),{contractVersion:'creation-verified-runtime/v1',
170
+ version:metadata.version,integrity:metadata.integrity,payload:snapshot(payload)});
171
+ await syncDirectory(temporary);
172
+ if(!index){await exclusiveJSON(path.join(cacheRoot,'version-'+metadata.version+'.json'),metadata);await syncDirectory(cacheRoot);}
173
+ await rename(temporary,target);await syncDirectory(cacheRoot);
174
+ return{version:metadata.version,root:target,integrity:metadata.integrity,reused:false};
175
+ }finally{try{if(await info(temporary))await rm(temporary,{recursive:true});}finally{await release();}}
176
+ }
177
+
178
+ export async function selectBridgeRuntime({policy,currentVersion,lockedVersion,resolvedVersion,cacheRoot,fetchImpl=fetch,signal,checkRuntime,hostKind='codex'}={}){
179
+ version(currentVersion);if(lockedVersion!==undefined)version(lockedVersion);
180
+ if(resolvedVersion!==undefined&&resolvedVersion!==currentVersion)throw error('runtime_selection_identity_invalid');
181
+ if(!policy)throw new RuntimeSelectionError('platform_bridge_policy_unavailable',currentVersion,lockedVersion,null,
182
+ 'update_platform_then_start_new_session');
183
+ policy=readPlatformBridgePolicy({experimental:{'promptframe.creation':policy}});
184
+ const target=lockedVersion??resolvedVersion??(policy&&compareBridgeVersions(policy.recommendedBridge,currentVersion)>0?policy.recommendedBridge:currentVersion);
185
+ if(policy&&compareBridgeVersions(target,policy.minBridge)<0){
186
+ if(lockedVersion!==undefined)throw new RuntimeSelectionError('bridge_locked_below_minimum',currentVersion,lockedVersion,policy,'choose_compatible_bridge_version_or_remove_lock');
187
+ else assertBridgeCompatible({experimental:{'promptframe.creation':policy}},currentVersion);
188
+ }
189
+ if(target===currentVersion){if(policy)assertBridgeCompatible({experimental:{'promptframe.creation':policy}},currentVersion);
190
+ return{version:currentVersion,current:true,locked:lockedVersion!==undefined,status:'current'};}
191
+ try{
192
+ await privateDirectory(cacheRoot);let metadata,metadataSource='registry';
193
+ try{const raw=await boundedGet(REGISTRY+'/@promptframe%2fcreation/'+target,{fetchImpl,signal,maxBytes:256*1024,timeoutMs:5000});
194
+ metadata=checkedRuntimeMetadata(JSON.parse(raw),target);
195
+ }catch(e){const prior=await privateJSON(path.join(cacheRoot,'version-'+target+'.json'));if(!prior)throw e;
196
+ metadata=checkedRuntimeMetadata({name:PACKAGE,version:target,dist:prior},target);metadataSource='previously-verified-cache';}
197
+ return{...await prepareVerifiedRuntime(metadata,{cacheRoot,fetchImpl,signal,checkRuntime,hostKind}),current:false,
198
+ locked:lockedVersion!==undefined,status:'verified',metadataSource};
199
+ }catch(e){
200
+ if(signal?.aborted)throw error('runtime_selection_interrupted');
201
+ if(lockedVersion!==undefined)
202
+ throw new RuntimeSelectionError('bridge_locked_version_unavailable',currentVersion,lockedVersion,policy,'retry_same_fixed_version_in_new_session');
203
+ if(policy&&compareBridgeVersions(currentVersion,policy.minBridge)>=0)
204
+ return{version:currentVersion,current:true,locked:false,status:'update_unavailable_current_compatible'};
205
+ if(policy)assertBridgeCompatible({experimental:{'promptframe.creation':policy}},currentVersion);
206
+ if(e instanceof CreationClientError)throw e;throw error('runtime_selection_unavailable');
207
+ }
208
+ }
@@ -0,0 +1,27 @@
1
+ import {spawn} from 'node:child_process';
2
+ import path from 'node:path';
3
+ import {CreationClientError} from './credentials.mjs';
4
+
5
+ /** Relay a new session once, before this process has consumed host stdio.
6
+ * After spawning, any failure belongs to that runtime; it never respawns or
7
+ * falls back to another bridge which could replay an accepted business call. */
8
+ export async function launchSelectedBridge(selection,{host,configFile,spawnImpl=spawn,env=process.env}={}){
9
+ if(!path.isAbsolute(selection.root??'')||!path.isAbsolute(configFile??'')||!['codex','claude-code'].includes(host?.kind))
10
+ throw new CreationClientError('creation.runtime_launch_invalid');
11
+ let child;
12
+ try{child=spawnImpl(process.execPath,[path.join(selection.root,'bin/promptframe-creation.mjs'),'bridge',
13
+ '--config',configFile,'--host',host.kind,selection.locked?'--bridge-version':'--resolved-runtime-version',selection.version],
14
+ {stdio:'inherit',windowsHide:true,env:{...env,PROMPTFRAME_CREATION_CONFIG:configFile,
15
+ ...(host.kind==='claude-code'?{CLAUDECODE:'1',CLAUDE_CODE_SESSION_ID:host.threadId}:{})}});}
16
+ catch{throw new CreationClientError('creation.runtime_start_unconfirmed');}
17
+ let signaled=false;
18
+ const forward=signal=>{if(!signaled){signaled=true;child.kill(signal);}};
19
+ const interrupt=()=>forward('SIGINT'),terminate=()=>forward('SIGTERM');
20
+ process.once('SIGINT',interrupt);process.once('SIGTERM',terminate);
21
+ try{
22
+ return await new Promise((resolve,reject)=>{
23
+ child.once('error',()=>reject(new CreationClientError('creation.runtime_start_unconfirmed')));
24
+ child.once('close',(code,signal)=>resolve({code:Number.isInteger(code)?code:1,signal:signal??null}));
25
+ });
26
+ }finally{process.removeListener('SIGINT',interrupt);process.removeListener('SIGTERM',terminate);}
27
+ }
@@ -0,0 +1,41 @@
1
+ import {lstat,readdir,readFile} from 'node:fs/promises';
2
+ import {createHash} from 'node:crypto';
3
+ import path from 'node:path';
4
+ import {CreationClientError} from './credentials.mjs';
5
+
6
+ export const RUNTIME_PACKAGE_ENTRIES=Object.freeze(['package.json','README.md','LICENSE','bin','dist','lib','skills','docs','.codex-plugin','.mcp.json']);
7
+ export const OPTIONAL_HOST_ENTRIES=Object.freeze(['.claude-plugin','.claude-mcp.json']);
8
+ const hash=b=>createHash('sha256').update(b).digest('hex');
9
+ const invalid=code=>{throw new CreationClientError('installation.'+code);};
10
+ /** Shared payload inspection only. It never registers a host or changes a
11
+ * profile; callers own private staging, immutable publication and lifecycle. */
12
+ export async function inspectRuntimePackage(root,{entries}={}){
13
+ if(!entries){entries=[...RUNTIME_PACKAGE_ENTRIES];for(const name of OPTIONAL_HOST_ENTRIES){
14
+ try{await lstat(path.join(root,name));entries.push(name);}catch(e){if(e.code!=='ENOENT')throw e;}
15
+ }}
16
+ const files=[];let bytes=0;
17
+ async function walk(relative){
18
+ let s;try{s=await lstat(path.join(root,relative));}catch(error){if(error.code!=='ENOENT')throw error;}
19
+ if(!s||s.isSymbolicLink())invalid('package_file_invalid');
20
+ if(s.isDirectory()){
21
+ for(const name of(await readdir(path.join(root,relative))).sort()){
22
+ if(name==='node_modules'||name==='credentials.json'||name.startsWith('.env'))invalid('package_file_invalid');
23
+ await walk(path.join(relative,name));
24
+ }
25
+ }else if(s.isFile()){
26
+ if(s.size>32*1024*1024)invalid('package_too_large');
27
+ const body=await readFile(path.join(root,relative));bytes+=body.length;
28
+ if(files.length>=1024||bytes>32*1024*1024)invalid('package_too_large');
29
+ files.push({path:relative,bytes:body.length,sha256:hash(body),body});
30
+ }else invalid('package_file_invalid');
31
+ }
32
+ for(const name of entries)await walk(name);
33
+ for(const name of ['dist/cli.mjs','dist/THIRD_PARTY_NOTICES.txt','skills/creation-setup/SKILL.md','skills/video-creation/SKILL.md'])
34
+ if(!files.some(f=>f.path===name))invalid('package_incomplete');
35
+ const pkg=JSON.parse(files.find(f=>f.path==='package.json').body),plugin=JSON.parse(files.find(f=>f.path==='.codex-plugin/plugin.json').body);
36
+ if(pkg.name!=='@promptframe/creation'||!/^\d+\.\d+\.\d+$/.test(pkg.version)||plugin.version!==pkg.version)invalid('package_identity_invalid');
37
+ const claude=files.find(f=>f.path==='.claude-plugin/plugin.json');
38
+ if(claude&&JSON.parse(claude.body).version!==pkg.version)invalid('package_identity_invalid');
39
+ return{files,version:pkg.version,hosts:claude?['codex','claude-code']:['codex'],
40
+ payloadDigest:hash(JSON.stringify(files.map(({path,bytes,sha256})=>({path,bytes,sha256}))))};
41
+ }