@tomflow/chatloop-tools 0.9.52 → 0.9.54

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/index.mjs CHANGED
@@ -214,11 +214,11 @@ async function runtime(){
214
214
  throw localError(kind+'_TRACE_PARENT_MISSING');
215
215
  const result=await control.talk({
216
216
  contract:control.CONTRACT,action:'__trace_observation',
217
- requestId:randomUUID(),event:payload.event,
218
- status:payload.status||'CONFIRMED',
217
+ requestId:randomUUID(),event:payload.event,status:payload.status||'CONFIRMED',
219
218
  traceId:parent.traceId,spanId:parent.spanId,
220
219
  projectRef:'api_system',sessionRef:payload.traceRef,
221
- evidenceRef:payload[idKey],
220
+ evidenceRef:payload.documentId??payload[idKey],
221
+ ...(payload.taskId?{taskRef:payload.taskId}:{}),
222
222
  ...(payload.errorCode?{errorCode:payload.errorCode}:{})
223
223
  },1800);
224
224
  if(result?.status!=='OK'||!OBSERVER_UUID.test(result.eventId||''))
@@ -332,8 +332,8 @@ async function runtime(){
332
332
  dirname(control.paths().dir),'tunnel','profiles','chat-loop.yaml'))}
333
333
  catch{return {}}
334
334
  },
335
- loadContextControlSecret:contextAuth.loadContextControlSecret,
336
- handleContextControl:contextRun.handleContextControl
335
+ readContextSettings:()=>releaseUpgrade.readSupervisorContextSettings(join(dirname(control.paths().dir),'tunnel','profiles','chat-loop.yaml')),
336
+ loadContextControlSecret:contextAuth.loadContextControlSecret,handleContextControl:contextRun.handleContextControl
337
337
  });
338
338
  return Object.freeze({control,tunnel,tunnelAuth,release:releaseApi,gateway,supervisor});
339
339
  })();
@@ -47,7 +47,13 @@ const timeout=ctx=>Math.max(0,ctx.remaining());
47
47
  export function desktopCommanderEnvironment(parent=process.env,account=userInfo()){
48
48
  if(!isAbsolute(account?.homedir||'')||!account?.username)
49
49
  throw Object.assign(Error('LOCAL_ACCOUNT_UNAVAILABLE'),{code:'LOCAL_ACCOUNT_UNAVAILABLE'});
50
- return {...parent,HOME:account.homedir,USER:account.username,
50
+ // Supervisor's Native Context grant is for its signed private IPC and the
51
+ // owned Tunnel MCP, never for unrelated Desktop Commander shell commands.
52
+ const env={...parent};
53
+ for(const key of Object.keys(env))
54
+ if(/^CHAT_LOOP_(?:CONTEXT|TRACE)_(?:API_ENABLE|ROOT|DB|ALLOWED_PROJECTS|NODE_BIN)$/.test(key))
55
+ delete env[key];
56
+ return {...env,HOME:account.homedir,USER:account.username,
51
57
  LOGNAME:account.username,
52
58
  DESKTOP_COMMANDER_DISABLE_TELEMETRY:'true',DC_REMOTE_DEVICE:'false'};
53
59
  }
@@ -2,7 +2,7 @@
2
2
  // explicit ports from the SDK composition root; this module owns no state.
3
3
  import {randomUUID} from 'node:crypto';
4
4
  import {existsSync,mkdirSync,openSync,closeSync,unlinkSync,lstatSync,readFileSync,writeFileSync} from 'node:fs';
5
- import {join,dirname} from 'node:path';
5
+ import {join,dirname,isAbsolute,normalize} from 'node:path';
6
6
  import {verifyTunnelConnection,verifyMcpTools} from './release-health-checks.mjs';
7
7
  let PACKAGE_VERSION,CONTRACT,lifecycleDeadlineMs,talkForUpgrade,
8
8
  activeDesktopCommands,awaitStopped,checkedUpgradeBase,upgradeLayout,
@@ -123,6 +123,39 @@ export function readSupervisorMcpGrants(profilePath){
123
123
  return grants;
124
124
  }
125
125
 
126
+ // Context's private Native IPC executes in the Supervisor, whereas public MCP
127
+ // runs as a separately scoped child. Resolve both against the SAME trusted
128
+ // single-Project MCP profile, never the invoking CLI shell environment.
129
+ export function readSupervisorContextSettings(profilePath){
130
+ // Standalone isolated Supervisors may have an explicit Context env but no
131
+ // Tunnel profile; do not invent a profile or fail a valid direct scope.
132
+ try{lstatSync(profilePath)}catch(error){
133
+ if(error.code==='ENOENT')return null;
134
+ throw error;
135
+ }
136
+ const grants=readSupervisorMcpGrants(profilePath);
137
+ if(grants.CHAT_LOOP_CONTEXT_API_ENABLE!=='1')return null;
138
+ const profile=JSON.parse(readFileSync(profilePath,'utf8'));
139
+ const command=profile.mcp.commands.find(x=>x.channel==='main').command;
140
+ const prefix=preservedMcpEnvironmentPrefix(command);
141
+ const assignments=[...prefix.matchAll(/ "([^"]+)"/g)].map(x=>x[1]);
142
+ const rootValues=assignments.filter(x=>x.startsWith('CHAT_LOOP_CONTEXT_ROOT='));
143
+ if(rootValues.length!==1)throw Object.assign(Error('SUPERVISOR_CONTEXT_ROOT_MISSING'),
144
+ {code:'SUPERVISOR_CONTEXT_ROOT_MISSING'});
145
+ const root=rootValues[0].slice('CHAT_LOOP_CONTEXT_ROOT='.length);
146
+ if(!isAbsolute(root)||normalize(root)!==root)
147
+ throw Object.assign(Error('SUPERVISOR_CONTEXT_ROOT_INVALID'),
148
+ {code:'SUPERVISOR_CONTEXT_ROOT_INVALID'});
149
+ const st=lstatSync(root);
150
+ if(!st.isDirectory()||st.isSymbolicLink()||(st.mode&0o077)
151
+ ||(process.getuid&&st.uid!==process.getuid()))
152
+ throw Object.assign(Error('SUPERVISOR_CONTEXT_ROOT_UNTRUSTED'),
153
+ {code:'SUPERVISOR_CONTEXT_ROOT_UNTRUSTED'});
154
+ return Object.freeze({CHAT_LOOP_CONTEXT_API_ENABLE:'1',
155
+ CHAT_LOOP_CONTEXT_ROOT:root,
156
+ CHAT_LOOP_CONTEXT_ALLOWED_PROJECTS:grants.CHAT_LOOP_CONTEXT_ALLOWED_PROJECTS});
157
+ }
158
+
126
159
  export async function upgradeRuntime(options={}){
127
160
  if(options.args?.length)return freshResult('FAILED',{code:'INVALID_ARGUMENT'});
128
161
  const base=checkedUpgradeBase(options);
@@ -9,13 +9,13 @@ const entryOrMissing=path=>{
9
9
  try{return lstatSync(path)}
10
10
  catch(error){if(error.code==='ENOENT')return null;throw error}
11
11
  };
12
- let CONTRACT, VERSION, PACKAGE_VERSION, registry, paths, ensurePrivateDir, ACTIONS, createAdapter, createSupervisorTraceBridge, readObservationGrants, loadContextControlSecret, handleContextControl;
12
+ let CONTRACT, VERSION, PACKAGE_VERSION, registry, paths, ensurePrivateDir, ACTIONS, createAdapter, createSupervisorTraceBridge, readObservationGrants, readContextSettings, loadContextControlSecret, handleContextControl;
13
13
  let connected=false;
14
14
  export function configureSupervisor(ports){
15
15
  if(connected)throw Error('TOOLS_MODULE_ALREADY_COMPOSED');
16
- for(const name of ['CONTRACT', 'VERSION', 'PACKAGE_VERSION', 'registry', 'paths', 'ensurePrivateDir', 'ACTIONS', 'createAdapter', 'createSupervisorTraceBridge', 'readObservationGrants', 'loadContextControlSecret', 'handleContextControl'])
16
+ for(const name of ['CONTRACT', 'VERSION', 'PACKAGE_VERSION', 'registry', 'paths', 'ensurePrivateDir', 'ACTIONS', 'createAdapter', 'createSupervisorTraceBridge', 'readObservationGrants', 'readContextSettings', 'loadContextControlSecret', 'handleContextControl'])
17
17
  if(ports?.[name]===undefined)throw Error('TOOLS_PORT_MISSING:'+name);
18
- ({CONTRACT, VERSION, PACKAGE_VERSION, registry, paths, ensurePrivateDir, ACTIONS, createAdapter, createSupervisorTraceBridge, readObservationGrants, loadContextControlSecret, handleContextControl}=ports);
18
+ ({CONTRACT, VERSION, PACKAGE_VERSION, registry, paths, ensurePrivateDir, ACTIONS, createAdapter, createSupervisorTraceBridge, readObservationGrants, readContextSettings, loadContextControlSecret, handleContextControl}=ports);
19
19
  connected=true;
20
20
  }
21
21
 
@@ -41,6 +41,22 @@ function rememberRequest(id,payload,promise,readOnly=false){
41
41
  seen.set(id,{payload,promise});
42
42
  if(seen.size>MAX_REPLAY_RESULTS)seen.delete(seen.keys().next().value);
43
43
  }
44
+ // Bootstrap once from the authenticated single-Project MCP profile. These
45
+ // non-secret settings define the SAME local Store for Native trusted Context
46
+ // as the public MCP child. Never mix profile grants with ambient conflicting
47
+ // runtime configuration, and do not mutate process.env per request.
48
+ const trustedContext=readContextSettings();
49
+ if(trustedContext){
50
+ for(const [key,value] of Object.entries(trustedContext)){
51
+ if(process.env[key]!==undefined&&process.env[key]!==value)
52
+ throw Object.assign(Error('SUPERVISOR_CONTEXT_CONFIG_CONFLICT'),
53
+ {code:'SUPERVISOR_CONTEXT_CONFIG_CONFLICT'});
54
+ }
55
+ if(process.env.CHAT_LOOP_CONTEXT_DB)
56
+ throw Object.assign(Error('SUPERVISOR_CONTEXT_SOURCE_AMBIGUOUS'),
57
+ {code:'SUPERVISOR_CONTEXT_SOURCE_AMBIGUOUS'});
58
+ Object.assign(process.env,trustedContext);
59
+ }
44
60
  const p=paths(), nonce=randomUUID();
45
61
  const error=code=>{
46
62
  const safe=/^[A-Z][A-Z0-9_]{1,95}$/.test(code||'')
@@ -50,6 +50,7 @@ const DOC_ID=/^[A-Za-z0-9][A-Za-z0-9_.-]{7,127}$/;
50
50
  // types. Do not maintain a second pair of regex allowlists beside it.
51
51
  const APP_EVENT_API=Object.freeze({
52
52
  'form.prepared':'mcp.chat_loop_form__prepare',
53
+ 'form.review_link':'mcp.chat_loop_form__prepare',
53
54
  'form.rendered':'mcp.chat_loop_form__render',
54
55
  'form.submitted':'mcp.chat_loop_form__submit',
55
56
  'document.shown':'mcp.chat_loop_document__show',
@@ -120,7 +121,8 @@ async function diagnoseAppTrace(args){
120
121
  if(suffix!=='soft_observed'&&suffix!=='failed')return false;
121
122
  const type=event.event.slice(0,event.event.lastIndexOf('.'));
122
123
  if(!Object.hasOwn(APP_EVENT_API,type))return false;
123
- const idPattern=type.startsWith('form.')?FORM_ID:DOC_ID;
124
+ const idPattern=type==='form.review_link'||type.startsWith('document.')
125
+ ?DOC_ID:FORM_ID;
124
126
  return idPattern.test(event.evidenceRef||'');
125
127
  });
126
128
  const kind=appEvents.length
@@ -163,7 +165,13 @@ async function diagnoseAppTrace(args){
163
165
  &&event.parentSpanId===spanId&&event.status!==terminal.status))
164
166
  gaps.push(prefix+'_API_STATUS_MISMATCH');
165
167
  }
166
- const ids=[...new Set(matching.map(event=>event.evidenceRef))];
168
+ const links=matching.filter(event=>event.event==='form.review_link.soft_observed');
169
+ const primary=matching.filter(event=>event.event!=='form.review_link.soft_observed');
170
+ const ids=[...new Set(primary.map(event=>event.evidenceRef))];
171
+ if(links.length>1||links.some(event=>!event.taskRef))
172
+ gaps.push('FORM_REVIEW_LINK_AMBIGUOUS');
173
+ if(links.length&&!primary.some(event=>event.event==='form.prepared.soft_observed'))
174
+ gaps.push('FORM_PREPARE_NOT_OBSERVED');
167
175
  if(ids.length>1)gaps.push(prefix+'_TRACE_REF_REUSED');
168
176
  if(appEvents.length!==matching.length)gaps.push('APP_TRACE_REF_CROSS_KIND');
169
177
  if(!matching.length)gaps.push('NO_MATCHING_EVENTS');
@@ -173,7 +181,10 @@ async function diagnoseAppTrace(args){
173
181
  const lastConfirmed=timeline.findLast(event=>event.status==='CONFIRMED');
174
182
  const unknown=matching.some(event=>['UNKNOWN','BLOCKED'].includes(event.status));
175
183
  return {traceId:null,projectRef:'api_system',
176
- ...(kind==='form'?{formTraceRef:args.sessionRef,formId:ids.length===1?ids[0]:null}
184
+ ...(kind==='form'?{formTraceRef:args.sessionRef,formId:ids.length===1?ids[0]:null,
185
+ ...(links.length===1&&links[0].taskRef?{reviewLink:{
186
+ taskId:links[0].taskRef,documentId:links[0].evidenceRef,
187
+ confidence:'CALLER_ASSERTED_SOFT'}}:{})}
177
188
  :kind==='document'?{documentTraceRef:args.sessionRef,documentId:ids.length===1?ids[0]:null}
178
189
  :{appTraceRef:args.sessionRef,appKind:'UNVERIFIED'}),
179
190
  inspected:timeline.length,totalMatched:timeline.length,
@@ -12,12 +12,16 @@ export function createSupervisorTraceBridge({traceWriter,contract,error,
12
12
  };
13
13
  const traceEnabled=()=>observationGrants.CHAT_LOOP_TRACE_API_ENABLE==='1';
14
14
  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;
15
+ // Semantic first-render dedup survives iframe re-mounts, not Supervisor restarts.
16
+ // Every actual MCP render invocation retains its own independent API span.
17
+ const firstRenders=new Map(),MAX_FIRST_RENDERS=2048;
15
18
  function handleTraceObservation(req){
16
19
  // Internal Context audit collection uses its own exact single-project
17
20
  // grant. Public Trace MCP observation/diagnosis remains opt-in and does
18
21
  // not become reachable merely because Context collection is active.
19
22
  const isContextApi=req?.event==='context.api';
20
- const form=/^form\.(prepared|rendered|submitted)\.(soft_observed|failed)$/.test(req?.event||'');
23
+ const form=/^form\.(prepared|rendered|submitted)\.(soft_observed|failed)$/.test(req?.event||'')
24
+ ||req?.event==='form.review_link.soft_observed';
21
25
  const document=/^document\.(shown|rendered)\.(soft_observed|failed)$/.test(req?.event||'');
22
26
  const contextGrant=observationGrants.CHAT_LOOP_CONTEXT_ALLOWED_PROJECTS;
23
27
  const contextAuthorized=observationGrants.CHAT_LOOP_CONTEXT_API_ENABLE==='1'
@@ -76,8 +80,10 @@ export function createSupervisorTraceBridge({traceWriter,contract,error,
76
80
  }
77
81
  if(form||document){
78
82
  const success=req.event.endsWith('.soft_observed');
83
+ const reviewLink=req.event==='form.review_link.soft_observed';
79
84
  const allowed=new Set(['contract','action','requestId','traceId','spanId',
80
- 'projectRef','sessionRef','evidenceRef','event','status','errorCode']);
85
+ 'projectRef','sessionRef','evidenceRef','event','status','errorCode',
86
+ ...(reviewLink?['taskRef']:[])]);
81
87
  const validError=typeof req.errorCode==='string'
82
88
  &&/^[A-Z][A-Z0-9_]{1,95}$/.test(req.errorCode);
83
89
  if(req.contract!==CONTRACT||req.projectRef!=='api_system'
@@ -85,16 +91,31 @@ export function createSupervisorTraceBridge({traceWriter,contract,error,
85
91
  ||!UUID_RE.test(req.requestId||'')||!UUID_RE.test(req.traceId||'')
86
92
  ||!UUID_RE.test(req.spanId||'')
87
93
  ||!UUID_RE.test(req.sessionRef||'')
88
- ||!(document?/^[A-Za-z0-9][A-Za-z0-9_.-]{7,127}$/:
94
+ ||!(document||reviewLink?/^[A-Za-z0-9][A-Za-z0-9_.-]{7,127}$/:
89
95
  /^[A-Za-z0-9][A-Za-z0-9_-]{7,79}$/).test(req.evidenceRef||'')
96
+ ||(reviewLink&&(!/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/.test(req.taskRef||'')
97
+ ||!success))
90
98
  ||(success?req.errorCode!==undefined:!validError)
91
99
  ||Object.keys(req).some(k=>!allowed.has(k)))
92
100
  throw error('TRACE_INVALID_ARGUMENT');
101
+ const firstRender=success&&/^(form|document)\.rendered\.soft_observed$/.test(req.event);
102
+ const key=firstRender
103
+ ?req.event+':'+req.sessionRef+':'+req.evidenceRef:null;
104
+ if(key&&firstRenders.has(key))return {contract:CONTRACT,
105
+ requestId:req.requestId,status:'OK',eventId:firstRenders.get(key)};
93
106
  const written=traceWriter.record({traceId:req.traceId,
94
107
  parentSpanId:req.spanId,sessionRef:req.sessionRef,projectRef:'api_system',
95
108
  requestId:req.requestId,component:'gateway',event:req.event,
96
109
  status:req.status,...(req.errorCode?{errorCode:req.errorCode}:{}),
97
- evidenceRef:req.evidenceRef});
110
+ evidenceRef:req.evidenceRef,
111
+ ...(reviewLink?{taskRef:req.taskRef}:{})});
112
+ // Only a successfully persisted first render can suppress later
113
+ // semantic duplicates. An unknown write is never cached as success.
114
+ if(key&&UUID_RE.test(written.eventId)){
115
+ firstRenders.set(key,written.eventId);
116
+ if(firstRenders.size>MAX_FIRST_RENDERS)
117
+ firstRenders.delete(firstRenders.keys().next().value);
118
+ }
98
119
  return {contract:CONTRACT,requestId:req.requestId,status:'OK',
99
120
  eventId:written.eventId};
100
121
  }
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tomflow/chatloop-context",
3
- "version": "0.6.16",
3
+ "version": "0.6.17",
4
4
  "type": "module",
5
5
  "description": "Independent local Context SDK and short-lived CLI for Chat Loop projects",
6
6
  "publishConfig": {
@@ -34,7 +34,7 @@
34
34
  },
35
35
  "dependencies": {
36
36
  "ps-list": "9.0.0",
37
- "@tomflow/chatloop-extension": "0.4.22",
37
+ "@tomflow/chatloop-extension": "0.4.25",
38
38
  "@tomflow/chatloop-trace": "0.4.6"
39
39
  }
40
40
  }
@@ -42,7 +42,7 @@ The builder creates their isolated Action HTML, which uses the same
42
42
  dispatch switch needs modification. The builder refuses duplicate names,
43
43
  privileged type changes, invalid read modes, missing assets and stale output.
44
44
 
45
- **A declaration does not grant sending authority.** The separately reviewed `entry test` Action is a TEST_ONLY, Native-authorized first-turn fixture: it requires an explicit confirmation, creates one ordinary Chat with a real structured @ App mention, and must prove the unique user message without a Browser Owner; it cannot approve R/P or invoke Start/Continue/Handoff. Its explicit privilege review is allowlisted by exact ID, route, page, deadline and receipt format. Any other new sending declaration is denied. Start, Continue, Handoff,
45
+ **A declaration does not grant sending authority.** The separately reviewed `entry test` Action is a TEST_ONLY, Native-authorized first-turn fixture: it requires an explicit confirmation, creates one ordinary Chat with a real structured @ App mention, and must prove the unique user message without a Browser Owner; it cannot approve R/P or invoke Start/Continue/Handoff. Its explicit privilege review is allowlisted by exact ID, route, page, deadline and receipt format. When no ChatGPT tab exists, only this TEST_ONLY Action may open in the one Chrome window containing the verified exact extension details page; the Action itself creates the normal Chat. Other Actions still require the unique current ChatGPT window. Any other new sending declaration is denied. Start, Continue, Handoff,
46
46
  Clean, Status, screenshot and reload keep their reviewed, explicit Worker
47
47
  handlers and existing trust boundaries. New send/Owner/Native mutation
48
48
  requires a separate authorized security review and implementation; it cannot
@@ -81,7 +81,15 @@ For the installed command list, run `chatloop-extension extension --help`.
81
81
  `extension start` requires the real approved intent; `mode=adopt` does not
82
82
  re-send. Continue/Handoff only register intents with one Turn token and never
83
83
  silently send or repeat. Clean needs an exact verified tab ID, and Status
84
- is read-only. IPC messages are one-shot and have durable identity checks.
84
+ is read-only. A previously BLOCKED Session with a lost old Owner tab remains
85
+ `state:BLOCKED` (not `IDLE`) when Worker/Native identities agree; the
86
+ `oldOwnerTabStatus:MISSING_UNVERIFIED` diagnostic is not a replacement permit.
87
+ A missing ACTIVE Owner or mismatched Native pointer remains `UNVERIFIED`.
88
+ Explicit Adopt of a different approved Task still requires the exact old
89
+ Session ID, old Context fence, and a fresh Start lease. Two distinct genuine
90
+ Form A-confirmation user Turns may serve as SOFT R/P evidence in an explicitly
91
+ specified original Chat; this never substitutes for Context approval or Start
92
+ permission. IPC messages are one-shot and have durable identity checks.
85
93
 
86
94
  This package's source version is read from its own `package.json`. Installed
87
95
  Tools/Context consumers may pin a different Extension version; updating
@@ -16,9 +16,32 @@ if (message?.type === "CHAT_LOOP_APPROVAL_EVIDENCE_V1") {
16
16
  .filter(x=>["user","assistant"].includes(x.role));
17
17
  const textOf=x=>(x.el.querySelector?.(".markdown")?.innerText
18
18
  ||x.el.innerText||x.el.textContent||"").trim();
19
+ // Current independent Form App submits exactly one original user Turn.
20
+ // Its A-choice receipt differs from older issue-scoped prose. Match the
21
+ // full bounded host template, two UUIDs, choice and R/P-labelled version;
22
+ // a summary, B-choice or casual affirmation is not Form evidence.
23
+ // This is SOFT evidence only: a text-shaped copy is not host-signed,
24
+ // so Context's independent Start lease remains mandatory.
25
+ const formApprovalVersion=(value,type)=>{
26
+ const lines=value.split(/\r?\n/).map(x=>x.trim()).filter(Boolean);
27
+ if(lines.length!==6
28
+ ||lines[0]!=='Chat Loop Form 提交结果(由用户点击表单提交)'
29
+ ||!/^formId:\s*[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}$/i.test(lines[1])
30
+ ||!/^traceRef:\s*[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}$/i.test(lines[2])
31
+ ||lines[3]!=='选项值: A'
32
+ ||lines[5]!=='请核对当前业务任务、文档与 Issue 版本及原生消息身份后处理本次选择;表单回执本身不构成审批或写权。')
33
+ return null;
34
+ const label=lines[4].match(/^选项标签:\s*A[||]\s*确认当前\s*([RP][1-9][0-9]*)\s*(需求|技术与验证方案|技术方案|方案)$/i);
35
+ if(!label||label[1][0].toUpperCase()!==type
36
+ ||(type==='R')!==(label[2]==='需求'))return null;
37
+ const formId=lines[1].slice('formId:'.length).trim().toLowerCase();
38
+ const traceRef=lines[2].slice('traceRef:'.length).trim().toLowerCase();
39
+ return formId===traceRef?null:{version:label[1].toUpperCase(),formId,traceRef};
40
+ };
19
41
  const confirms=(value,type)=>{
20
42
  const line=value.replace(/\s+/g," ").trim();
21
43
  if(!line||line.length>500)return false;
44
+ if(formApprovalVersion(value,type))return true;
22
45
  // Native R/P review controls send two explicit, task-scoped fields:
23
46
  // "TASK|Rn-ISSUE:<uuid>|我确认 Rn vN。" (and the Pn equivalent).
24
47
  // Accept only a matching kind+version from a genuine user message,
@@ -73,7 +96,18 @@ if (message?.type === "CHAT_LOOP_APPROVAL_EVIDENCE_V1") {
73
96
  return versions.length===1?versions[0]:null;
74
97
  };
75
98
  const lastUser=rows.findLastIndex(x=>x.role==="user");
76
- if(lastUser<3 || rows[lastUser-1].role!=="assistant") {
99
+ // ChatGPT can virtualize the initial R issuing assistant while keeping
100
+ // both original Form A user Turns and the issued P assistant mounted.
101
+ // Only an explicitly named current Chat plus the exact Form template
102
+ // may use this bounded partial-DOM proof. A Context Start lease must
103
+ // still independently authorize the R/P approvals and current Task.
104
+ const currentChatId=path.match(/\/c\/([0-9a-f-]{12,})$/i)?.[1].toLowerCase();
105
+ const explicitFormChat=typeof message.explicitChatId==='string'
106
+ &&message.explicitChatId.toLowerCase()===currentChatId;
107
+ const virtualizedR=lastUser===2&&explicitFormChat
108
+ &&rows[0]?.role==='user'&&!!formApprovalVersion(textOf(rows[0]),'R')
109
+ &&rows[1]?.role==='assistant'&&rows[2]?.role==='user';
110
+ if((lastUser<3&&!virtualizedR)||rows[lastUser-1]?.role!=="assistant") {
77
111
  fail("APPROVAL_SEQUENCE_UNVERIFIED");return false;
78
112
  }
79
113
  const pUser=rows[lastUser],pAssistant=rows[lastUser-1];
@@ -101,6 +135,12 @@ if (message?.type === "CHAT_LOOP_APPROVAL_EVIDENCE_V1") {
101
135
  // This fallback is ONLY for native issue-scoped approvals. The Native
102
136
  // Context Start lease independently verifies the effective R approval.
103
137
  const rUser=rIndex>=0?rows[rIndex]:null;
138
+ const rForm=rUser?formApprovalVersion(textOf(rUser),'R'):null;
139
+ const pForm=formApprovalVersion(textOf(pUser),'P');
140
+ if(rForm&&pForm&&(rForm.formId===pForm.formId
141
+ ||rForm.traceRef===pForm.traceRef)){
142
+ fail('APPROVAL_FORM_REUSED');return false;
143
+ }
104
144
  const nativeR=rUser&&textOf(rUser).match(/^[A-Z][A-Z0-9._:-]{7,120}[||]\s*(R[1-9][0-9]*)-ISSUE:[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}[||]\s*我确认\s+(R[1-9][0-9]*)\s+v([1-9][0-9]*)[。.!!]/i);
105
145
  const nativeRVersion=nativeR
106
146
  &&nativeR[1].toUpperCase()===nativeR[2].toUpperCase()
@@ -108,6 +148,7 @@ if (message?.type === "CHAT_LOOP_APPROVAL_EVIDENCE_V1") {
108
148
  ?nativeR[1].toUpperCase():null;
109
149
  const rAssistant=rIndex>0?rows[rIndex-1]:null;
110
150
  if(rIndex<0 || rIndex===0&&!nativeRVersion
151
+ &&!(virtualizedR&&rForm)
111
152
  ||rIndex>0&&rAssistant?.role!=="assistant"){
112
153
  fail("APPROVAL_REQUIREMENTS_MISSING");return false;
113
154
  }
@@ -140,7 +181,8 @@ if (message?.type === "CHAT_LOOP_APPROVAL_EVIDENCE_V1") {
140
181
  || !/\bR[1-9][0-9]*\b/i.test(textOf(rAssistant)))) {
141
182
  fail("APPROVAL_REQUIREMENTS_MISSING");return false;
142
183
  }
143
- const rVersion=rAssistant?versionOf(textOf(rAssistant),"R"):nativeRVersion;
184
+ const rVersion=rAssistant?versionOf(textOf(rAssistant),"R")
185
+ :nativeRVersion||virtualizedR&&rForm?.version;
144
186
  // A stage-02 plan can generate an immutable Rn synchronization SNAPSHOT
145
187
  // after its P approval. It is not a new R approval: Context retains the
146
188
  // original R/P approvals and exact P.requirementRef. Only a precisely
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "manifest_version": 3,
3
3
  "name": "Chat Loop Extension",
4
- "version": "0.4.22",
4
+ "version": "0.4.25",
5
5
  "description": "Chat Loop browser companion: Eye actions, Turn observer, Continue and Handoff Actions",
6
6
  "permissions": [
7
7
  "activeTab",
@@ -47,8 +47,29 @@ async function sessionStartPrepare(message,sender){
47
47
  const independentTask=Boolean(intent.mode==='adopt'&&intent.contextLeaseRef
48
48
  &&intent.taskId && (!prior?.taskId && !prior?.contextManaged
49
49
  ||prior?.taskId&&prior.taskId!==intent.taskId));
50
+ // A first Adopt that failed BEFORE permit.consume completed has no Chat
51
+ // send, tab binding, or Context writer. A fresh Context lease (which
52
+ // independently requires runRef=null) may replace this exact BLOCKED
53
+ // pre-permit Session at most once for the SAME approved Task. Unknown
54
+ // post-permit / browser outcomes are never eligible for this route.
55
+ const prePermitRecovery=Boolean(prior?.phase==='BLOCKED'
56
+ &&prior.reason==='CONTEXT_START_PERMIT_UNVERIFIED'
57
+ &&prior.action==='START'&&prior.mode==='adopt'
58
+ &&prior.contextLeaseRef&&!prior.prePermitRetryUsed
59
+ &&!prior.contextManaged&&prior.projectId===intent.projectId
60
+ &&prior.taskId===intent.taskId&&intent.mode==='adopt'
61
+ &&intent.contextLeaseRef&&intent.contextLeaseRef!==prior.contextLeaseRef
62
+ &&prior.contextStoreEpoch===intent.contextStoreEpoch
63
+ &&prior.contextTaskRevision===intent.contextTaskRevision
64
+ &&prior.contextApprovalRevision===intent.contextApprovalRevision
65
+ &&prior.tabId===null&&prior.page==='/'&&!prior.newUserKey
66
+ &&!prior.userKey&&!prior.attemptedNewTabId
67
+ &&!!intent.chatUrl&&prior.adoptPage===pathOf(intent.chatUrl)
68
+ &&Number.isInteger(prior.adoptTabId)
69
+ &&typeof prior.adoptUserKey==='string');
50
70
  const matchingBlocked=prior?.phase==='BLOCKED' && prior.sessionId===replace
51
- && (prior.projectId!==intent.projectId || independentTask);
71
+ && (prior.projectId!==intent.projectId || independentTask
72
+ ||prePermitRecovery);
52
73
  if(replace&&!matchingBlocked)return {status:'DENIED',code:'BLOCKED_REPLACEMENT_MISMATCH'};
53
74
  if(prior&&prior.phase!=='DONE'&&!matchingBlocked)
54
75
  return {status:'DENIED',code:'LOOP_ALREADY_ACTIVE'};
@@ -112,6 +133,7 @@ async function sessionStartPrepare(message,sender){
112
133
  page:'/',tabId:null,startedAt:Date.now(),
113
134
  machineRequestId:message.requestId,machineActionTabId:sender.tab.id,
114
135
  ...(matchingBlocked?{replacedBlockedSessionId:replace}:{}),
136
+ ...(prePermitRecovery?{prePermitRetryUsed:true}:{}),
115
137
  ...(adoption?{mode:'adopt',adoptTabId:adoption.target.tabId,
116
138
  adoptPage:adoption.target.page,adoptUserKey:adoption.target.userKey,
117
139
  ...((intent.chatUrl||adoption.target.explicitChatId)
@@ -170,10 +170,18 @@ async function sessionStatus(message,sender){
170
170
  const projectContext=disk.contextStatus==='VERIFIED'
171
171
  &&disk.projectContext?.projectId===run.projectId
172
172
  ?disk.projectContext:null;
173
+ let blockedOwnerTabMissing=false;
173
174
  if(record.activeChatId&&['WAITING_REPLY','BLOCKED'].includes(run.phase)){
174
175
  const tab=await chrome.tabs.get(run.tabId).catch(()=>null);
175
- if(!tab||pathOf(tab.url)!==run.page)
176
- return {status:'UNVERIFIED',code:'OWNER_TAB_MISSING',session:record};
176
+ if(!tab||pathOf(tab.url)!==run.page){
177
+ // A missing tab for the OLD, already-BLOCKED Session is a locator
178
+ // diagnostic, not a conclusion about a different newly approved Task.
179
+ // Native/Worker identity above must still match; the independent new
180
+ // Start must separately prove the exact replacement and Context fence.
181
+ if(run.phase!=='BLOCKED')
182
+ return {status:'UNVERIFIED',code:'OWNER_TAB_MISSING',session:record};
183
+ blockedOwnerTabMissing=true;
184
+ }
177
185
  }
178
186
  // Identity comes from the verified Worker projection, but updatedAt is
179
187
  // Native's durable CAS revision. Never report a synthetic timestamp as a
@@ -187,7 +195,10 @@ async function sessionStatus(message,sender){
187
195
  ...(run.lastStartFailureCode?{lastStartFailureCode:run.lastStartFailureCode}:{}),
188
196
  // The numeric tab ID is a locator, never a send capability. Expose only
189
197
  // for an exactly verified terminal/awaiting Owner, not a guessed tab.
190
- ownerTabId:['WAITING_REPLY','BLOCKED'].includes(run.phase)?run.tabId:null,
198
+ ownerTabId:blockedOwnerTabMissing?null
199
+ :['WAITING_REPLY','BLOCKED'].includes(run.phase)?run.tabId:null,
200
+ ...(blockedOwnerTabMissing
201
+ ?{oldOwnerTabStatus:'MISSING_UNVERIFIED'}:{}),
191
202
  reason:run.reason||null,action:run.action||null,
192
203
  userKey:run.userKey||null,assistantKey:run.assistantKey||null,
193
204
  newUserKey:run.newUserKey||null,recoveryAttempts:run.recoveryAttempts||0,
@@ -25,14 +25,57 @@ const OPEN_IN_CHAT_WINDOW = `on run argv
25
25
  end tell
26
26
  end run`;
27
27
 
28
+ // Entry TEST_ONLY may bootstrap a normal Chat when there is no existing
29
+ // ChatGPT tab. In that case require exactly one Chrome window containing the
30
+ // explicitly verified Chat Loop extension details page. Never select a random
31
+ // Chrome window or another profile, and never create a Chat tab here.
32
+ const OPEN_TEST_ENTRY_WINDOW = `on run argv
33
+ set destination to item 1 of argv
34
+ set managerURL to item 2 of argv
35
+ tell application "Google Chrome"
36
+ set chatWindowIds to {}
37
+ repeat with w in windows
38
+ set hasChat to false
39
+ repeat with t in tabs of w
40
+ try
41
+ if (URL of t) starts with "https://chatgpt.com/" then set hasChat to true
42
+ end try
43
+ end repeat
44
+ if hasChat then set end of chatWindowIds to id of w
45
+ end repeat
46
+ if (count of chatWindowIds) is 1 then
47
+ set ownWindow to window id (item 1 of chatWindowIds)
48
+ else
49
+ if (count of chatWindowIds) is not 0 then error "CHATGPT_WINDOW_AMBIGUOUS" number 103
50
+ set managerWindowIds to {}
51
+ repeat with w in windows
52
+ set hasManager to false
53
+ repeat with t in tabs of w
54
+ try
55
+ if (URL of t) is managerURL then set hasManager to true
56
+ end try
57
+ end repeat
58
+ if hasManager then set end of managerWindowIds to id of w
59
+ end repeat
60
+ if (count of managerWindowIds) is not 1 then error "ENTRY_TEST_WINDOW_UNVERIFIED" number 103
61
+ set ownWindow to window id (item 1 of managerWindowIds)
62
+ end if
63
+ make new tab at end of tabs of ownWindow with properties {URL:destination}
64
+ return "WINDOW=" & (id of ownWindow)
65
+ end tell
66
+ end run`;
67
+
28
68
  export function openExtensionActionPage(url,{platform=process.platform,spawn=spawnSync}={}){
29
69
  if(platform!=='darwin')
30
70
  throw Object.assign(Error('Browser launcher not yet verified on this OS'),
31
71
  {code:'BROWSER_LAUNCH_UNSUPPORTED'});
32
72
  if(!/^chrome-extension:\/\/[a-p]{32}\/[a-z_]+\.html\?requestId=[a-f0-9]{32}$/.test(url))
33
73
  throw Object.assign(Error('Untrusted Extension Action URL'),{code:'INVALID_ACTION_URL'});
34
- const receipt=spawn('osascript',['-e',OPEN_IN_CHAT_WINDOW,url],
35
- {encoding:'utf8',timeout:7000});
74
+ const entry=url.match(/^chrome-extension:\/\/([a-p]{32})\/entry_test\.html\?requestId=[a-f0-9]{32}$/);
75
+ const launchArgs=entry
76
+ ?['-e',OPEN_TEST_ENTRY_WINDOW,url,'chrome://extensions/?id='+entry[1]]
77
+ :['-e',OPEN_IN_CHAT_WINDOW,url];
78
+ const receipt=spawn('osascript',launchArgs,{encoding:'utf8',timeout:7000});
36
79
  if(receipt.error||receipt.status!==0||!/\bWINDOW=\d+\b/.test(receipt.stdout||''))
37
80
  throw Object.assign(Error('Existing ChatGPT Chrome window unavailable or ambiguous'),
38
81
  {code:'CHROME_TARGET_WINDOW_UNVERIFIED'});
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tomflow/chatloop-extension",
3
- "version": "0.4.22",
3
+ "version": "0.4.25",
4
4
  "type": "module",
5
5
  "description": "Chat Loop Extension: reviewed formal Action pages, including TEST_ONLY native App entry",
6
6
  "bin": {
package/package.json CHANGED
@@ -3,7 +3,7 @@
3
3
  "publishConfig": {
4
4
  "access": "public"
5
5
  },
6
- "version": "0.9.52",
6
+ "version": "0.9.54",
7
7
  "type": "module",
8
8
  "description": "Chat Loop local tools: MCP gateway, isolated bundled tunnel-client and unified CLI",
9
9
  "bin": {
@@ -33,11 +33,11 @@
33
33
  "prepack": "node ./scripts/build-providers.mjs --check && node ./scripts/build-form-app.mjs --check && node ./scripts/build-document-app.mjs --check"
34
34
  },
35
35
  "dependencies": {
36
- "@tomflow/chatloop-context": "0.6.16",
36
+ "@tomflow/chatloop-context": "0.6.17",
37
37
  "@tomflow/chatloop-trace": "0.4.6",
38
38
  "@wonderwhy-er/desktop-commander": "0.2.44",
39
39
  "ps-list": "9.0.0",
40
- "@tomflow/chatloop-extension": "0.4.22"
40
+ "@tomflow/chatloop-extension": "0.4.25"
41
41
  },
42
42
  "bundleDependencies": [
43
43
  "@tomflow/chatloop-context",
@@ -23,7 +23,10 @@ const CARD=['title','description','options','submitLabel','footer','textInput'];
23
23
  const REQUIRED_CARD=['title','description','options','submitLabel'];
24
24
  const OPTION=['value','label'];
25
25
  const TEXT_INPUT=['label','placeholder','showWhen','requiredWhen','maxLength','rows'];
26
- const PREP=['formId','card'];
26
+ const PREP=['formId','card','reviewRef'];
27
+ const REVIEW=['taskId','documentId'];
28
+ const TASK_ID=/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/;
29
+ const DOC_ID=/^[A-Za-z0-9][A-Za-z0-9_.-]{7,127}$/;
27
30
  const RENDER=['formId','traceRef'];
28
31
  const SUBMIT=['formId','traceRef','selection','input'];
29
32
  const optionSchema={type:'object',additionalProperties:false,required:OPTION,
@@ -53,9 +56,12 @@ const cardSchema={type:'object',additionalProperties:false,required:REQUIRED_CAR
53
56
  }};
54
57
  const tools=[
55
58
  {name:'chat_loop_form__prepare',description:
56
- 'Prepare an independent generic single-select Form with caller-defined options and optional text input. For R/P reviews, the caller shows the complete document in the separate Document App before this Form; never embed document text in the Form or duplicate it in a normal ChatGPT reply. Other callers may use Form independently. Preserve caller formId or generate a UUID and traceRef. Form returns selection data but does not trigger Chat messages, business approvals, or workflow transitions.',
59
+ 'Prepare an independent generic single-select Form with caller-defined options and optional text input. For R/P reviews, show the separate Document App first and optionally pass reviewRef with the verified Task and Document IDs for SOFT Trace correlation only; no document content. Other callers may use Form independently. Preserve caller formId or generate a UUID and traceRef. Form never creates Chat messages, business approvals, or workflow transitions.',
57
60
  inputSchema:{type:'object',additionalProperties:false,required:['card'],
58
- properties:{formId:{type:'string',pattern:FORM_ID.source},card:cardSchema}},
61
+ properties:{formId:{type:'string',pattern:FORM_ID.source},card:cardSchema,
62
+ reviewRef:{type:'object',additionalProperties:false,required:REVIEW,
63
+ properties:{taskId:{type:'string',pattern:TASK_ID.source},
64
+ documentId:{type:'string',pattern:DOC_ID.source}}}}},
59
65
  annotations:{readOnlyHint:false},
60
66
  _meta:{ui:{resourceUri:RESOURCE_URI,visibility:['model','app']},
61
67
  'openai/outputTemplate':RESOURCE_URI,'openai/widgetAccessible':true}},
@@ -135,6 +141,15 @@ function view(args,formId){
135
141
  }:null,
136
142
  submitLabel:card.submitLabel,footer:card.footer??''};
137
143
  }
144
+ async function observeReviewLink(form,reviewRef,traceRef){
145
+ if(!reviewRef)return;
146
+ try{
147
+ const reply=await form?.observe?.({event:'form.review_link.soft_observed',
148
+ taskId:reviewRef.taskId,documentId:reviewRef.documentId,
149
+ traceRef,status:'CONFIRMED'});
150
+ if(reply?.status!=='OK'||!UUID.test(reply.eventId||''))await notifyLost(form);
151
+ }catch{await notifyLost(form)}
152
+ }
138
153
  async function observeForm(form,event,formId,traceRef,errorCode){
139
154
  if(typeof form?.observe!=='function'||!FORM_ID.test(formId||'')
140
155
  ||!UUID.test(traceRef||''))return false;
@@ -154,6 +169,11 @@ function prepare(args){
154
169
  const traceRef=randomUUID();
155
170
  try{
156
171
  check(args,PREP);
172
+ if(args.reviewRef!==undefined&&(!shape(args.reviewRef,REVIEW)
173
+ ||REVIEW.some(key=>!Object.hasOwn(args.reviewRef,key))
174
+ ||!TASK_ID.test(args.reviewRef.taskId||'')
175
+ ||!DOC_ID.test(args.reviewRef.documentId||'')))
176
+ throw fail('FORM_REVIEW_REF_INVALID');
157
177
  checkCard(args)
158
178
  }
159
179
  catch(error){
@@ -217,6 +237,8 @@ export const provider=Object.freeze({
217
237
  const event=isPrepare?'form.prepared.soft_observed':
218
238
  isRender?'form.rendered.soft_observed':'form.submitted.soft_observed';
219
239
  void observeForm(form,event,result.formId,result.traceRef);
240
+ if(isPrepare&&args.reviewRef)
241
+ void observeReviewLink(form,args.reviewRef,result.traceRef);
220
242
  return ok(result);
221
243
  }catch(error){
222
244
  const event=isPrepare?'form.prepared.failed':