@tomflow/chatloop-tools 0.4.17 → 0.4.19

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/README.md CHANGED
@@ -21,6 +21,8 @@ Usage: chatloop-tools start [desktop-commander|tunnel]
21
21
  Start all enabled tools or one.
22
22
  ```
23
23
 
24
+ **同 Chat 新接口(候选)**:`chat_loop_extension__start({projectId,mode:'adopt',confirmed:true})`(无 prompt)只尝试接管原 Chat,并由扩展自己检查 R/P 真实用户回合与版本。`mode:'adopt'` 与 `prompt` 互斥;从原 Chat 提出执行请求不能降级为新 Chat。
25
+
24
26
  MCP `chat_loop_extension__start` 入参为 `{projectId, prompt, confirmed:true}`,可选 `replaceBlockedSessionId` 仅用于在双重核验旧 Session `BLOCKED` 且新 projectId 不同的情况下显式开启**新任务**;不提供 `force`,不重发旧任务。`status` 保持只读,未知回执不自动重试。
25
27
 
26
28
  Extension Actions 委托 `@tomflow/chatloop-extension` 公共 CLI,不复制浏览器操作。具体安全边界和协议见 [Local Tools 产品文档](../../docs/local-tools.md),实际部署与已验证状态见 [CURRENT](../../context/CURRENT.md)。
@@ -35,3 +37,8 @@ npx --yes --package=@tomflow/chatloop-tools@latest chatloop-tools upgrade
35
37
  升级先独立安装新版本、核实 Supervisor 所有权与运行状态,再通过原 Supervisor 停止旧版、将 Tunnel MCP 启动命令固定到新版本并启动;不在 Tunnel 正处理 MCP 调用时直接自我重启。若返回 `BLOCKED`,先核对原任务回执,不要盲重试。`start` 全量入口在正常用户安装环境检测到版本差异时复用此流程;带隔离状态目录的测试不触发升级。详情见 [Local Tools 主文档](../../docs/local-tools.md)。
36
38
 
37
39
  **Start 长页面准备(0.4.17)**:私人 MCP `chat_loop_extension__start` 的 CLI 子调用等待窗口最多 330 秒,仅用于允许 Chrome 安全校验和 ChatGPT 编辑器自然就绪。超时仍返回不确定错误,不重新启动或重发,必须单独查询 Status。
40
+
41
+
42
+ **0.4.18 原有接口结构(历史候选)**:九个 Extension MCP 接口的名字、参数 Schema、CLI 映射和本机参数准入统一维护于 lib/extension-contract.mjs(纯契约、无进程副作用);extension-proxy.mjs 仅负责 npx 转发、超时和回执验证,Gateway 单独暴露一个安全限定 UUID 的 operation_status 查询。发布工具总数为 36:26 DC + 9 Extension + 1 Runtime 回执。发行/运行版本与源码候选需分开核验。
43
+
44
+ **源码候选 0.4.19(未发布)**:在不增加公开 Extension 工具数量的前提下,原 `chat_loop_extension__start` 增加只允许 `mode:adopt`、不含 prompt 的同 Chat 原地接管方式;可选 `chatUrl` 精确限制候选。真实 Chrome 正向链路、用户交互原生表单和 npm 正式发布仍须单独验收。
package/bin/cli.mjs CHANGED
@@ -5,7 +5,7 @@ import {randomUUID} from 'node:crypto';
5
5
  import {createRequire} from 'node:module';
6
6
  import {dirname,join} from 'node:path';
7
7
  import {fileURLToPath} from 'node:url';
8
- import {CONTRACT,ACTIONS,registry,ensurePrivateDir,paths,
8
+ import {lifecycleDeadlineMs,CONTRACT,ACTIONS,registry,ensurePrivateDir,paths,
9
9
  safeFallback,recoverStaleLock,exitCode,talk} from '../lib/control.mjs';
10
10
  import {runGateway} from '../lib/gateway.mjs';
11
11
  import {tunnelDoctor,runTunnel} from '../lib/tunnel.mjs';
@@ -95,7 +95,7 @@ async function runControl(action=command, params=extra){
95
95
  }
96
96
  // Real Desktop Commander cold startup can exceed 12s on loaded macOS.
97
97
  const req={contract:CONTRACT,requestId,action,scope:target?'tool':'all',
98
- deadlineMs:action==='start'||action==='restart'?25000:12000};
98
+ deadlineMs:lifecycleDeadlineMs(action)};
99
99
  if(target)req.toolId=target;
100
100
  let reply;
101
101
  try{
@@ -3,7 +3,7 @@ import {createRequire} from 'node:module';
3
3
  import {dirname,join} from 'node:path';
4
4
  import {mkdirSync,readFileSync} from 'node:fs';
5
5
  import {randomUUID} from 'node:crypto';
6
- import {paths,toolCallDeadlineMs} from '../control.mjs';
6
+ import {paths,toolCallDeadlineMs,PACKAGE_VERSION} from '../control.mjs';
7
7
 
8
8
  const require=createRequire(import.meta.url);
9
9
  const catalog=JSON.parse(readFileSync(new URL('../desktop-commander-tools.json',import.meta.url),'utf8'));
@@ -106,7 +106,7 @@ export function createMcpChildAdapter({records,log},options={}){
106
106
  const handshake=(async()=>{
107
107
  try{
108
108
  const info=await request(rec,'initialize',{protocolVersion:'2025-03-26',
109
- capabilities:{},clientInfo:{name:'chat-loop-local-tools',version:'0.4.4'}},null);
109
+ capabilities:{},clientInfo:{name:'chat-loop-local-tools',version:PACKAGE_VERSION}},null);
110
110
  if(!info?.protocolVersion)throw Object.assign(Error('Handshake failed'),{code:'MCP_HANDSHAKE_FAILED'});
111
111
  child.stdin.write(JSON.stringify({jsonrpc:'2.0',method:'notifications/initialized'})+'\n');
112
112
  const listed=await request(rec,'tools/list',{},null);
@@ -0,0 +1,55 @@
1
+ // INERT, opt-in MCP 2026-07-28 MRTR form probe.
2
+ // No browser actions, approvals, persistent state, or business side effects.
3
+ // The returned test selection MUST NOT authorize a real Chat Loop Start.
4
+ export const probeTool = Object.freeze({
5
+ name: 'chat_loop_test__approval_form',
6
+ description: 'TEST ONLY: display a native choice form. No approval, no Start, no persistence.',
7
+ inputSchema: {type:'object',properties:{},additionalProperties:false}
8
+ });
9
+ const names=['confirm','revise','reject','other'];
10
+ const options=[
11
+ {const:'confirm',title:'确认(仅测试,不批准任何真实任务)'},
12
+ {const:'revise',title:'需要修改(仅测试)'},
13
+ {const:'reject',title:'不通过(仅测试)'},
14
+ {const:'other',title:'自定义回答(仅测试)'}
15
+ ];
16
+ const failed=reason=>({resultType:'complete',isError:true,
17
+ content:[{type:'text',text:'FORM_PROBE_'+reason}]});
18
+ const completed=value=>({resultType:'complete',
19
+ content:[{type:'text',text:JSON.stringify({probeOnly:true, ...value})}]});
20
+ const supportsForm=caps=>!!caps?.elicitation
21
+ && (caps.elicitation.form!==undefined || Object.keys(caps.elicitation).length===0);
22
+ export function handleProbeForm(params={}) {
23
+ if(params?.arguments===null || typeof params?.arguments!=='object'
24
+ || Array.isArray(params.arguments) || Object.keys(params.arguments||{}).length)
25
+ return failed('INVALID_ARGUMENT');
26
+ // MCP 2026-07-28 requires per-request client capabilities. Never elicit
27
+ // input unless the client explicitly declares support for form mode.
28
+ const capabilities=params?._meta?.['io.modelcontextprotocol/clientCapabilities'];
29
+ if(params?._meta?.['io.modelcontextprotocol/protocolVersion']!=='2026-07-28')
30
+ return failed('MODERN_METADATA_REQUIRED');
31
+ if(!supportsForm(capabilities))return failed('CLIENT_FORM_UNSUPPORTED');
32
+ if(params.requestState!==undefined)return failed('UNEXPECTED_REQUEST_STATE');
33
+ const received=params.inputResponses;
34
+ if(received===undefined)return {resultType:'input_required',
35
+ inputRequests:{test_choice:{
36
+ method:'elicitation/create',
37
+ params:{mode:'form',message:'Chat Loop 原生选项技术测试:不会批准任务或启动循环。',
38
+ requestedSchema:{type:'object',properties:{
39
+ choice:{type:'string',title:'请选择一个测试选项',oneOf:options},
40
+ note:{type:'string',title:'自定义回答(选自定义时必填)',maxLength:300}
41
+ },required:['choice']}
42
+ }
43
+ }}};
44
+ if(!received || typeof received!=='object'||Array.isArray(received)
45
+ ||Object.keys(received).some(k=>k!=='test_choice'))
46
+ return failed('INVALID_RESPONSE');
47
+ const result=received.test_choice;
48
+ if(!result || !['accept','decline','cancel'].includes(result.action))
49
+ return failed('INVALID_RESPONSE');
50
+ if(result.action!=='accept')return completed({userAction:result.action,choice:null});
51
+ const choice=result.content?.choice, note=result.content?.note??'';
52
+ if(!names.includes(choice)||typeof note!=='string'||note.length>300
53
+ ||choice==='other'&&!note.trim())return failed('INVALID_CHOICE');
54
+ return completed({userAction:'accept',choice,note});
55
+ }
package/lib/control.mjs CHANGED
@@ -13,9 +13,14 @@ export const toolCallDeadlineMs = args => {
13
13
  const requested = Number.isSafeInteger(args?.timeout_ms) && args.timeout_ms > 0 ? args.timeout_ms : 0;
14
14
  return Math.min(42000, Math.max(12000, requested + 8000));
15
15
  };
16
+ // Lifecycle wait contract shared by CLI callers and integration tests.
17
+ export const lifecycleDeadlineMs = action => ['start','restart'].includes(action) ? 25000 : 12000;
16
18
  export const ACTIONS = new Set(['start','stop','restart','status']);
17
19
  export const directory = () => process.env.CHAT_LOOP_LOCAL_TOOLS_STATE_DIR || join(homedir(), '.chat-loop', 'local-tools');
18
- export const paths = () => ({dir: directory(), socket: join(directory(), 'control.sock'), lock: join(directory(), 'manager.lock'), log: join(directory(), 'events.jsonl')});
20
+ export const paths = () => {
21
+ const dir=directory();
22
+ return {dir,socket:join(dir,'control.sock'),lock:join(dir,'manager.lock'),log:join(dir,'events.jsonl')};
23
+ };
19
24
  export function registry() {
20
25
  const tools = [{id: 'desktop-commander', enabled: process.env.CHAT_LOOP_LOCAL_TOOLS_FIXTURES !== '1', kind: 'mcp-child'}];
21
26
  if (!['1','both'].includes(process.env.CHAT_LOOP_LOCAL_TOOLS_FIXTURES)) {
@@ -34,8 +39,8 @@ export function ensurePrivateDir() {
34
39
  if (!s.isDirectory() || s.isSymbolicLink() || (process.getuid && s.uid !== process.getuid()) || (s.mode & 0o077))
35
40
  throw Object.assign(new Error('Insecure local-tools state directory'), {code:'INSECURE_STATE_DIR'});
36
41
  }
37
- export function lockPresent() {return existsSync(paths().lock);}
38
- export function verifyOwner(hello) {
42
+ function lockPresent() {return existsSync(paths().lock);}
43
+ function verifyOwner(hello) {
39
44
  const p=paths();
40
45
  const d=lstatSync(p.dir), l=lstatSync(p.lock), s=lstatSync(p.socket);
41
46
  if (!d.isDirectory() || d.isSymbolicLink() || (d.mode&0o077) ||
@@ -0,0 +1,90 @@
1
+ // Pure public API: MCP schemas, CLI routes and their argument gate.
2
+ // No process creation, filesystem access, browser actions or user side effects.
3
+ const PROJECT_ID=/^[a-zA-Z0-9][a-zA-Z0-9._-]{0,127}$/;
4
+ const CHAT_URL=/^https:\/\/chatgpt\.com\/(?:c\/[0-9a-f-]{12,}|g\/[^/]+\/c\/[0-9a-f-]{12,})$/i;
5
+ const REPLACE_SESSION=/^[0-9a-fA-F]{8}(?:-[0-9a-fA-F]{4}){3}-[0-9a-fA-F]{12}$/;
6
+ const TURN_TOKEN=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
7
+ const INTENT_ID=/^[a-f0-9]{32}$/;
8
+ const CONTROL_TOOLS=new Set(['start','continue','handoff']);
9
+ export const isControlTool=name=>CONTROL_TOOLS.has(name);
10
+ const extensionTool = (name,description,readOnlyHint,properties={},required=[]) => ({
11
+ name,description,inputSchema:{type:'object',properties,required,additionalProperties:false},
12
+ annotations:{readOnlyHint}
13
+ });
14
+ const endpoints=[
15
+ [['extension','chat','text'],extensionTool('chat_text','Read text from Chat Loop Extension current unique Chat Owner.',true)],
16
+ [['extension','chat','dom'],extensionTool('chat_dom','Read HTML from Chat Loop Extension current unique Chat Owner.',true)],
17
+ [['extension','chat','screenshot'],extensionTool('chat_screenshot','Capture PNG from Chat Loop Extension current unique Chat Owner; activates its tab.',false)],
18
+ [['extension','clean'],extensionTool('clean','Clear composer text in one exact verified ChatGPT tab; never sends.',false,
19
+ {tabId:{type:'integer',minimum:1}},['tabId'])],
20
+ [['extension','reload'],extensionTool('reload','Request reload of Chat Loop Extension; final health is unverified.',false)],
21
+ [['extension','status'],extensionTool('status','Read the unique current Mac Chrome Web Chat Owner; never starts or sends.',true)],
22
+ [['extension','start'],extensionTool('start',
23
+ 'Start a new Chat with prompt, OR mode=adopt for an existing Chat with two browser-verified R/P approvals. Adopt never creates a tab or resends a message; ambiguous or absent approvals are denied.',false,
24
+ {projectId:{type:'string',minLength:1,maxLength:128,pattern:PROJECT_ID.source},
25
+ prompt:{type:'string',minLength:1,maxLength:4000,pattern:'\\S'},confirmed:{const:true},
26
+ mode:{type:'string',enum:['adopt']},
27
+ chatUrl:{type:'string',pattern:CHAT_URL.source},
28
+ replaceBlockedSessionId:{type:'string',pattern:REPLACE_SESSION.source}},
29
+ ['projectId','confirmed'])],
30
+ [['extension','continue'],extensionTool('continue','Submit next-turn text with turnToken and nextPrompt; alternatively query its final status with turnToken and intentId. Only the Extension can send after Turn completion.',false,
31
+ {turnToken:{type:'string',pattern:TURN_TOKEN.source},nextPrompt:{type:'string',minLength:1,maxLength:4000,pattern:'\\S'},
32
+ intentId:{type:'string',pattern:INTENT_ID.source},lookup:{type:'boolean'}},['turnToken'])],
33
+ [['extension','handoff'],extensionTool('handoff','Submit an early Handoff with turnToken and optional reason; alternatively query receipt with turnToken and intentId. Extension still owns the timing and send.',false,
34
+ {turnToken:{type:'string',pattern:TURN_TOKEN.source},reason:{type:'string',maxLength:400},
35
+ intentId:{type:'string',pattern:INTENT_ID.source},lookup:{type:'boolean'}},['turnToken'])],
36
+ ];
37
+ export const extensionTools=endpoints.map(([,tool])=>tool);
38
+ export const extensionCommand=name=>endpoints.find(([,tool])=>tool.name===name)?.[0]||null;
39
+ // The Native Host independently validates at its own trust boundary.
40
+ export function validExtensionArgs(name,args){
41
+ const endpoint=endpoints.find(([,tool])=>tool.name===name);
42
+ if(!endpoint||!args||typeof args!=='object'||Array.isArray(args))return false;
43
+ const schema=endpoint[1].inputSchema;
44
+ // Required fields must be supplied by the caller, not inherited from a prototype.
45
+ if(schema.required.some(k=>!Object.hasOwn(args,k))
46
+ || Object.keys(args).some(k=>!Object.hasOwn(schema.properties,k)))
47
+ return false;
48
+ const control=isControlTool(name);
49
+ if(name==='clean'){
50
+ if(Object.keys(args).length!==1||!Number.isSafeInteger(args.tabId)||args.tabId<1)
51
+ return false;
52
+ }else if(!control && Object.keys(args).length)return false;
53
+ if(name==='start'){
54
+ if(!PROJECT_ID.test(args.projectId||'')
55
+ ||args.confirmed!==true
56
+ ||(args.replaceBlockedSessionId!==undefined
57
+ && !REPLACE_SESSION.test(args.replaceBlockedSessionId))
58
+ ||(args.mode!==undefined && args.mode!=='adopt')
59
+ ||(args.chatUrl!==undefined && (args.mode!=='adopt'
60
+ ||typeof args.chatUrl!=='string'||!CHAT_URL.test(args.chatUrl)))
61
+ ||(args.mode==='adopt'
62
+ ? Object.hasOwn(args,'prompt')
63
+ : typeof args.prompt!=='string'||!args.prompt.trim()||args.prompt.length>4000))
64
+ return false;
65
+ }
66
+ if(control&&name!=='start'){
67
+ if(typeof args.turnToken!=='string'||!TURN_TOKEN.test(args.turnToken))
68
+ return false;
69
+ const hasId=Object.hasOwn(args,'intentId');
70
+ const hasLookup=Object.hasOwn(args,'lookup');
71
+ // Receipt query and newest-receipt lookup are mutually exclusive.
72
+ if(hasId||hasLookup){
73
+ if(hasId===hasLookup||Object.keys(args).length!==2)return false;
74
+ return hasId
75
+ ? typeof args.intentId==='string'&&INTENT_ID.test(args.intentId)
76
+ : args.lookup===true;
77
+ }
78
+ if(name==='continue'){
79
+ return Object.keys(args).length===2
80
+ && typeof args.nextPrompt==='string' && !!args.nextPrompt.trim()
81
+ && args.nextPrompt.length<=4000
82
+ && !/[\x00-\x1f]/.test(args.nextPrompt.replaceAll('\n',''));
83
+ }
84
+ // Handoff only needs the bound token; its short reason is optional.
85
+ return (Object.keys(args).length===1||Object.hasOwn(args,'reason'))
86
+ && (args.reason===undefined || (typeof args.reason==='string'
87
+ && args.reason.length<=400 && !/[\x00-\x1f]/.test(args.reason)));
88
+ }
89
+ return true;
90
+ }
@@ -3,91 +3,26 @@
3
3
  import {spawn} from 'node:child_process';
4
4
  import {readFileSync,statSync} from 'node:fs';
5
5
  import {tmpdir} from 'node:os';
6
+ import {extensionCommand,validExtensionArgs,isControlTool} from './extension-contract.mjs';
7
+ export {extensionTools} from './extension-contract.mjs';
6
8
 
7
- // Static signatures are discoverable even when npm is offline; control requests queue, never send in an MCP call.
8
- // All executable behavior and Native Host integration belong to the Extension npm package.
9
- const extensionTool = (name,description,readOnlyHint,properties={},required=[]) => ({
10
- name,description,inputSchema:{type:'object',properties,required,additionalProperties:false},
11
- annotations:{readOnlyHint}
12
- });
13
- export const extensionTools=[
14
- extensionTool('chat_text','Read text from Chat Loop Extension current unique Chat Owner.',true),
15
- extensionTool('chat_dom','Read HTML from Chat Loop Extension current unique Chat Owner.',true),
16
- extensionTool('chat_screenshot','Capture PNG from Chat Loop Extension current unique Chat Owner; activates its tab.',false),
17
- extensionTool('clean','Clear composer text in one exact verified ChatGPT tab; never sends.',false,
18
- {tabId:{type:'integer',minimum:1}},['tabId']),
19
- extensionTool('reload','Request reload of Chat Loop Extension; final health is unverified.',false),
20
- extensionTool('status','Read the unique current Mac Chrome Web Chat Owner; never starts or sends.',true),
21
- extensionTool('start','After confirmed intent and preflight, ask Extension to start one unique Web Chat; fails if any task owns it.',false,
22
- {projectId:{type:'string',minLength:1,maxLength:128},prompt:{type:'string',minLength:1,maxLength:4000},confirmed:{const:true},
23
- replaceBlockedSessionId:{type:'string',pattern:'^[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}$'}},
24
- ['projectId','prompt','confirmed']),
25
- extensionTool('continue','Submit next-turn text with turnToken and nextPrompt; alternatively query its final status with turnToken and intentId. Only the Extension can send after Turn completion.',false,
26
- {turnToken:{type:'string'},nextPrompt:{type:'string',minLength:1,maxLength:4000},
27
- intentId:{type:'string',pattern:'^[a-f0-9]{32}$'},lookup:{type:'boolean'}},['turnToken']),
28
- extensionTool('handoff','Submit an early Handoff with turnToken and optional reason; alternatively query receipt with turnToken and intentId. Extension still owns the timing and send.',false,
29
- {turnToken:{type:'string'},reason:{type:'string',maxLength:400},
30
- intentId:{type:'string',pattern:'^[a-f0-9]{32}$'},lookup:{type:'boolean'}},['turnToken']),
31
- ];
32
9
  // Public CLI contract only: no require.resolve, extension source path or pinned npm dependency.
33
10
  // Explicit @latest enables npm's default cache/revalidation behavior; --yes only accepts
34
11
  // npm's install confirmation. No --offline, --no-install or forced network flags.
35
12
  const EXTENSION_PACKAGE='@tomflow/chatloop-extension@latest';
36
13
  const NPX_COMMAND=process.platform==='win32'?'npx.cmd':'npx';
37
14
  export const extensionInvocation=name=>{
38
- const command=commands[name];
15
+ const command=extensionCommand(name);
39
16
  if(!command)return null;
40
17
  return {executable:NPX_COMMAND,
41
18
  args:['--yes','--package='+EXTENSION_PACKAGE,'chatloop-extension',...command]};
42
19
  };
43
- const commands={
44
- chat_text:['extension','chat','text'],
45
- chat_dom:['extension','chat','dom'],
46
- chat_screenshot:['extension','chat','screenshot'],
47
- reload:['extension','reload'],
48
- status:['extension','status'],
49
- start:['extension','start'],
50
- clean:['extension','clean'],
51
- continue:['extension','continue'],
52
- handoff:['extension','handoff']
53
- };
54
20
  const fail=code=>({isError:true,content:[{type:'text',text:code}]});
55
21
  export async function forwardExtensionAction(name,args={}) {
56
22
  const invocation=extensionInvocation(name);
57
- if(!invocation||!args||typeof args!=='object'||Array.isArray(args))return fail('INVALID_ARGUMENT');
58
- const control=['continue','handoff','start'].includes(name);
59
- if(name==='clean'){
60
- if(Object.keys(args).length!==1||!Number.isSafeInteger(args.tabId)||args.tabId<1)
61
- return fail('INVALID_ARGUMENT');
62
- invocation.args.push(String(args.tabId));
63
- }else if(!control && Object.keys(args).length)return fail('INVALID_ARGUMENT');
64
- if(name==='start'){
65
- if(Object.keys(args).some(k=>!['projectId','prompt','confirmed','replaceBlockedSessionId'].includes(k))
66
- ||!(/^[a-zA-Z0-9][a-zA-Z0-9._-]{0,127}$/).test(args.projectId||'')
67
- ||typeof args.prompt!=='string'||!args.prompt.trim()||args.prompt.length>4000
68
- ||args.confirmed!==true
69
- ||(args.replaceBlockedSessionId!==undefined
70
- && !/^[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}$/i.test(args.replaceBlockedSessionId)))
71
- return fail('INVALID_ARGUMENT');
72
- }
73
- if(control&&name!=='start'){
74
- const query=Object.hasOwn(args,'intentId')||args.lookup===true;
75
- if(typeof args.turnToken!=='string' || !/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/.test(args.turnToken)
76
- || Object.keys(args).some(k=>k!=='turnToken' && (query?
77
- k!==(args.lookup===true?'lookup':'intentId'):
78
- name==='continue'?k!=='nextPrompt':k!=='reason'))
79
- || (query && args.lookup!==true
80
- && (typeof args.intentId!=='string'||!/^[a-f0-9]{32}$/.test(args.intentId))))
81
- return fail('INVALID_ARGUMENT');
82
- if(!query){
83
- if(name==='continue' && (typeof args.nextPrompt!=='string'||!args.nextPrompt.trim()
84
- || args.nextPrompt.length>4000||/[\x00-\x1f]/.test(args.nextPrompt.replaceAll('\n',''))))
85
- return fail('INVALID_ARGUMENT');
86
- if(name==='handoff' && args.reason!==undefined
87
- && (typeof args.reason!=='string'||args.reason.length>400||/[\x00-\x1f]/.test(args.reason)))
88
- return fail('INVALID_ARGUMENT');
89
- }
90
- }
23
+ if(!invocation||!validExtensionArgs(name,args))return fail('INVALID_ARGUMENT');
24
+ const control=isControlTool(name);
25
+ if(name==='clean')invocation.args.push(String(args.tabId));
91
26
  const response=await new Promise(resolve=>{
92
27
  const child=spawn(invocation.executable,invocation.args,{stdio:[control?'pipe':'ignore','pipe','pipe'],
93
28
  cwd:tmpdir(),windowsHide:true,env:process.env});
@@ -105,7 +40,7 @@ export async function forwardExtensionAction(name,args={}) {
105
40
  const line=stdout.trim().split('\n').filter(Boolean).at(-1);
106
41
  let msg;try{msg=JSON.parse(line);}catch{return settle(fail('INVALID_EXTENSION_REPLY'));}
107
42
  if(msg.contract!=='chat-loop.extension-cli.v1'||msg.event!=='RESULT'
108
- ||msg.command!==(name==='clean'?'extension clean '+args.tabId:commands[name].join(' ')))return settle(fail('INVALID_EXTENSION_REPLY'));
43
+ ||msg.command!==(name==='clean'?'extension clean '+args.tabId:extensionCommand(name).join(' ')))return settle(fail('INVALID_EXTENSION_REPLY'));
109
44
  if(!msg.ok||code!==0)return settle(fail(msg.error?.code||'EXTENSION_ACTION_FAILED'));
110
45
  settle(msg.value);
111
46
  });
package/lib/gateway.mjs CHANGED
@@ -3,6 +3,7 @@ import {randomUUID} from 'node:crypto';
3
3
  import {readFileSync} from 'node:fs';
4
4
  import {CONTRACT,PACKAGE_VERSION,registry,talk,toolCallDeadlineMs} from './control.mjs';
5
5
  import {extensionTools,forwardExtensionAction} from './extension-proxy.mjs';
6
+ import {probeTool,handleProbeForm} from './approval-form-probe.mjs';
6
7
  import {runtimeNeedsUpgrade} from './release.mjs';
7
8
 
8
9
  const desktopTools=JSON.parse(readFileSync(new URL('./desktop-commander-tools.json',import.meta.url),'utf8'));
@@ -13,14 +14,20 @@ const prefix=id=>id.replaceAll('-','_')+'__';
13
14
  // The pinned child's UI metadata advertises resources this tools-only Gateway does not serve.
14
15
  // Do not expose those references until resources/read is explicitly supported.
15
16
  const extEnabled=()=>process.env.CHAT_LOOP_LOCAL_TOOLS_FIXTURES!=='1';
17
+ // Opt-in isolated research probe; never shipped as an active production tool.
18
+ const formProbeEnabled=()=>process.env.CHAT_LOOP_FORM_PROBE==='1';
19
+ // The only extra Gateway-owned API: read an existing operation receipt.
20
+ // Its identifier is always a generated UUID, never an arbitrary selector.
21
+ const RECEIPT_ID=/^[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}$/;
16
22
  const receiptTool={name:'chat_loop_runtime__operation_status',
17
23
  description:'Read a previously timed-out MCP request receipt without replaying its side effects.',
18
24
  inputSchema:{type:'object',required:['requestId'],additionalProperties:false,
19
- properties:{requestId:{type:'string'}}}};
25
+ properties:{requestId:{type:'string',pattern:RECEIPT_ID.source}}}};
20
26
  const published=()=>[
21
27
  ...registry().filter(t=>t.enabled).flatMap(t=>
22
28
  toolsFor(t).map(({_meta,...x})=>({...x,name:prefix(t.id)+x.name}))),
23
29
  ...(extEnabled()?extensionTools.map(t=>({...t,name:'chat_loop_extension__'+t.name})):[]),
30
+ ...(formProbeEnabled()?[probeTool]:[]),
24
31
  receiptTool
25
32
  ];
26
33
  function resolveTool(name){
@@ -41,16 +48,18 @@ function resolveTool(name){
41
48
  const failure=code=>({isError:true,content:[{type:'text',text:code}]});
42
49
  const rpcError=(code,message)=>({code,message});
43
50
  export function runGateway(){
44
- let buf='',connected=false;
51
+ let buf='',connected=false,negotiatedVersion=null;
45
52
  const write=message=>process.stdout.write(JSON.stringify(message)+'\n');
46
53
  const reply=(id,result)=>write({jsonrpc:'2.0',id,result});
47
54
  const reject=(id,code,message)=>write({jsonrpc:'2.0',id,error:rpcError(code,message)});
48
55
  const processMessage=async m=>{
49
56
  if(!m||m.jsonrpc!=='2.0'||m.id===undefined)return;
50
57
  if(m.method==='initialize'){
51
- if(!['2025-11-25','2025-06-18','2025-03-26','2024-11-05'].includes(m.params?.protocolVersion))
58
+ if(![...(['2025-11-25','2025-06-18','2025-03-26','2024-11-05']),
59
+ ...(formProbeEnabled()?['2026-07-28']:[])].includes(m.params?.protocolVersion))
52
60
  return reject(m.id,-32602,'UNSUPPORTED_MCP_VERSION');
53
61
  connected=true;
62
+ negotiatedVersion=m.params.protocolVersion;
54
63
  return reply(m.id,{protocolVersion:m.params.protocolVersion,
55
64
  capabilities:{tools:{}},serverInfo:{name:'chat-loop-local-tools',version:PACKAGE_VERSION}});
56
65
  }
@@ -61,6 +70,11 @@ export function runGateway(){
61
70
  if(m.method==='ping')return reply(m.id,{});
62
71
  if(m.method==='tools/list')return reply(m.id,{tools:published()});
63
72
  if(m.method==='tools/call'){
73
+ if(formProbeEnabled() && m.params?.name===probeTool.name)
74
+ return reply(m.id,negotiatedVersion==='2026-07-28'
75
+ ?handleProbeForm(m.params)
76
+ :{resultType:'complete',isError:true,
77
+ content:[{type:'text',text:'FORM_PROBE_MODERN_PROTOCOL_REQUIRED'}]});
64
78
  const routed=m.params?.name===receiptTool.name?
65
79
  {toolId:'runtime',name:'operation_status'}:resolveTool(m.params?.name);
66
80
  if(!routed)return reply(m.id,failure('UNKNOWN_TOOL'));
@@ -69,6 +83,9 @@ export function runGateway(){
69
83
  return reply(m.id,failure('INVALID_ARGUMENT'));
70
84
  try{
71
85
  if(routed.toolId==='runtime'){
86
+ if(Object.keys(args).length!==1 || typeof args.requestId!=='string'
87
+ ||!RECEIPT_ID.test(args.requestId))
88
+ return reply(m.id,failure('INVALID_ARGUMENT'));
72
89
  const res=await talk({contract:CONTRACT,action:'receipt',requestId:randomUUID(),
73
90
  targetRequestId:args.requestId},4000);
74
91
  return reply(m.id,res.status==='OK'?{operation:res.operation}:failure('RECEIPT_UNAVAILABLE'));
package/lib/tunnel.mjs CHANGED
@@ -37,11 +37,8 @@ export function bundledTunnel(){
37
37
  }
38
38
  export function tunnelDoctor(){
39
39
  try{
40
+ // bundledTunnel already verifies both bundled binaries against provenance.
40
41
  const b=bundledTunnel();
41
- const cloudflared=createHash('sha256').update(readFileSync(b.cloudflared)).digest('hex');
42
- const info=JSON.parse(readFileSync(join(b.base,'provenance.json'),'utf8'));
43
- if(cloudflared!==info.cloudflaredSha256)
44
- throw Object.assign(Error('Bundled cloudflared checksum mismatch'),{code:'INVALID_BUNDLE'});
45
42
  return {status:'BUNDLED_READY',release:b.release,platform:b.platform,
46
43
  executable:b.binary,cloudflared:b.cloudflared,verified:true,connection:'UNVERIFIED'};
47
44
  }catch(e){return {status:'BLOCKED',code:e.code||'INVALID_BUNDLE',reason:e.message};}
package/package.json CHANGED
@@ -3,7 +3,7 @@
3
3
  "publishConfig": {
4
4
  "access": "public"
5
5
  },
6
- "version": "0.4.17",
6
+ "version": "0.4.19",
7
7
  "type": "module",
8
8
  "description": "Chat Loop local tools: MCP gateway, isolated bundled tunnel-client and unified CLI",
9
9
  "bin": {