@promptframe/creation 0.3.12 → 0.3.14

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,7 +1,7 @@
1
1
  {
2
2
  "schemaVersion": "creation-install-guidance/v1",
3
3
  "package": "@promptframe/creation",
4
- "version": "0.3.12",
4
+ "version": "0.3.14",
5
5
  "hosts": [
6
6
  {
7
7
  "kind": "codex",
@@ -28,6 +28,20 @@
28
28
  "{{endpoint}}"
29
29
  ],
30
30
  "nextSession": "在同一主机开始新的 Claude Code session;桌面版远程连接 WSL 时在该 WSL 安装。"
31
+ },
32
+ {
33
+ "kind": "antigravity",
34
+ "name": "Antigravity",
35
+ "minimumBridge": "0.3.13",
36
+ "requirements": "Node.js 20+ 与支持本地插件及 PreToolUse 的 Google Antigravity;在支持 POSIX 文件权限的宿主安装",
37
+ "commandArgs": [
38
+ "connect",
39
+ "--host",
40
+ "antigravity",
41
+ "--endpoint",
42
+ "{{endpoint}}"
43
+ ],
44
+ "nextSession": "在同一主机打开新的 Antigravity 对话(或在 Customizations 确认 promptframe-creation 插件已启用)。"
31
45
  }
32
46
  ],
33
47
  "versionInstructions": "比较已安装版本:同版本复用,更新版本不降级;待升级或 Node 不可用时按明确指引处理,不把旧版复用当作升级成功。",
@@ -6,7 +6,7 @@
6
6
 
7
7
  <!-- creation-install-command -->
8
8
  ```bash
9
- npx --yes @promptframe/creation@0.3.12 connect --endpoint <Studio提供的API地址>
9
+ npx --yes @promptframe/creation@0.3.14 connect --endpoint <Studio提供的API地址>
10
10
  ```
11
11
  <!-- /creation-install-command -->
12
12
 
@@ -26,7 +26,7 @@ npx --yes @promptframe/creation@0.3.12 connect --endpoint <Studio提供的API地
26
26
 
27
27
  <!-- creation-install-command -->
28
28
  ```bash
29
- npx --yes @promptframe/creation@0.3.12 connect --host claude-code --endpoint <Studio提供的API地址>
29
+ npx --yes @promptframe/creation@0.3.14 connect --host claude-code --endpoint <Studio提供的API地址>
30
30
  ```
31
31
  <!-- /creation-install-command -->
32
32
 
@@ -38,6 +38,20 @@ CLI 优先使用 PATH 中的 Claude;桌面版远程连接 WSL 时,也识别
38
38
 
39
39
  启动帮助明确不提供插件命令时,安装器使用官方 user-scope MCP 登记并准备两份用户 Skill。返回 `installationMode: mcp-and-skills`、`pluginInstalled: false` 与实际 Skill 名称;不同 profile 分开命名,原凭据保持。MCP 写后从本地配置核回,不通过 `mcp list/get` 启动健康检查。已有陌生 MCP/Skill 或未确认的插件安装不会转到备用路径;备用 MCP 的回程未知也只核原身份,不重复 add。以后宿主增加插件命令时保留现有备用登记,避免同一 profile 两份连接。
40
40
 
41
+ ## Antigravity 接入
42
+
43
+ 在支持 POSIX 文件权限并运行 Google Antigravity 的主机上打开终端,使用 Studio 提供的 API 地址。
44
+
45
+ <!-- creation-install-command -->
46
+ ```bash
47
+ npx --yes @promptframe/creation@0.3.14 connect --host antigravity --endpoint <Studio提供的API地址>
48
+ ```
49
+ <!-- /creation-install-command -->
50
+
51
+ 安装后检查 Antigravity 的 Customizations 中是否启用 PromptFrame Creation,再打开新对话。插件通过 `PreToolUse` 将调用绑定到实际对话,两个 Skill 和 MCP 工具由宿主加载。首次授权在终端隐藏输入,已有有效授权可复用。
52
+
53
+ 0.3.14 支持 Antigravity 默认的懒加载 MCP 调用。已有插件需重跑本段命令以更新注册的 hook,再开独立对话。如果安装报告 `installation.legacy_mcp_entry_requires_review`,在 Antigravity 的 MCP 设置核对清单所列的旧手工 PromptFrame 条目,移除冲突条目后重试。安装器保留全局文件和其他 MCP 配置。
54
+
41
55
  ## 环境与账号
42
56
 
43
57
  默认凭据沿用 `$XDG_CONFIG_HOME/promptframe-creation/credentials.json`(未配置 XDG 时位于用户 `.config`)。旧的 `PROMPTFRAME_CREATION_CONFIG` 仍可显式引用安全文件。
@@ -46,7 +60,7 @@ CLI 优先使用 PATH 中的 Claude;桌面版远程连接 WSL 时,也识别
46
60
 
47
61
  <!-- creation-install-command -->
48
62
  ```bash
49
- npx --yes @promptframe/creation@0.3.12 connect --profile work-account --endpoint <另一环境API地址>
63
+ npx --yes @promptframe/creation@0.3.14 connect --profile work-account --endpoint <另一环境API地址>
50
64
  ```
51
65
  <!-- /creation-install-command -->
52
66
 
@@ -2,6 +2,7 @@ import path from 'node:path';
2
2
  import { CreationClientError, readCredentials, normalizeEndpoint } from './credentials.mjs';
3
3
  import { connectPlatform, connectionAccountIdentity } from './connection.mjs';
4
4
  import { createHostCallBridge, resolveHostCallBinding, hostParameters } from './host-context.mjs';
5
+ import { isHookProofHost } from './host-identity.mjs';
5
6
  import { CLAUDE_HOST_PROOF } from './claude-host-session.mjs';
6
7
  import { localAccountsRoot, localAccountKey, localAgentDigest, localCredentialDigest, localReferenceId,
7
8
  listLocalAccounts, readLocalAuthorizations, readSelectedLocalAccount, selectLocalAccount } from './local-accounts.mjs';
@@ -22,7 +23,7 @@ function localTool(name,host) {
22
23
  identityKey: {type:'string',pattern:'^[a-f0-9]{64}-[a-f0-9]{64}$'},
23
24
  referenceId: {type:'string',pattern:'^sha256:[a-f0-9]{64}$',description:'同一账号有多份创作授权时可明确选择列表中的引用。'},
24
25
  } : {};
25
- if(host.kind==='claude-code')properties[CLAUDE_HOST_PROOF]={type:'string',pattern:'^[a-f0-9]{64}$',description:'由当前宿主hook填入,保留原值。'};
26
+ if(isHookProofHost(host.kind))properties[CLAUDE_HOST_PROOF]={type:'string',pattern:'^[a-f0-9]{64}$',description:'由当前宿主hook填入,保留原值。'};
26
27
  return {name,description:name===listName?'列出本机已登记账号的安全摘要和缺少的授权类型,不返回凭据或本机路径。'
27
28
  :'只为当前宿主会话选择本机已授权账号;不切换其它Agent,不申请编辑权或重放业务。',
28
29
  inputSchema:{type:'object',properties,additionalProperties:false,...(name===selectName?{required:['identityKey']}:{})},
@@ -43,7 +44,7 @@ export function createAccountAwareBridge(defaultClient,{credentials,configFile,h
43
44
  function caller(raw,binding,required=false){
44
45
  const params={...raw,arguments:binding.arguments};
45
46
  hostParameters(params,binding.host,required?'authority':'independent-read');
46
- const sessionId=binding.host.kind==='claude-code'?binding.host.threadId:params._meta?.threadId;
47
+ const sessionId=isHookProofHost(binding.host.kind)?binding.host.threadId:params._meta?.threadId;
47
48
  return sessionId?{kind:binding.host.kind,sessionId}:undefined;
48
49
  }
49
50
  async function context(identity,agent,referenceId){
@@ -0,0 +1,210 @@
1
+ import {constants} from 'node:fs';
2
+ import {open,mkdir,lstat,rename,unlink,rmdir} from 'node:fs/promises';
3
+ import path from 'node:path';
4
+ import {homedir} from 'node:os';
5
+ import {createHash,randomBytes} from 'node:crypto';
6
+ import {CreationClientError} from './credentials.mjs';
7
+ import {CLAUDE_HOST_PROOF} from './claude-host-session.mjs';
8
+ import {threadFormat} from './host-identity.mjs';
9
+
10
+ const hex=/^[0-9a-f]{64}$/;
11
+ const TICKET_TTL_MS=120_000;
12
+ const SESSION_TTL_MS=24*60*60*1000;
13
+ const MAX_TICKETS=256;
14
+ const MAX_SESSIONS=256;
15
+ const DEFAULT_SERVER='promptframe-creation_promptframe-creation';
16
+ const mcpToolName=/^[A-Za-z0-9_.:-]{1,200}$/;
17
+ const error=code=>new CreationClientError('creation.'+code);
18
+ const canonical=value=>{
19
+ if(value===null||typeof value==='string'||typeof value==='boolean'||typeof value==='number'&&Number.isFinite(value))return JSON.stringify(value);
20
+ if(Array.isArray(value))return '['+value.map(canonical).join(',')+']';
21
+ if(value&&typeof value==='object'&&[Object.prototype,null].includes(Object.getPrototypeOf(value)))
22
+ return '{'+Object.keys(value).sort().map(key=>JSON.stringify(key)+':'+canonical(value[key])).join(',')+'}';
23
+ throw error('request_invalid');
24
+ };
25
+ const digest=value=>createHash('sha256').update(canonical(value)).digest('hex');
26
+ const withoutProof=args=>Object.fromEntries(Object.entries(args??{}).filter(([key])=>key!==CLAUDE_HOST_PROOF));
27
+
28
+ function objectArgs(value){
29
+ return value&&typeof value==='object'&&!Array.isArray(value)?value:null;
30
+ }
31
+ function promptFrameCall(toolCall,serverName){
32
+ if(typeof toolCall?.name!=='string')return null;
33
+ const args=objectArgs(toolCall.args)??{};
34
+ if(toolCall.name==='call_mcp_tool'){
35
+ if(args.ServerName!==serverName||typeof args.ToolName!=='string'||!mcpToolName.test(args.ToolName))return null;
36
+ const inner=args.Arguments===undefined?{}:objectArgs(args.Arguments);
37
+ return inner?{name:args.ToolName,args:inner,lazy:true}:null;
38
+ }
39
+ // Match the namespaced server, the former eager prefix, or a native
40
+ // PromptFrame tool name already reduced by the host.
41
+ const namespacedPrefix=`mcp_${serverName}_`,oldPrefix=`mcp_${serverName.split('_')[0]}_`;
42
+ if(toolCall.name.startsWith(namespacedPrefix)){
43
+ const name=toolCall.name.slice(namespacedPrefix.length);
44
+ return mcpToolName.test(name)?{name,args,lazy:false}:null;
45
+ }
46
+ const name=toolCall.name.startsWith(oldPrefix)?toolCall.name.slice(oldPrefix.length):toolCall.name;
47
+ return /^(?:platform_|promptframe_local_)[a-z0-9_]+$/i.test(name)&&mcpToolName.test(name)?{name,args,lazy:false}:null;
48
+ }
49
+ function sessionId(value){
50
+ return typeof value==='string'&&threadFormat.test(value)?value.toLowerCase():null;
51
+ }
52
+ function transcriptDigest(input){
53
+ const file=input?.transcriptPath;
54
+ return typeof file==='string'&&file.length<=4096&&path.isAbsolute(file)?digest(path.normalize(file)):null;
55
+ }
56
+ function toolNameMatches(hookToolName,bridgeToolName){
57
+ if(typeof hookToolName!=='string'||typeof bridgeToolName!=='string'||!bridgeToolName)return false;
58
+ if(hookToolName===bridgeToolName)return true;
59
+ return hookToolName.endsWith('_'+bridgeToolName)||hookToolName.endsWith(':'+bridgeToolName);
60
+ }
61
+
62
+ async function privateDirectory(directory){
63
+ try{await mkdir(directory,{recursive:true,mode:0o700});}catch(e){if(e.code!=='EEXIST')throw e;}
64
+ const info=await lstat(directory);
65
+ if(!info.isDirectory()||info.isSymbolicLink()||info.uid!==process.getuid?.()||(info.mode&0o077))throw error('host_identity_unavailable');
66
+ }
67
+ async function privateRead(file){
68
+ let handle;try{
69
+ handle=await open(file,constants.O_RDONLY|constants.O_NOFOLLOW);const info=await handle.stat();
70
+ if(!info.isFile()||info.uid!==process.getuid?.()||(info.mode&0o077)||info.size>262144)throw error('host_identity_unavailable');
71
+ return JSON.parse(await handle.readFile('utf8'));
72
+ }catch(e){if(e.code==='ENOENT')return null;throw e;}finally{await handle?.close();}
73
+ }
74
+
75
+ export function antigravityConfigRoot(env=process.env){
76
+ return path.resolve(env.ANTIGRAVITY_CONFIG_DIR??env.GEMINI_CONFIG_DIR??path.join(homedir(),'.gemini','config'));
77
+ }
78
+
79
+ /** Local host provenance for Antigravity. Supports multiple concurrent
80
+ * conversations sharing one plugin MCP server process by binding each
81
+ * one-use PreToolUse ticket to its conversationId UUID and exact arguments. */
82
+ export async function createAntigravityHostSession({configFile,env=process.env,root,serverName=DEFAULT_SERVER,now=()=>Date.now()}={}){
83
+ const base=root??path.join(antigravityConfigRoot(env),'promptframe-host-sessions');
84
+ const namespace=path.join(base,digest(path.resolve(configFile)));
85
+ const stateFile=path.join(namespace,'state.json');
86
+
87
+ async function readState(){
88
+ const value=await privateRead(stateFile);
89
+ if(!value)return {contractVersion:'antigravity-host-session/v1',tickets:{}};
90
+ if(value.contractVersion!=='antigravity-host-session/v1'||!value.tickets||typeof value.tickets!=='object'
91
+ ||Array.isArray(value.tickets)||Object.keys(value.tickets).length>MAX_TICKETS+32)throw error('host_identity_unavailable');
92
+ return value;
93
+ }
94
+
95
+ async function transaction(work){
96
+ await privateDirectory(base);await privateDirectory(namespace);
97
+ const lock=path.join(namespace,'write.lock');let acquired=false;
98
+ for(let count=0;count<100;count++)try{await mkdir(lock,{mode:0o700});acquired=true;break;}
99
+ catch(e){if(e.code!=='EEXIST')throw e;await new Promise(resolve=>setTimeout(resolve,10));}
100
+ if(!acquired)throw error('host_identity_unavailable');
101
+ let temporary;
102
+ try{
103
+ const current=await readState();
104
+ const next=await work(current);
105
+ if(next===undefined)return;
106
+ const body=JSON.stringify(next);if(Buffer.byteLength(body)>262144)throw error('host_identity_unavailable');
107
+ temporary=path.join(namespace,'state-'+randomBytes(16).toString('hex')+'.partial');
108
+ const file=await open(temporary,constants.O_WRONLY|constants.O_CREAT|constants.O_EXCL|constants.O_NOFOLLOW,0o600);
109
+ try{await file.writeFile(body);await file.sync();}finally{await file.close();}
110
+ await rename(temporary,stateFile);temporary=undefined;
111
+ const directory=await open(namespace,constants.O_RDONLY|constants.O_DIRECTORY|constants.O_NOFOLLOW);
112
+ try{await directory.sync();}finally{await directory.close();}
113
+ }finally{if(temporary)await unlink(temporary).catch(()=>{});await rmdir(lock).catch(()=>{});}
114
+ }
115
+
116
+ function pruneTickets(tickets,currentTime){
117
+ const kept={};
118
+ for(const [k,v] of Object.entries(tickets)){
119
+ if(v&&typeof v==='object'&&typeof v.expiresAt==='number'&&v.expiresAt>currentTime
120
+ &&typeof v.conversationId==='string'&&threadFormat.test(v.conversationId))kept[k]=v;
121
+ }
122
+ const keys=Object.keys(kept);
123
+ while(keys.length>=MAX_TICKETS)delete kept[keys.shift()];
124
+ return kept;
125
+ }
126
+
127
+ function pruneSessions(sessions,currentTime){
128
+ const active=Object.entries(sessions??{}).filter(([id,value])=>sessionId(id)
129
+ &&Number.isSafeInteger(value?.expiresAt)&&value.expiresAt>currentTime);
130
+ return Object.fromEntries(active.slice(-MAX_SESSIONS));
131
+ }
132
+
133
+ function bindSession(sessions,id,transcript,currentTime){
134
+ const previous=sessions[id];
135
+ delete sessions[id];
136
+ sessions[id]={transcriptDigest:transcript??previous?.transcriptDigest??null,expiresAt:currentTime+SESSION_TTL_MS};
137
+ return pruneSessions(sessions,currentTime);
138
+ }
139
+
140
+ async function begin(raw){
141
+ const proof=raw.arguments?.[CLAUDE_HOST_PROOF],args=withoutProof(raw.arguments);
142
+ if(proof===undefined)return {host:{kind:'antigravity'},assertCurrent:async()=>{},arguments:args};
143
+ if(typeof proof!=='string'||!hex.test(proof))throw error('host_identity_invalid');
144
+ const argsHash=digest(args),currentTime=now();
145
+ let accepted;
146
+ try{
147
+ await transaction(current=>{
148
+ const ticket=current.tickets[proof];
149
+ if(!ticket||ticket.expiresAt<=currentTime||ticket.argsDigest!==argsHash
150
+ ||!(ticket.exactToolName?ticket.toolName===raw.name:toolNameMatches(ticket.toolName,raw.name))
151
+ ||!threadFormat.test(ticket.conversationId??''))
152
+ throw error('host_identity_invalid');
153
+ accepted={threadId:ticket.conversationId.toLowerCase()};
154
+ delete current.tickets[proof];
155
+ current.tickets=pruneTickets(current.tickets,currentTime);
156
+ return current;
157
+ });
158
+ }catch(e){if(e instanceof CreationClientError)throw e;throw error('host_identity_unavailable');}
159
+ return {host:{kind:'antigravity',threadId:accepted.threadId},arguments:args,assertCurrent:async()=>{}};
160
+ }
161
+
162
+ async function hook(input,event=input?.hookEventName??'PreToolUse'){
163
+ if(input?.hookEventName!==undefined&&input.hookEventName!==event)return {};
164
+ const id=sessionId(input?.conversationId),transcript=transcriptDigest(input),currentTime=now();
165
+ if(event==='SessionStart'){
166
+ if(id)await transaction(current=>{
167
+ current.sessions=bindSession(pruneSessions(current.sessions,currentTime),id,transcript,currentTime);
168
+ return current;
169
+ });
170
+ return {};
171
+ }
172
+ if(event!=='PreToolUse')return {};
173
+ const call=promptFrameCall(input?.toolCall,serverName);
174
+ if(!call)return {decision:'allow'};
175
+ const args=withoutProof(call.args),argsHash=digest(args);
176
+ let token;
177
+ await transaction(current=>{
178
+ const sessions=pruneSessions(current.sessions,currentTime);
179
+ // SessionStart is a fallback only for an exact, unambiguous transcript.
180
+ // A shared bridge must never choose the most recently opened conversation.
181
+ const matches=!id&&input?.conversationId===undefined&&transcript
182
+ ?Object.keys(sessions).filter(key=>sessions[key].transcriptDigest===transcript):[];
183
+ const conversationId=id??(matches.length===1?matches[0]:null);
184
+ if(!conversationId)return;
185
+ const tickets=pruneTickets(current.tickets,currentTime);
186
+ token=randomBytes(32).toString('hex');
187
+ tickets[token]={toolName:call.name,exactToolName:true,argsDigest:argsHash,conversationId,expiresAt:currentTime+TICKET_TTL_MS};
188
+ return {contractVersion:'antigravity-host-session/v1',tickets,sessions:bindSession(sessions,conversationId,transcript,currentTime)};
189
+ });
190
+ if(!token)return Object.hasOwn(call.args,CLAUDE_HOST_PROOF)
191
+ ?{decision:'deny',reason:'Missing valid Antigravity conversationId for PromptFrame proof.'}:{decision:'allow'};
192
+ return {decision:'allow',overwrite:call.lazy
193
+ ?{Arguments:{...args,[CLAUDE_HOST_PROOF]:token}}:{[CLAUDE_HOST_PROOF]:token}};
194
+ }
195
+
196
+ return {begin,hook};
197
+ }
198
+
199
+ export async function readAntigravityHookInput(input){
200
+ const chunks=[];let bytes=0;
201
+ for await(const value of input){const chunk=Buffer.isBuffer(value)?value:Buffer.from(value);bytes+=chunk.length;
202
+ if(bytes>2*1024*1024+65536)throw error('host_identity_invalid');chunks.push(chunk);}
203
+ return JSON.parse(new TextDecoder('utf-8',{fatal:true}).decode(Buffer.concat(chunks,bytes)));
204
+ }
205
+
206
+ export async function runAntigravityHostHook({configFile,serverName,event,input=process.stdin,output=process.stdout,env=process.env}={}){
207
+ const body=await readAntigravityHookInput(input);
208
+ const store=await createAntigravityHostSession({configFile,serverName,env});
209
+ output.write(JSON.stringify(await store.hook(body,event))+'\n');
210
+ }
@@ -0,0 +1,253 @@
1
+ import {lstat,mkdir,open,readFile,rename,rm} from 'node:fs/promises';
2
+ import {constants} from 'node:fs';
3
+ import {createHash,randomBytes} from 'node:crypto';
4
+ import {homedir} from 'node:os';
5
+ import path from 'node:path';
6
+ import {CreationClientError} from './credentials.mjs';
7
+ import {compareBridgeVersions} from './bridge-negotiation.mjs';
8
+ import {inspectRuntimePackage} from './runtime-package.mjs';
9
+ import {antigravityConfigRoot} from './antigravity-host-session.mjs';
10
+
11
+ const hash=b=>createHash('sha256').update(b).digest('hex');
12
+ class AntigravityInstallationError extends CreationClientError{
13
+ constructor(code,details){super('installation.'+code);this.details=details;}
14
+ }
15
+ export const antigravityInstallationDetails=error=>error instanceof AntigravityInstallationError?error.details:undefined;
16
+ const fail=(code,details)=>{throw new AntigravityInstallationError(code,details);};
17
+ const profileFormat=/^[a-z0-9][a-z0-9-]{0,39}$/;
18
+ const antigravityServerName=profile=>'promptframe-creation'+(profile==='default'?'':'-'+profile);
19
+ const object=value=>value!==null&&typeof value==='object'&&!Array.isArray(value);
20
+
21
+ function usesCreationBridge(server,{profile,configFile}){
22
+ if(!object(server)||typeof server.command!=='string'||!Array.isArray(server.args))return false;
23
+ const args=server.args;
24
+ const bridgeIndex=args.indexOf('bridge');
25
+ if(bridgeIndex<0)return false;
26
+ const isCreationExecutable=value=>typeof value==='string'&&/^promptframe-creation(?:\.mjs|\.cmd|\.exe)?$/.test(path.win32.basename(value));
27
+ const command=path.win32.basename(server.command);
28
+ const bridgeLauncher=isCreationExecutable(command)||
29
+ (/^(?:node|nodejs|bun)(?:\.exe)?$/.test(command)&&isCreationExecutable(args[bridgeIndex-1]))||
30
+ (/^(?:npx|npm|pnpm|yarn|bunx)(?:\.cmd|\.exe)?$/.test(command)&&
31
+ typeof args[bridgeIndex-1]==='string'&&/^@promptframe\/creation(?:@[^\s]+)?$/.test(args[bridgeIndex-1]));
32
+ if(!bridgeLauncher)return false;
33
+
34
+ const configIndex=args.indexOf('--config',bridgeIndex+1);
35
+ const profileIndex=args.indexOf('--profile',bridgeIndex+1);
36
+ const configuredProfile=profileIndex<0?'default':args[profileIndex+1];
37
+ const configuredFile=configIndex>=0?args[configIndex+1]:configuredProfile==='default'?server.env?.PROMPTFRAME_CREATION_CONFIG:undefined;
38
+ if(typeof configuredFile==='string'&&path.isAbsolute(configuredFile))return path.resolve(configuredFile)===configFile;
39
+ return configuredProfile===profile;
40
+ }
41
+
42
+ export async function checkAntigravityMcpConflicts({profile='default',configFile,env=process.env}={}){
43
+ const mcpConfigFile=path.join(antigravityConfigRoot(env),'mcp_config.json');
44
+ const unreadable=()=>fail('antigravity_mcp_config_unreadable',{mcpConfigFile,
45
+ action:'Check that the Antigravity MCP configuration is readable and contains a valid JSON object, then retry connect.'});
46
+ let file;
47
+ try{file=await open(mcpConfigFile,constants.O_RDONLY|constants.O_NONBLOCK);}
48
+ catch(error){if(error.code==='ENOENT')return;unreadable();}
49
+ let config;
50
+ try{
51
+ const info=await file.stat();
52
+ if(!info.isFile()||info.size>4*1024*1024)unreadable();
53
+ config=JSON.parse(await file.readFile('utf8'));
54
+ }catch{unreadable();}finally{await file.close();}
55
+ if(!object(config)||config.mcpServers!==undefined&&!object(config.mcpServers))unreadable();
56
+ const serverName=antigravityServerName(profile);
57
+ const mcpServerNames=Object.entries(config.mcpServers??{})
58
+ .filter(([name,server])=>name===serverName||name===`${serverName}_${serverName}`
59
+ ||profile==='default'&&name==='promptframe'||usesCreationBridge(server,{profile,configFile}))
60
+ .map(([name])=>name);
61
+ if(mcpServerNames.length)fail('legacy_mcp_entry_requires_review',{mcpConfigFile,mcpServerNames,
62
+ action:'In Antigravity MCP settings, review the listed entries and remove the conflicting manual PromptFrame entries, then rerun connect with the existing Token.'});
63
+ }
64
+
65
+ function shellQuote(value){
66
+ return '"'+String(value).replace(/(["\\$`])/g,'\\$1')+'"';
67
+ }
68
+
69
+ export function antigravityPluginManifest({version,name='promptframe-creation',displayName='PromptFrame Creation'}){
70
+ return {
71
+ name,
72
+ displayName,
73
+ description:'PromptFrame video creation Skill and MCP bridge for Antigravity: inspect projects, plan shots, search/author components, preview and render videos.',
74
+ version,
75
+ repository:'https://github.com/ty-teams/promptframe-creation',
76
+ suggestedPrompts:[
77
+ '列出我在 PromptFrame 当前项目中的作品并读取最新状态',
78
+ '帮我在 PromptFrame 中规划并创建一个新的科普视频分镜',
79
+ '在组件市场搜索适合数据对比展示的可视化组件',
80
+ ],
81
+ };
82
+ }
83
+
84
+ export function antigravityMcpConfig({serverName,nodeCommand,runtimeRoot,configFile}){
85
+ return {
86
+ mcpServers:{
87
+ [serverName]:{
88
+ command:nodeCommand,
89
+ args:[path.join(runtimeRoot,'bin','promptframe-creation.mjs'),'bridge','--config',configFile,'--host','antigravity'],
90
+ },
91
+ },
92
+ };
93
+ }
94
+
95
+ export function antigravityHooksConfig({nodeCommand,runtimeRoot,configFile,serverName}){
96
+ const cliPath=path.join(runtimeRoot,'bin','promptframe-creation.mjs');
97
+ const command=[shellQuote(nodeCommand),shellQuote(cliPath),'antigravity-host-hook','--config',shellQuote(configFile),
98
+ '--mcp-server',shellQuote(`${serverName}_${serverName}`)].join(' ');
99
+ return {
100
+ 'promptframe-host-identity':{
101
+ SessionStart:[{type:'command',command:command+' --hook-event SessionStart',timeout:5}],
102
+ PreToolUse:[
103
+ {
104
+ matcher:'(.*promptframe.*|^platform_.*|^call_mcp_tool$)',
105
+ hooks:[{type:'command',command:command+' --hook-event PreToolUse',timeout:5}],
106
+ },
107
+ ],
108
+ },
109
+ };
110
+ }
111
+
112
+ async function readJsonOrNull(file){
113
+ try{return JSON.parse(await readFile(file,'utf8'));}catch(e){if(e.code==='ENOENT')return null;throw e;}
114
+ }
115
+ async function writeFileAtomic(file,content,mode=0o600){
116
+ await mkdir(path.dirname(file),{recursive:true,mode:0o700});
117
+ const tmp=file+'.'+randomBytes(8).toString('hex')+'.partial';
118
+ const fd=await open(tmp,'wx',mode);
119
+ try{await fd.writeFile(content);await fd.sync();}finally{await fd.close();}
120
+ await rename(tmp,file);
121
+ }
122
+ async function copyPackagePayload(payload,destRoot){
123
+ const tmp=destRoot+'.partial-'+randomBytes(8).toString('hex');
124
+ await mkdir(tmp,{recursive:true,mode:0o700});
125
+ try{
126
+ for(const file of payload.files){
127
+ const dest=path.join(tmp,...file.path.split('/'));
128
+ await mkdir(path.dirname(dest),{recursive:true,mode:0o700});
129
+ const fd=await open(dest,'wx',0o600);
130
+ try{await fd.writeFile(file.body);await fd.sync();}finally{await fd.close();}
131
+ }
132
+ await rename(tmp,destRoot);
133
+ }catch(e){
134
+ await rm(tmp,{recursive:true,force:true}).catch(()=>{});
135
+ throw e;
136
+ }
137
+ }
138
+
139
+ /** Install PromptFrame Creation as a native Antigravity plugin once.
140
+ * Subsequent bridge upgrades happen automatically on startup via
141
+ * runtime-bootstrap.mjs without requiring plugin reinstallation. */
142
+ export async function installForAntigravityUser({
143
+ sourceRoot,
144
+ profile='default',
145
+ configFile,
146
+ env=process.env,
147
+ nodeCommand=process.execPath,
148
+ signal,
149
+ }={}){
150
+ if(!profileFormat.test(profile))fail('profile_invalid');
151
+ if(!path.isAbsolute(configFile??''))fail('config_path_invalid');
152
+ signal?.throwIfAborted();
153
+ await checkAntigravityMcpConflicts({profile,configFile,env});
154
+ const payload=await inspectRuntimePackage(sourceRoot);
155
+ const serverName=antigravityServerName(profile);
156
+ const pluginDirName=serverName;
157
+ const dataRoot=path.resolve(env.XDG_DATA_HOME??path.join(homedir(),'.local','share'),'promptframe-creation',profile,'antigravity');
158
+ const versionRoot=path.join(dataRoot,'versions',payload.version);
159
+ const pluginsRoot=path.join(antigravityConfigRoot(env),'plugins');
160
+ const pluginDir=path.join(pluginsRoot,pluginDirName);
161
+ const markerFile=path.join(pluginDir,'promptframe-installation.json');
162
+
163
+ let pluginDirectoryExists=false;
164
+ try{
165
+ const status=await lstat(pluginDir);
166
+ if(!status.isDirectory()||status.isSymbolicLink())fail('managed_installation_invalid');
167
+ pluginDirectoryExists=true;
168
+ }catch(error){if(error.code!=='ENOENT')throw error;}
169
+ const existing=await readJsonOrNull(markerFile);
170
+ if(pluginDirectoryExists&&!existing)fail('managed_installation_invalid');
171
+ if(existing){
172
+ if(existing.host!=='antigravity'||existing.profile!==profile||existing.configFile!==configFile
173
+ ||typeof existing.version!=='string'||!/^\d+\.\d+\.\d+$/.test(existing.version))fail('managed_installation_invalid');
174
+ const cmp=compareBridgeVersions(existing.version,payload.version);
175
+ if(cmp>0){
176
+ return {registered:true,pluginInstalled:true,pluginEnabled:true,reused:true,host:'antigravity',
177
+ installationMode:'antigravity-plugin',profile,version:existing.version,requestedVersion:payload.version,
178
+ versionStatus:'newer_installed_kept',recordedRuntimeRetained:true,pluginDir,serverName,
179
+ skillsInstalled:true,skills:[{name:'creation-setup'},{name:'video-creation'}]};
180
+ }
181
+ if(cmp===0&&existing.payloadDigest===payload.payloadDigest&&existing.versionRoot===versionRoot){
182
+ return {registered:true,pluginInstalled:true,pluginEnabled:true,reused:true,host:'antigravity',
183
+ installationMode:'antigravity-plugin',profile,version:payload.version,requestedVersion:payload.version,
184
+ versionStatus:'already_current',recordedRuntimeRetained:false,pluginDir,serverName,
185
+ skillsInstalled:true,skills:[{name:'creation-setup'},{name:'video-creation'}]};
186
+ }
187
+ }
188
+
189
+ let versionExists=false;
190
+ try{const s=await lstat(versionRoot);versionExists=s.isDirectory()&&!s.isSymbolicLink();}catch(e){if(e.code!=='ENOENT')throw e;}
191
+ if(!versionExists){
192
+ await mkdir(path.dirname(versionRoot),{recursive:true,mode:0o700});
193
+ await copyPackagePayload(payload,versionRoot);
194
+ }
195
+ signal?.throwIfAborted();
196
+
197
+ if(!existing){
198
+ await mkdir(pluginsRoot,{recursive:true,mode:0o700});
199
+ await mkdir(pluginDir,{mode:0o700});
200
+ }
201
+ const pluginJson=JSON.stringify(antigravityPluginManifest({
202
+ version:payload.version,
203
+ name:pluginDirName,
204
+ displayName:profile==='default'?'PromptFrame Creation':'PromptFrame Creation ('+profile+')',
205
+ }),null,2)+'\n';
206
+ const mcpJson=JSON.stringify(antigravityMcpConfig({serverName,nodeCommand,runtimeRoot:versionRoot,configFile}),null,2)+'\n';
207
+ const hooksJson=JSON.stringify(antigravityHooksConfig({nodeCommand,runtimeRoot:versionRoot,configFile,serverName}),null,2)+'\n';
208
+
209
+ await writeFileAtomic(path.join(pluginDir,'plugin.json'),pluginJson,0o644);
210
+ await writeFileAtomic(path.join(pluginDir,'mcp_config.json'),mcpJson,0o600);
211
+ await writeFileAtomic(path.join(pluginDir,'hooks.json'),hooksJson,0o600);
212
+
213
+ const skillEntries=payload.files.filter(f=>f.path.startsWith('skills/')&&f.path.endsWith('/SKILL.md'));
214
+ for(const skill of skillEntries){
215
+ const dest=path.join(pluginDir,...skill.path.split('/'));
216
+ await writeFileAtomic(dest,skill.body,0o644);
217
+ }
218
+
219
+ const record={
220
+ contractVersion:'antigravity-plugin-installation/v1',
221
+ host:'antigravity',
222
+ profile,
223
+ configFile,
224
+ pluginDirName,
225
+ serverName,
226
+ version:payload.version,
227
+ versionRoot,
228
+ nodeCommand,
229
+ payloadDigest:payload.payloadDigest,
230
+ mcpDigest:hash(mcpJson),
231
+ hooksDigest:hash(hooksJson),
232
+ installedAt:new Date().toISOString(),
233
+ };
234
+ await writeFileAtomic(markerFile,JSON.stringify(record,null,2)+'\n',0o600);
235
+
236
+ return {
237
+ registered:true,
238
+ pluginInstalled:true,
239
+ pluginEnabled:true,
240
+ reused:false,
241
+ host:'antigravity',
242
+ installationMode:'antigravity-plugin',
243
+ profile,
244
+ version:payload.version,
245
+ requestedVersion:payload.version,
246
+ versionStatus:existing?'upgraded':'installed',
247
+ recordedRuntimeRetained:false,
248
+ pluginDir,
249
+ serverName,
250
+ skillsInstalled:true,
251
+ skills:skillEntries.map(s=>({name:s.path.split('/')[1]})),
252
+ };
253
+ }