@promptframe/creation 0.2.7 → 0.3.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.agents/plugins/marketplace.json +1 -1
- package/.claude-mcp.json +8 -0
- package/.claude-plugin/marketplace.json +5 -0
- package/.claude-plugin/plugin.json +60 -0
- package/.codex-plugin/plugin.json +1 -1
- package/README.md +6 -4
- package/dist/THIRD_PARTY_NOTICES.txt +59 -0
- package/dist/cli.mjs +6222 -1557
- package/docs/development.md +20 -1
- package/docs/install-guidance.json +36 -0
- package/docs/installing.md +23 -3
- package/docs/releases/0.3.0.md +10 -0
- package/docs/releases/0.3.1.md +7 -0
- package/lib/bridge-negotiation.mjs +54 -0
- package/lib/claude-command.mjs +57 -0
- package/lib/claude-hook-definition.mjs +11 -0
- package/lib/claude-hook-registration.mjs +66 -0
- package/lib/claude-host-process.mjs +48 -0
- package/lib/claude-host-session.mjs +150 -0
- package/lib/claude-installation.mjs +195 -0
- package/lib/claude-local-state.mjs +17 -0
- package/lib/claude-mcp-installation.mjs +177 -0
- package/lib/cli.mjs +89 -15
- package/lib/connection.mjs +15 -4
- package/lib/content-budget.mjs +15 -0
- package/lib/host-context.mjs +178 -123
- package/lib/host-identity.mjs +34 -0
- package/lib/runtime-bootstrap.mjs +208 -0
- package/lib/runtime-launch.mjs +27 -0
- package/lib/runtime-package.mjs +41 -0
- package/lib/user-installation.mjs +6 -25
- package/lib/version.mjs +1 -1
- package/package.json +5 -2
- package/skills/creation-setup/SKILL.md +9 -3
- package/skills/video-creation/SKILL.md +16 -40
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import {CreationClientError} from './credentials.mjs';
|
|
2
|
+
|
|
3
|
+
export const MCP_BLOCK_BYTES=400_000;
|
|
4
|
+
export const MCP_RESPONSE_BYTES=2_000_000;
|
|
5
|
+
const bytes=value=>Buffer.byteLength(JSON.stringify(value),'utf8');
|
|
6
|
+
|
|
7
|
+
/** Inspect the serialized response, including base64 and metadata. Refusing
|
|
8
|
+
* an oversized result never retries the accepted business operation. */
|
|
9
|
+
export function assertMcpResponseBudget(result){
|
|
10
|
+
if(bytes(result)>MCP_RESPONSE_BYTES)throw new CreationClientError('creation.response_budget_exceeded');
|
|
11
|
+
const blocks=[...(result.content??[]),...(result.contents??[])];
|
|
12
|
+
for(const message of result.messages??[])if(message.content)blocks.push(message.content);
|
|
13
|
+
if(blocks.some(block=>bytes(block)>MCP_BLOCK_BYTES))throw new CreationClientError('creation.content_budget_exceeded');
|
|
14
|
+
return result;
|
|
15
|
+
}
|
package/lib/host-context.mjs
CHANGED
|
@@ -1,129 +1,184 @@
|
|
|
1
|
-
import {
|
|
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
|
+
import {CLAUDE_HOST_PROOF} from './claude-host-session.mjs';
|
|
6
|
+
export {hostParameters} from './host-identity.mjs';
|
|
2
7
|
|
|
3
|
-
const
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
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; }
|
|
8
|
+
const digestPattern=/^sha256:[a-f0-9]{64}$/;
|
|
9
|
+
const accesses=new Set(['independent-read','controlled','authority']);
|
|
10
|
+
const digest=value=>'sha256:'+createHash('sha256').update(value).digest('hex');
|
|
11
|
+
const canonical=value=>{
|
|
12
|
+
if(value===null||typeof value==='string'||typeof value==='boolean'||typeof value==='number'&&Number.isFinite(value))return JSON.stringify(value);
|
|
13
|
+
if(Array.isArray(value))return '['+value.map(canonical).join(',')+']';
|
|
14
|
+
if(value&&typeof value==='object'&&[Object.prototype,null].includes(Object.getPrototypeOf(value)))
|
|
15
|
+
return '{'+Object.keys(value).sort().map(key=>JSON.stringify(key)+':'+canonical(value[key])).join(',')+'}';
|
|
16
|
+
throw new CreationClientError('creation.request_invalid');
|
|
40
17
|
};
|
|
18
|
+
const argumentsDigest=value=>digest(canonical(value));
|
|
19
|
+
const boundedSet=(map,key,value)=>{if(!map.has(key)&&map.size>=1024)map.delete(map.keys().next().value);map.set(key,value);};
|
|
41
20
|
|
|
42
|
-
/**
|
|
43
|
-
*
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
const versions = new Map();
|
|
48
|
-
const
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
const
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
const
|
|
63
|
-
if
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
21
|
+
/** The authenticated platform owns classification and editor authority.
|
|
22
|
+
* Business text and model annotations never populate this cache. */
|
|
23
|
+
export function createHostCallBridge(client,{credentials,host=resolveHostIdentity(),hostSession,onCatalogChange=()=>{},onKnowledgeChange=()=>{}}={}){
|
|
24
|
+
if(!credentials?.endpoint||!credentials.clientId)throw new CreationClientError('creation.bridge_identity_required');
|
|
25
|
+
const installationDigest=digest(credentials.clientId);
|
|
26
|
+
const versions=new Map(),controllers=new Map(),catalogs=new Map(),inflight=new Map();
|
|
27
|
+
const knowledgeVersions=new Map(),upstream=client.getServerCapabilities?.()??{};
|
|
28
|
+
let platformDigest,accountDigest,directory,directoryRead,sequence=0,hostEpoch;
|
|
29
|
+
function catalog(channel,version,order){
|
|
30
|
+
if(typeof version!=='string'||!digestPattern.test(version))return;
|
|
31
|
+
const old=catalogs.get(channel);if(old&&old.order>order)return;
|
|
32
|
+
boundedSet(catalogs,channel,{version,order});
|
|
33
|
+
if(old&&old.version!==version)Promise.resolve().then(onCatalogChange).catch(()=>{});
|
|
34
|
+
}
|
|
35
|
+
function keyFor(params){
|
|
36
|
+
const {projectId,sessionId}=params.arguments??{},thread=params._meta?.threadId;
|
|
37
|
+
return typeof thread==='string'&&[projectId,sessionId].every(v=>typeof v==='string'&&v.length>0&&v.length<=160)
|
|
38
|
+
?JSON.stringify([thread.toLowerCase(),projectId,sessionId]):null;
|
|
39
|
+
}
|
|
40
|
+
function metadata(params,result){
|
|
41
|
+
const v=result?._meta?.['promptframe.creation'];
|
|
42
|
+
if(!v||v.contractVersion!=='creation-transport-metadata/v1'||!digestPattern.test(v.platformDigest)
|
|
43
|
+
||platformDigest&&v.platformDigest!==platformDigest
|
|
44
|
+
||v.installationDigest!==installationDigest||!digestPattern.test(v.accountDigest)||!digestPattern.test(v.controllerDigest))return null;
|
|
45
|
+
const thread=params._meta?.threadId?.toLowerCase();
|
|
46
|
+
if(thread?v.host?.kind!==host.kind||v.host.threadDigest!==digest(thread):v.host?.kind!=='legacy')return null;
|
|
47
|
+
for(const field of ['projectId','sessionId'])if(params.arguments?.[field]!==undefined&&v[field]!==params.arguments[field])return null;
|
|
48
|
+
if(accountDigest&&accountDigest!==v.accountDigest)return null;
|
|
49
|
+
const controllerKey=thread??'legacy',prior=controllers.get(controllerKey);
|
|
50
|
+
if(prior&&prior!==v.controllerDigest)return null;
|
|
51
|
+
// The connection URL can be a supported alias. Pin the canonical identity
|
|
52
|
+
// received outside business text on this one authenticated connection.
|
|
53
|
+
platformDigest??=v.platformDigest;accountDigest??=v.accountDigest;boundedSet(controllers,controllerKey,v.controllerDigest);return v;
|
|
54
|
+
}
|
|
55
|
+
function remember(params,result,order){
|
|
56
|
+
const v=metadata(params,result);if(!v)return null;
|
|
57
|
+
catalog(JSON.stringify([v.projectId??null,v.sessionId??null]),v.catalogVersion,order);
|
|
58
|
+
const target=v.sessionId&&!params.arguments?.sessionId?{...params,arguments:{...params.arguments,sessionId:v.sessionId}}:params;
|
|
59
|
+
const key=keyFor(target),c=v.control;
|
|
60
|
+
if(!key||!c||!Number.isSafeInteger(c.controlVersion)||c.controlVersion<=0||!['web','client'].includes(c.editor?.kind)
|
|
61
|
+
||typeof c.editor.isCurrentClient!=='boolean'||c.editor.kind==='web'&&c.editor.isCurrentClient)return v;
|
|
62
|
+
const old=versions.get(key),version=c.controlVersion,owned=c.editor.kind==='client'&&c.editor.isCurrentClient;
|
|
63
|
+
const authorityRead=directory?.tools.get(params.name)?._meta?.['promptframe.role']==='control-read';
|
|
64
|
+
if(!old||version>old.version)boundedSet(versions,key,{version,owned,needsRead:false,authorityOrder:order});
|
|
65
|
+
else if(version===old.version&&order>=(old.authorityOrder??0)){
|
|
66
|
+
const freshRead=!result.isError&&authorityRead&&order>(old.invalidatedAt??0);
|
|
67
|
+
if(freshRead)boundedSet(versions,key,{version,owned,needsRead:false,authorityOrder:order});
|
|
68
|
+
else if(old.owned!==owned)boundedSet(versions,key,{...old,owned:false,needsRead:true,invalidatedAt:++sequence});
|
|
69
|
+
// A normal same-generation result cannot erase a newer error or conflict.
|
|
67
70
|
}
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
}
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
}
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
}
|
|
120
|
-
}
|
|
121
|
-
outgoing = { ...params, arguments: { ...params.arguments, controlVersion } };
|
|
71
|
+
return v;
|
|
72
|
+
}
|
|
73
|
+
async function send(params,binding){
|
|
74
|
+
await binding?.assertCurrent();
|
|
75
|
+
const order=++sequence,result=assertMcpResponseBudget(await client.callTool(params,undefined,{timeout:60000}));
|
|
76
|
+
await binding?.assertCurrent();
|
|
77
|
+
return {result,trusted:remember(params,result,order)};
|
|
78
|
+
}
|
|
79
|
+
async function listTools(){
|
|
80
|
+
const order=++sequence,result=assertMcpResponseBudget(await client.listTools());
|
|
81
|
+
if(result.tools.some(tool=>!accesses.has(tool._meta?.['promptframe.access'])))throw new CreationClientError('creation.upgrade_required');
|
|
82
|
+
if(!directory||order>=directory.order)directory={tools:new Map(result.tools.map(t=>[t.name,t])),order};
|
|
83
|
+
catalog('outer',result._meta?.['promptframe.catalogVersion'],order);
|
|
84
|
+
return {...result,tools:result.tools.map(tool=>{
|
|
85
|
+
const p=tool.inputSchema.properties;
|
|
86
|
+
const {controlVersion:_managed,...properties}=p??{};
|
|
87
|
+
return {...tool,inputSchema:{...tool.inputSchema,properties:{...properties,...(host.kind==='claude-code'?{
|
|
88
|
+
[CLAUDE_HOST_PROOF]:{type:'string',pattern:'^[a-f0-9]{64}$',description:'由当前宿主hook填入的单次身份凭证;请保留,不自行填写。'}
|
|
89
|
+
}:{})},...(tool.inputSchema.required
|
|
90
|
+
?{required:tool.inputSchema.required.filter(name=>name!=='controlVersion')}:{})}};
|
|
91
|
+
})};
|
|
92
|
+
}
|
|
93
|
+
async function ensureDirectory(){
|
|
94
|
+
if(!directory){directoryRead??=listTools().finally(()=>{directoryRead=undefined;});await directoryRead;}
|
|
95
|
+
}
|
|
96
|
+
function role(name){
|
|
97
|
+
const found=[...directory.tools.values()].filter(t=>t._meta?.['promptframe.role']===name);
|
|
98
|
+
if(found.length!==1)throw new CreationClientError('creation.upgrade_required');return found[0].name;
|
|
99
|
+
}
|
|
100
|
+
async function controlRead(params,key,binding){
|
|
101
|
+
if(!inflight.has(key)){
|
|
102
|
+
const pending=send({name:role('control-read'),_meta:params._meta,
|
|
103
|
+
arguments:{projectId:params.arguments.projectId,sessionId:params.arguments.sessionId,pageSize:1}},binding)
|
|
104
|
+
.finally(()=>{if(inflight.get(key)===pending)inflight.delete(key);});
|
|
105
|
+
inflight.set(key,pending);
|
|
106
|
+
}
|
|
107
|
+
const observation=await inflight.get(key);if(observation.result.isError)return observation.result;
|
|
108
|
+
if(!observation.trusted||!versions.has(key)||versions.get(key).needsRead)throw new CreationClientError('creation.control_unverified');
|
|
109
|
+
}
|
|
110
|
+
async function knowledgeRead(kind,method,raw={}){
|
|
111
|
+
if(!upstream[kind])throw new CreationClientError('creation.knowledge_unsupported');
|
|
112
|
+
const params=hostParameters(raw,host.kind==='claude-code'?{kind:host.kind}:host,'independent-read'),order=++sequence;
|
|
113
|
+
const result=assertMcpResponseBudget(await client[method](params,undefined,{timeout:60000}));
|
|
114
|
+
const version=result._meta?.[kind==='resources'&&method==='listResources'
|
|
115
|
+
?'promptframe.guideDirectoryVersion':'promptframe.guideVersion'];
|
|
116
|
+
const key=JSON.stringify([kind,method,raw.uri??raw.arguments?.projectId??null]);
|
|
117
|
+
if(digestPattern.test(version??'')){
|
|
118
|
+
const old=knowledgeVersions.get(key);
|
|
119
|
+
if(!old||order>=old.order){
|
|
120
|
+
boundedSet(knowledgeVersions,key,{version,order});
|
|
121
|
+
if(old&&old.version!==version)Promise.resolve().then(()=>onKnowledgeChange(kind)).catch(()=>{});
|
|
122
122
|
}
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
},
|
|
128
|
-
|
|
123
|
+
}
|
|
124
|
+
return result;
|
|
125
|
+
}
|
|
126
|
+
return {listTools,knowledgeCapabilities:{...(upstream.resources?{resources:{listChanged:true}}:{}),
|
|
127
|
+
...(upstream.prompts?{prompts:{listChanged:true}}:{})},
|
|
128
|
+
listResources:params=>knowledgeRead('resources','listResources',params),
|
|
129
|
+
listResourceTemplates:params=>knowledgeRead('resources','listResourceTemplates',params),
|
|
130
|
+
readResource:params=>knowledgeRead('resources','readResource',params),
|
|
131
|
+
listPrompts:params=>knowledgeRead('prompts','listPrompts',params),
|
|
132
|
+
getPrompt:params=>knowledgeRead('prompts','getPrompt',params),async call(raw){
|
|
133
|
+
for(const field of ['threadId','controller','clientDigest','token','controlVersion'])if(Object.hasOwn(raw.arguments??{},field))
|
|
134
|
+
throw new CreationClientError('creation.transport_authority_managed_by_bridge');
|
|
135
|
+
let binding={host,arguments:raw.arguments,assertCurrent:async()=>{}};
|
|
136
|
+
if(host.kind==='claude-code'){
|
|
137
|
+
if(hostSession)binding=await hostSession.begin(raw);
|
|
138
|
+
else if(raw.arguments?.[CLAUDE_HOST_PROOF]!==undefined)throw new CreationClientError('creation.host_identity_invalid');
|
|
139
|
+
else binding={host:{kind:'claude-code'},arguments:raw.arguments,assertCurrent:async()=>{}};
|
|
140
|
+
if(binding.epoch!==hostEpoch){versions.clear();controllers.clear();inflight.clear();hostEpoch=binding.epoch;}
|
|
141
|
+
}else if(Object.hasOwn(raw.arguments??{},CLAUDE_HOST_PROOF))throw new CreationClientError('creation.transport_authority_managed_by_bridge');
|
|
142
|
+
raw={...raw,arguments:binding.arguments};
|
|
143
|
+
await ensureDirectory();await binding.assertCurrent();const definition=directory.tools.get(raw.name);
|
|
144
|
+
if(!definition)throw new CreationClientError('creation.tool_unavailable');
|
|
145
|
+
const access=definition._meta['promptframe.access'],managed=Object.hasOwn(definition.inputSchema.properties??{},'controlVersion');
|
|
146
|
+
// Resolve parameter-dependent access before requiring a controller. A
|
|
147
|
+
// missing host UUID must not block an independently authorized read.
|
|
148
|
+
const params=hostParameters(raw,binding.host,'independent-read');let effectiveAccess=access,resolvedControl;
|
|
149
|
+
if(definition._meta['promptframe.resolveAccess']==='target'){
|
|
150
|
+
const {projectId,sessionId,tool,arguments:input}=params.arguments??{};
|
|
151
|
+
if(typeof tool!=='string'||!input||typeof input!=='object'||Array.isArray(input))throw new CreationClientError('creation.request_invalid');
|
|
152
|
+
const observed=await send({name:role('describe-target'),_meta:params._meta,arguments:{projectId,sessionId,tool,arguments:input}},binding);
|
|
153
|
+
if(observed.result.isError)return observed.result;
|
|
154
|
+
const resolved=observed.trusted?.resolvedAccess;
|
|
155
|
+
if(resolved?.tool!==tool||resolved.argumentsDigest!==argumentsDigest(input)||!accesses.has(resolved.access))throw new CreationClientError('creation.access_unverified');
|
|
156
|
+
effectiveAccess=resolved.access;
|
|
157
|
+
resolvedControl=observed.trusted?.control;
|
|
158
|
+
}
|
|
159
|
+
hostParameters(raw,binding.host,effectiveAccess);
|
|
160
|
+
const key=keyFor(params);let outgoing=params;
|
|
161
|
+
if(managed){
|
|
162
|
+
if(!key){
|
|
163
|
+
if(effectiveAccess!=='independent-read'||!Number.isSafeInteger(resolvedControl?.controlVersion)||resolvedControl.controlVersion<=0)
|
|
164
|
+
throw new CreationClientError('creation.control_unverified');
|
|
165
|
+
outgoing={...params,arguments:{...params.arguments,controlVersion:resolvedControl.controlVersion}};
|
|
166
|
+
}else{let entry=versions.get(key);
|
|
167
|
+
if(!entry||entry.needsRead){const denied=await controlRead(params,key,binding);if(denied)return denied;entry=versions.get(key);}
|
|
168
|
+
if(effectiveAccess!=='independent-read'&&!entry.owned)throw new CreationClientError('creation.editor_not_current');
|
|
169
|
+
outgoing={...params,arguments:{...params.arguments,controlVersion:entry.version}};
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
const dispatched=key&&versions.get(key);
|
|
173
|
+
const invalidate=()=>{
|
|
174
|
+
if(host.kind==='claude-code'&&binding.epoch!==hostEpoch)return;
|
|
175
|
+
const current=key&&versions.get(key);
|
|
176
|
+
if(dispatched&¤t&¤t.version<=dispatched.version)
|
|
177
|
+
boundedSet(versions,key,{...current,needsRead:true,invalidatedAt:++sequence});
|
|
178
|
+
};
|
|
179
|
+
let response;
|
|
180
|
+
try{response=await send(outgoing,binding);}catch(error){invalidate();throw error;}
|
|
181
|
+
if(response.result.isError)invalidate();
|
|
182
|
+
return response.result;
|
|
183
|
+
}};
|
|
129
184
|
}
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
import {CreationClientError} from './credentials.mjs';
|
|
2
|
+
|
|
3
|
+
export function hostClientName(savedName,host){
|
|
4
|
+
return ['Codex PromptFrame','Claude Code PromptFrame'].includes(savedName)
|
|
5
|
+
?host.kind==='claude-code'?'Claude Code PromptFrame':'Codex PromptFrame':savedName;
|
|
6
|
+
}
|
|
7
|
+
|
|
8
|
+
export 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
|
+
// Select the transport kind, not a controller. Claude's startup environment
|
|
11
|
+
// can remain stale after /clear; only a current host-hook call binds its UUID.
|
|
12
|
+
export function resolveHostIdentity({host,env=process.env}={}){
|
|
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
|
+
return Object.freeze({kind});
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
export function hostParameters(params,host,access){
|
|
20
|
+
const meta=params._meta??{};
|
|
21
|
+
if(Object.keys(meta).some(key=>key.startsWith('promptframe.')||['controlVersion','controller','clientDigest','token','catalogVersion','platformDigest'].includes(key)))
|
|
22
|
+
throw new CreationClientError('creation.transport_authority_managed_by_bridge');
|
|
23
|
+
if(host.kind==='claude-code'){
|
|
24
|
+
if(Object.hasOwn(meta,'threadId'))throw new CreationClientError('creation.transport_authority_managed_by_bridge');
|
|
25
|
+
if(!host.threadId){if(access==='independent-read')return params;throw new CreationClientError('creation.host_identity_unavailable');}
|
|
26
|
+
return {...params,_meta:{...meta,threadId:host.threadId}};
|
|
27
|
+
}
|
|
28
|
+
if(meta.threadId===undefined){
|
|
29
|
+
if(access==='independent-read')return params;
|
|
30
|
+
throw new CreationClientError('creation.host_identity_required');
|
|
31
|
+
}
|
|
32
|
+
if(typeof meta.threadId!=='string'||!threadFormat.test(meta.threadId))throw new CreationClientError('creation.host_identity_invalid');
|
|
33
|
+
return params;
|
|
34
|
+
}
|
|
@@ -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'}:{})}});}
|
|
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
|
+
}
|