@tomflow/chatloop-tools 0.4.26 → 0.4.27

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/lib/gateway.mjs CHANGED
@@ -3,12 +3,11 @@ 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';
7
6
  import {taskRegistryTool,runTaskRegistry} from './task-registry.mjs';
8
7
  import {managedTaskRegistry} from './task-registry-managed.mjs';
9
8
  import {contextGatewayTools,contextGatewayEnabled,runContextGateway} from './context-gateway.mjs';
10
9
  import {runtimeNeedsUpgrade} from './release.mjs';
11
- import {traceDiagnoseTool,traceGatewayEnabled,runTraceDiagnose,observeExtensionResult} from './trace-gateway.mjs';
10
+ import {traceDiagnoseTool,traceStageTool,traceGatewayEnabled,runTraceDiagnose,runTraceStage,observeExtensionResult} from './trace-gateway.mjs';
12
11
  import {isGraphicalTerminalCommand} from './terminal-app-policy.mjs';
13
12
 
14
13
  // Keep the pinned Desktop Commander as the implementation, but expose only
@@ -46,8 +45,6 @@ const prefix=id=>id.replaceAll('-','_')+'__';
46
45
  // The pinned child's UI metadata advertises resources this tools-only Gateway does not serve.
47
46
  // Do not expose those references until resources/read is explicitly supported.
48
47
  const extEnabled=()=>process.env.CHAT_LOOP_LOCAL_TOOLS_FIXTURES!=='1';
49
- // Opt-in isolated research probe; never shipped as an active production tool.
50
- const formProbeEnabled=()=>process.env.CHAT_LOOP_FORM_PROBE==='1';
51
48
  // The only extra Gateway-owned API: read an existing operation receipt.
52
49
  // Its identifier is always a generated UUID, never an arbitrary selector.
53
50
  const RECEIPT_ID=/^[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}$/;
@@ -59,11 +56,10 @@ const published=()=>[
59
56
  ...registry().filter(t=>t.enabled).flatMap(t=>
60
57
  toolsFor(t).map(({_meta,...x})=>({...x,name:prefix(t.id)+x.name}))),
61
58
  ...(extEnabled()?extensionTools.map(t=>({...t,name:'chat_loop_extension__'+t.name})):[]),
62
- ...(formProbeEnabled()?[probeTool]:[]),
63
59
  receiptTool,
64
60
  taskRegistryTool,
65
61
  ...(contextGatewayEnabled()?contextGatewayTools:[]),
66
- ...(traceGatewayEnabled()?[traceDiagnoseTool]:[])
62
+ ...(traceGatewayEnabled()?[traceDiagnoseTool,traceStageTool]:[])
67
63
  ];
68
64
  function resolveTool(name){
69
65
  if(extEnabled()&&typeof name==='string'&&name.startsWith('chat_loop_extension__')){
@@ -83,18 +79,17 @@ function resolveTool(name){
83
79
  const failure=code=>({isError:true,content:[{type:'text',text:code}]});
84
80
  const rpcError=(code,message)=>({code,message});
85
81
  export function runGateway(){
86
- let buf='',connected=false,negotiatedVersion=null;
82
+ let buf='',connected=false;
87
83
  const write=message=>process.stdout.write(JSON.stringify(message)+'\n');
88
84
  const reply=(id,result)=>write({jsonrpc:'2.0',id,result});
89
85
  const reject=(id,code,message)=>write({jsonrpc:'2.0',id,error:rpcError(code,message)});
90
86
  const processMessage=async m=>{
91
87
  if(!m||m.jsonrpc!=='2.0'||m.id===undefined)return;
92
88
  if(m.method==='initialize'){
93
- if(![...(['2025-11-25','2025-06-18','2025-03-26','2024-11-05']),
94
- ...(formProbeEnabled()?['2026-07-28']:[])].includes(m.params?.protocolVersion))
89
+ if(!['2025-11-25','2025-06-18','2025-03-26','2024-11-05']
90
+ .includes(m.params?.protocolVersion))
95
91
  return reject(m.id,-32602,'UNSUPPORTED_MCP_VERSION');
96
92
  connected=true;
97
- negotiatedVersion=m.params.protocolVersion;
98
93
  return reply(m.id,{protocolVersion:m.params.protocolVersion,
99
94
  capabilities:{tools:{}},serverInfo:{name:'chat-loop-local-tools',version:PACKAGE_VERSION}});
100
95
  }
@@ -105,6 +100,12 @@ export function runGateway(){
105
100
  if(m.method==='ping')return reply(m.id,{});
106
101
  if(m.method==='tools/list')return reply(m.id,{tools:published()});
107
102
  if(m.method==='tools/call'){
103
+ if(traceGatewayEnabled()&&m.params?.name===traceStageTool.name){
104
+ try{
105
+ const value=await runTraceStage(m.params.arguments);
106
+ return reply(m.id,{content:[{type:'text',text:JSON.stringify(value)}]});
107
+ }catch(e){return reply(m.id,failure(e.code||'TRACE_STAGE_FAILED'))}
108
+ }
108
109
  if(traceGatewayEnabled()&&m.params?.name===traceDiagnoseTool.name){
109
110
  try{
110
111
  const result=await runTraceDiagnose(m.params.arguments);
@@ -153,11 +154,6 @@ export function runGateway(){
153
154
  return reply(m.id,{content:[{type:'text',text:JSON.stringify(value)}]});
154
155
  }catch(e){return reply(m.id,failure(e.code||e.message||'CONTEXT_OPERATION_FAILED'));}
155
156
  }
156
- if(formProbeEnabled() && m.params?.name===probeTool.name)
157
- return reply(m.id,negotiatedVersion==='2026-07-28'
158
- ?handleProbeForm(m.params)
159
- :{resultType:'complete',isError:true,
160
- content:[{type:'text',text:'FORM_PROBE_MODERN_PROTOCOL_REQUIRED'}]});
161
157
  const routed=m.params?.name===receiptTool.name?
162
158
  {toolId:'runtime',name:'operation_status'}:resolveTool(m.params?.name);
163
159
  if(!routed)return reply(m.id,failure('UNKNOWN_TOOL'));
@@ -29,17 +29,25 @@ const allowedTraceProjects=()=>{
29
29
  ? entries : []);
30
30
  };
31
31
  const traceEnabled=()=>process.env.CHAT_LOOP_TRACE_API_ENABLE==='1';
32
+ const UUID_RE=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
32
33
  function handleTraceObservation(req){
33
34
  if(!traceEnabled()||!allowedTraceProjects().has(req?.projectRef))
34
35
  throw error('TRACE_PROJECT_ACCESS_DENIED');
35
36
  const intent=/^extension\.(continue|handoff)\.(intent\.queued|receipt\.observed)$/.test(req?.event||'');
37
+ const agent=/^agent\.(intent|project|tooling)\.soft_(observed|blocked|unverified)$/.test(req?.event||'');
38
+ const agentStatus=req?.event?.endsWith('_observed')?'CONFIRMED':
39
+ req?.event?.endsWith('_blocked')?'BLOCKED':'UNKNOWN';
36
40
  const validEvent=['extension.start.observed','extension.status.observed'].includes(req?.event)
37
- ||intent;
41
+ ||intent||agent;
38
42
  if(req?.contract!==CONTRACT||!validEvent
39
- ||!(intent?(req.event.endsWith('.intent.queued')?req.status==='BEGIN'
40
- :['CONFIRMED','UNKNOWN'].includes(req.status))
41
- :['CONFIRMED','UNKNOWN','BLOCKED'].includes(req.status))
43
+ ||!(agent?req.status===agentStatus:
44
+ intent?(req.event.endsWith('.intent.queued')?req.status==='BEGIN'
45
+ :['CONFIRMED','UNKNOWN'].includes(req.status))
46
+ :['CONFIRMED','UNKNOWN','BLOCKED'].includes(req.status))
42
47
  ||typeof req.traceId!=='string'
48
+ ||(agent&&(req.sessionRef!==undefined||req.taskRef!==undefined||
49
+ req.generation!==undefined||req.evidenceRef!==undefined||
50
+ req.actionId!==undefined||req.errorCode!==undefined||!UUID_RE.test(req.traceId)))
43
51
  ||(intent&&(!/^[a-f0-9]{32}$/.test(req.actionId||'')
44
52
  ||req.evidenceRef!==req.actionId)))throw error('TRACE_INVALID_ARGUMENT');
45
53
  const errorCode=typeof req.errorCode==='string'&&
@@ -27,6 +27,48 @@ export const traceDiagnoseTool={
27
27
  },
28
28
  annotations:{readOnlyHint:true}
29
29
  };
30
+ // Pre-Session agent decisions are SOFT observations, not authenticated
31
+ // ChatGPT user-click, approval, Context write or Native Owner receipts.
32
+ const STAGE_NAMES=['intent','project','tooling'];
33
+ const STAGE_OUTCOMES=['OBSERVED','BLOCKED','UNVERIFIED'];
34
+ export const traceStageTool={
35
+ name:'chat_loop_trace_stage',
36
+ description:'Record a scoped, explicitly SOFT agent-stage observation in the existing single Trace writer. Does not authenticate @ clicks, grant Context/Owner, or store conversation content. Return traceId for later calls; never use this as task approval.',
37
+ inputSchema:{
38
+ type:'object',additionalProperties:false,
39
+ required:['projectRef','stage','outcome'],
40
+ properties:{
41
+ projectRef:{type:'string',pattern:PROJECT.source},
42
+ traceId:{type:'string',pattern:UUID},
43
+ stage:{type:'string',enum:STAGE_NAMES},
44
+ outcome:{type:'string',enum:STAGE_OUTCOMES}
45
+ }
46
+ },
47
+ annotations:{readOnlyHint:false}
48
+ };
49
+ export async function runTraceStage(args){
50
+ if(!traceGatewayEnabled())throw fail('TRACE_API_DISABLED');
51
+ if(!args||typeof args!=='object'||Array.isArray(args)||
52
+ Object.keys(args).some(k=>!Object.hasOwn(traceStageTool.inputSchema.properties,k))||
53
+ !STAGE_NAMES.includes(args.stage)||
54
+ !STAGE_OUTCOMES.includes(args.outcome)||
55
+ args.traceId!==undefined&&!new RegExp(UUID).test(args.traceId))
56
+ throw fail('TRACE_INVALID_ARGUMENT');
57
+ if(typeof args.projectRef!=='string'||!getAllowedProjects().includes(args.projectRef))
58
+ throw fail('TRACE_PROJECT_ACCESS_DENIED');
59
+ const traceId=args.traceId||randomUUID();
60
+ const status=args.outcome==='OBSERVED'?'CONFIRMED':
61
+ args.outcome==='BLOCKED'?'BLOCKED':'UNKNOWN';
62
+ const requestId=randomUUID();
63
+ const event='agent.'+args.stage+'.soft_'+args.outcome.toLowerCase();
64
+ const r=await talk({contract:CONTRACT,action:'__trace_observation',
65
+ requestId,traceId,projectRef:args.projectRef,event,status},1800);
66
+ if(r?.status!=='OK'||!new RegExp(UUID).test(r?.eventId||''))
67
+ throw fail(r?.error?.code||'TRACE_STAGE_NOT_RECORDED');
68
+ return {status:'RECORDED_SOFT',confidence:'SOFT_AGENT_OBSERVATION',
69
+ traceId,eventId:r.eventId,event,requestId};
70
+ }
71
+
30
72
  const getAllowedProjects=()=>{
31
73
  const entries=(process.env.CHAT_LOOP_TRACE_ALLOWED_PROJECTS||'')
32
74
  .split(',').map(x=>x.trim());
@@ -1145,8 +1145,8 @@ export function openContextProtocol(file,{authorizeInternal=()=>false,authorizeD
1145
1145
  .get(a.projectId,a.taskId,issue.document_id,issue.version);
1146
1146
  assert(doc&&doc.content_hash===issue.content_hash,'DOCUMENT_CHANGED');
1147
1147
  if(a.decision!=='APPROVE'){
1148
- const issueStatus=a.decision==='REJECT'?'REJECTED':
1149
- a.decision==='REQUEST_CHANGE'?'CHANGE_REQUESTED':'CUSTOM_UNDECIDED';
1148
+ // The legacy CUSTOM decision has the same meaning as a change request.
1149
+ const issueStatus=a.decision==='REJECT'?'REJECTED':'CHANGE_REQUESTED';
1150
1150
  db.prepare('UPDATE issues SET state=?,presented_ref=? WHERE project_id=? AND task_id=? AND issue_id=?')
1151
1151
  .run(issueStatus,a.presentedAssistantRef,a.projectId,a.taskId,a.issueId);
1152
1152
  db.prepare('UPDATE tasks SET business_revision=business_revision+1 WHERE project_id=? AND task_id=?')
package/package.json CHANGED
@@ -3,7 +3,7 @@
3
3
  "publishConfig": {
4
4
  "access": "public"
5
5
  },
6
- "version": "0.4.26",
6
+ "version": "0.4.27",
7
7
  "type": "module",
8
8
  "description": "Chat Loop local tools: MCP gateway, isolated bundled tunnel-client and unified CLI",
9
9
  "bin": {
@@ -1,55 +0,0 @@
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
- }