@tomflow/chatloop-tools 0.9.44 → 0.9.45

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.
Files changed (74) hide show
  1. package/README.md +6 -2
  2. package/bin/cli.mjs +12 -5
  3. package/index.mjs +33 -9
  4. package/lib/adapters/mcp-child.mjs +142 -30
  5. package/lib/adapters/tunnel.mjs +22 -11
  6. package/lib/context-control-auth.mjs +0 -5
  7. package/lib/context-gateway.mjs +14 -1
  8. package/lib/control.mjs +27 -8
  9. package/lib/extension-cli-contract.mjs +5 -3
  10. package/lib/extension-proxy.mjs +80 -10
  11. package/lib/gateway.mjs +20 -8
  12. package/lib/release-health-checks.mjs +49 -12
  13. package/lib/release-owner-preflight.mjs +1 -2
  14. package/lib/release-upgrade.mjs +6 -2
  15. package/lib/release.mjs +27 -6
  16. package/lib/supervisor-observability.mjs +2 -2
  17. package/lib/supervisor-runtime.mjs +96 -33
  18. package/lib/trace-gateway.mjs +43 -34
  19. package/lib/tunnel.mjs +15 -5
  20. package/node_modules/@tomflow/chatloop-context/README.md +2 -2
  21. package/node_modules/@tomflow/chatloop-context/docs/interfaces.md +1 -1
  22. package/node_modules/@tomflow/chatloop-context/docs/operator-and-migration.md +1 -1
  23. package/node_modules/@tomflow/chatloop-context/lib/api-log.mjs +1 -1
  24. package/node_modules/@tomflow/chatloop-context/lib/approval-policy.mjs +2 -7
  25. package/node_modules/@tomflow/chatloop-context/lib/capability-router.mjs +3 -1
  26. package/node_modules/@tomflow/chatloop-context/lib/cli-commands.mjs +8 -3
  27. package/node_modules/@tomflow/chatloop-context/lib/context-migration.mjs +13 -7
  28. package/node_modules/@tomflow/chatloop-context/lib/core/store.mjs +12 -8
  29. package/node_modules/@tomflow/chatloop-context/lib/core/task.mjs +20 -3
  30. package/node_modules/@tomflow/chatloop-context/lib/project-branch.mjs +8 -4
  31. package/node_modules/@tomflow/chatloop-context/lib/project-store.mjs +5 -3
  32. package/node_modules/@tomflow/chatloop-context/package.json +3 -3
  33. package/node_modules/@tomflow/chatloop-extension/bin/cli.mjs +14 -6
  34. package/node_modules/@tomflow/chatloop-extension/bin/native-host.mjs +26 -7
  35. package/node_modules/@tomflow/chatloop-extension/extension/actions/clean.js +6 -3
  36. package/node_modules/@tomflow/chatloop-extension/extension/actions/common.js +5 -2
  37. package/node_modules/@tomflow/chatloop-extension/extension/actions/continue.js +22 -4
  38. package/node_modules/@tomflow/chatloop-extension/extension/actions/handoff.js +19 -4
  39. package/node_modules/@tomflow/chatloop-extension/extension/actions/model-intent.js +4 -2
  40. package/node_modules/@tomflow/chatloop-extension/extension/actions/start.js +11 -3
  41. package/node_modules/@tomflow/chatloop-extension/extension/actions/status.js +2 -1
  42. package/node_modules/@tomflow/chatloop-extension/extension/loop/api-observation-queue.generated.js +11 -3
  43. package/node_modules/@tomflow/chatloop-extension/extension/loop/observer-approval.js +10 -9
  44. package/node_modules/@tomflow/chatloop-extension/extension/manifest.json +1 -1
  45. package/node_modules/@tomflow/chatloop-extension/extension/popup.js +9 -3
  46. package/node_modules/@tomflow/chatloop-extension/extension/worker/action-result.js +2 -2
  47. package/node_modules/@tomflow/chatloop-extension/extension/worker/action-take.js +8 -10
  48. package/node_modules/@tomflow/chatloop-extension/extension/worker/adopt-prepare.js +7 -2
  49. package/node_modules/@tomflow/chatloop-extension/extension/worker/adopt-recovery.js +2 -1
  50. package/node_modules/@tomflow/chatloop-extension/extension/worker/adopt-result.js +7 -1
  51. package/node_modules/@tomflow/chatloop-extension/extension/worker/bootstrap.js +16 -5
  52. package/node_modules/@tomflow/chatloop-extension/extension/worker/manual.js +5 -7
  53. package/node_modules/@tomflow/chatloop-extension/extension/worker/router.js +12 -3
  54. package/node_modules/@tomflow/chatloop-extension/extension/worker/scheduler.js +35 -21
  55. package/node_modules/@tomflow/chatloop-extension/extension/worker/turn-finished.js +11 -6
  56. package/node_modules/@tomflow/chatloop-extension/lib/api-observation-queue.mjs +11 -3
  57. package/node_modules/@tomflow/chatloop-extension/lib/bridge.mjs +39 -5
  58. package/node_modules/@tomflow/chatloop-extension/lib/context-ipc.mjs +5 -1
  59. package/node_modules/@tomflow/chatloop-extension/lib/owner-evidence.mjs +5 -1
  60. package/node_modules/@tomflow/chatloop-extension/lib/session-file.mjs +27 -3
  61. package/node_modules/@tomflow/chatloop-extension/package.json +2 -2
  62. package/node_modules/@tomflow/chatloop-trace/README.md +7 -2
  63. package/node_modules/@tomflow/chatloop-trace/lib/trace-reader.mjs +66 -36
  64. package/node_modules/@tomflow/chatloop-trace/lib/trace-retention.mjs +17 -4
  65. package/node_modules/@tomflow/chatloop-trace/lib/trace.mjs +30 -6
  66. package/node_modules/@tomflow/chatloop-trace/package.json +1 -1
  67. package/package.json +6 -6
  68. package/providers/context.mjs +5 -1
  69. package/providers/desktop.mjs +23 -6
  70. package/providers/document.mjs +5 -3
  71. package/providers/extension.mjs +6 -4
  72. package/providers/form.mjs +5 -3
  73. package/providers/runtime.mjs +14 -6
  74. package/providers/trace.mjs +3 -2
@@ -1,8 +1,29 @@
1
1
  // Trace Reader: bounded, scoped, read-only diagnostic and API usage views.
2
2
  import {constants as FS,createReadStream,closeSync,fstatSync,openSync} from 'node:fs';
3
- import {createInterface} from 'node:readline';
4
-
5
3
  const MAX_TRACE_READ_BYTES=2*1024*1024*1024;
4
+ const MAX_TRACE_EVENT_IDS=200_000; // Bounded dedup and API-usage state.
5
+ const MAX_LINE_BYTES=8192;
6
+ // readLine interfaces allocate the entire line before exposing it. A torn
7
+ // log without LF may reach gigabytes; retain at most one validated line.
8
+ async function* boundedLines(stream){
9
+ let held='',heldBytes=0,oversize=false;
10
+ for await(const chunk of stream){
11
+ let start=0;
12
+ while(start<chunk.length){
13
+ const end=chunk.indexOf('\n',start);
14
+ const part=chunk.slice(start,end<0?chunk.length:end);
15
+ if(!oversize){
16
+ heldBytes+=Buffer.byteLength(part,'utf8');
17
+ if(heldBytes>MAX_LINE_BYTES){oversize=true;held=''}
18
+ else held+=part;
19
+ }
20
+ if(end<0)break;
21
+ yield oversize?null:held.replace(/\r$/,'');
22
+ held='';heldBytes=0;oversize=false;start=end+1;
23
+ }
24
+ }
25
+ if(oversize||held.length)yield oversize?null:held.replace(/\r$/,'');
26
+ }
6
27
 
7
28
  export function makeTraceReader(options,deps){
8
29
  const {TRACE_SCHEMA_VERSION,fail,validStoredFamily,object,isId,safeScope,
@@ -56,29 +77,44 @@ export function makeTraceReader(options,deps){
56
77
  throw fail('TRACE_PROJECT_SCOPE_REQUIRED');
57
78
  if(!Number.isSafeInteger(maxSegments)||maxSegments<1||maxSegments>5)
58
79
  throw fail('TRACE_ROTATION_INVALID');
80
+ // Both diagnosis and API usage use the same secured segment inventory
81
+ // and aggregate read budget. No second enumeration policy can drift.
82
+ const scopedFiles=()=>{
83
+ const files=[...Array.from({length:maxSegments},(_,i)=>
84
+ filePath+'.'+(maxSegments-i)),filePath]
85
+ .map(path=>({path,stat:secureFile(path)})).filter(x=>x.stat);
86
+ if(files.reduce((total,x)=>total+x.stat.size,0)>MAX_TRACE_READ_BYTES)
87
+ throw fail('TRACE_FILE_TOO_LARGE');
88
+ return files;
89
+ };
90
+ const openVerifiedStream=item=>{
91
+ const fd=openSync(item.path,FS.O_RDONLY|FS.O_NOFOLLOW);
92
+ try{
93
+ const opened=fstatSync(fd);
94
+ if(!opened.isFile()||(opened.mode&0o077)
95
+ ||process.getuid&&opened.uid!==process.getuid())
96
+ throw fail('TRACE_FILE_UNTRUSTED');
97
+ return createReadStream(item.path,{fd,autoClose:true,encoding:'utf8'});
98
+ }catch(error){
99
+ closeSync(fd);
100
+ throw error;
101
+ }
102
+ };
59
103
  async function query(opts){
60
104
  const filter=filterInput(opts,allowedProjects);
61
- const files=[...Array.from({length:maxSegments},(_,i)=>filePath+'.'+(maxSegments-i)),
62
- filePath].map(path=>({path,stat:secureFile(path)})).filter(x=>x.stat);
105
+ const files=scopedFiles();
63
106
  if(!files.length)return {events:[],matched:0,legacyUncorrelated:true,gapped:true,
64
107
  errors:['TRACE_LOG_MISSING'],truncated:false};
65
- if(files.reduce((sum,x)=>sum+x.stat.size,0)>MAX_TRACE_READ_BYTES)
66
- throw fail('TRACE_FILE_TOO_LARGE');
67
108
  const seen=new Set(),events=[],errors=[],writerEpochs=new Set();
68
109
  let matched=0,corrupt=0,legacy=0;
69
110
  for(const item of files){
70
- const fd=openSync(item.path,FS.O_RDONLY|FS.O_NOFOLLOW);
71
- const opened=fstatSync(fd);
72
- if(!opened.isFile()||(opened.mode&0o077)||process.getuid&&opened.uid!==process.getuid()){
73
- closeSync(fd);throw fail('TRACE_FILE_UNTRUSTED');
74
- }
75
- const stream=createReadStream(item.path,{fd,autoClose:true,encoding:'utf8'});
76
- const lines=createInterface({input:stream,crlfDelay:Infinity});
111
+ const stream=openVerifiedStream(item);
77
112
  try{
78
- for await(const line of lines){
79
- if(!line.trim())continue;
80
- if(Buffer.byteLength(line)>8192){corrupt++;continue}
113
+ for await(const line of boundedLines(stream)){
114
+ if(line===null){corrupt++;continue}
115
+ if(!line.trim())continue
81
116
  let entry;try{entry=JSON.parse(line)}catch{corrupt++;continue}
117
+ if(!object(entry)){corrupt++;continue}
82
118
  // v1 is retained read-only evidence, never rewritten or promoted to
83
119
  // the new typed API contract; unknown schemas stay untrusted.
84
120
  if(entry.schemaVersion!==TRACE_SCHEMA_VERSION&&entry.schemaVersion!==1){
@@ -89,12 +125,13 @@ export function makeTraceReader(options,deps){
89
125
  filter.sessionRef&&entry.sessionRef!==filter.sessionRef)continue;
90
126
  if(!validStored(entry)){corrupt++;continue}
91
127
  if(seen.has(entry.eventId))continue;
128
+ if(seen.size>=MAX_TRACE_EVENT_IDS)throw fail('TRACE_EVENT_CAPACITY');
92
129
  seen.add(entry.eventId);matched++;
93
130
  writerEpochs.add(entry.writerEpoch);
94
131
  events.push(publicEvent(entry));
95
132
  if(events.length>filter.maxEvents)events.shift();
96
133
  }
97
- }finally{lines.close();stream.destroy()}
134
+ }finally{stream.destroy()}
98
135
  }
99
136
  if(corrupt)errors.push('TRACE_MALFORMED_LINES');
100
137
  return {events,matched,legacyUncorrelated:legacy>0,gapped:corrupt>0,
@@ -156,25 +193,14 @@ export function makeTraceReader(options,deps){
156
193
  throw fail('TRACE_INVALID_LIMIT');
157
194
  const now=Date.now(),since=now-windowMinutes*60000;
158
195
  const calls=new Map(),seenEvents=new Set();
159
- const files=[...Array.from({length:maxSegments},(_,i)=>
160
- filePath+'.'+(maxSegments-i)),filePath]
161
- .map(path=>({path,stat:secureFile(path)})).filter(x=>x.stat);
162
- if(files.reduce((n,x)=>n+x.stat.size,0)>MAX_TRACE_READ_BYTES)
163
- throw fail('TRACE_FILE_TOO_LARGE');
196
+ const files=scopedFiles();
164
197
  let malformed=0;
165
198
  for(const item of files){
166
- const fd=openSync(item.path,FS.O_RDONLY|FS.O_NOFOLLOW);
167
- const opened=fstatSync(fd);
168
- if(!opened.isFile()||(opened.mode&0o077)
169
- ||process.getuid&&opened.uid!==process.getuid()){
170
- closeSync(fd);throw fail('TRACE_FILE_UNTRUSTED');
171
- }
172
- const stream=createReadStream(item.path,{fd,autoClose:true,encoding:'utf8'});
173
- const lines=createInterface({input:stream,crlfDelay:Infinity});
199
+ const stream=openVerifiedStream(item);
174
200
  try{
175
- for await(const line of lines){
176
- if(!line.trim())continue;
177
- if(Buffer.byteLength(line)>8192){malformed++;continue}
201
+ for await(const line of boundedLines(stream)){
202
+ if(line===null){malformed++;continue}
203
+ if(!line.trim())continue
178
204
  let v;try{v=JSON.parse(line)}catch{malformed++;continue}
179
205
  // New event families provide their own safe usage projection.
180
206
  // A Provider never acquires access to a Project by being registered.
@@ -183,10 +209,14 @@ export function makeTraceReader(options,deps){
183
209
  if(typeof rule?.usageName!=='function')continue;
184
210
  if(!['BEGIN','CONFIRMED','FAILED'].includes(v.status))continue;
185
211
  if(!validStored(v)){malformed++;continue}
186
- if(seenEvents.has(v.eventId))continue;
187
- seenEvents.add(v.eventId);
188
212
  const time=Date.parse(v.time);
189
213
  if(!Number.isFinite(time)||time<since||time>now+60000)continue;
214
+ // Deduplicate only events inside the requested usage window.
215
+ // Old history cannot consume the memory budget of this query.
216
+ if(seenEvents.has(v.eventId))continue;
217
+ if(seenEvents.size>=MAX_TRACE_EVENT_IDS)
218
+ throw fail('TRACE_EVENT_CAPACITY');
219
+ seenEvents.add(v.eventId);
190
220
  let name;
191
221
  try{
192
222
  const view={...v};
@@ -217,7 +247,7 @@ export function makeTraceReader(options,deps){
217
247
  }
218
248
  calls.set(key,call);
219
249
  }
220
- }finally{lines.close();stream.destroy()}
250
+ }finally{stream.destroy()}
221
251
  }
222
252
  // Count calls by their BEGIN inside the time window, never by the
223
253
  // number of log records. An unmatched completion is not a new API call.
@@ -5,7 +5,12 @@ const sameFile=(a,b)=>a.dev===b.dev&&a.ino===b.ino&&a.size===b.size
5
5
  &&a.mtimeMs===b.mtimeMs;
6
6
  const writeAll=(fd,buffer)=>{
7
7
  let offset=0;
8
- while(offset<buffer.length)offset+=writeSync(fd,buffer,offset,buffer.length-offset);
8
+ while(offset<buffer.length){
9
+ const count=writeSync(fd,buffer,offset,buffer.length-offset);
10
+ if(count<=0)throw Object.assign(Error('TRACE_RETENTION_WRITE_INCOMPLETE'),
11
+ {code:'TRACE_RETENTION_WRITE_INCOMPLETE'});
12
+ offset+=count;
13
+ }
9
14
  };
10
15
  function pruneFile(filePath,cutoff,secureFile){
11
16
  const before=secureFile(filePath);
@@ -33,7 +38,14 @@ function pruneFile(filePath,cutoff,secureFile){
33
38
  }catch{}
34
39
  }
35
40
  if(expired){droppedRecords++;droppedBytes+=line.length+(terminated?1:0);}
36
- else{writeAll(output,line);writeAll(output,newline);keptRecords++;}
41
+ else{
42
+ // An unterminated, possibly torn final record is historical evidence.
43
+ // Retention may remove expired records but must not synthesize bytes
44
+ // that were never written, including an otherwise absent final LF.
45
+ writeAll(output,line);
46
+ if(terminated)writeAll(output,newline);
47
+ keptRecords++;
48
+ }
37
49
  };
38
50
  while(position<before.size){
39
51
  const count=readSync(input,chunk,0,Math.min(chunk.length,before.size-position),position);
@@ -64,8 +76,9 @@ function pruneFile(filePath,cutoff,secureFile){
64
76
  pending=Buffer.alloc(0);start=end+1;
65
77
  }
66
78
  }
67
- if(longLine)writeAll(output,newline);
68
- else if(pending.length)keepLine(pending,false);
79
+ // longLine already copied its exact bytes. Its final LF, when present,
80
+ // was copied in the read loop; do not append another one at EOF.
81
+ if(!longLine&&pending.length)keepLine(pending,false);
69
82
  const after=fstatSync(input),current=lstatSync(filePath);
70
83
  if(!sameFile(before,after)||!sameFile(before,current))
71
84
  throw Object.assign(Error('TRACE_RETENTION_SOURCE_CHANGED'),
@@ -1,6 +1,6 @@
1
1
  import {makeTraceReader} from './trace-reader.mjs';
2
2
  import {randomUUID} from 'node:crypto';
3
- import {constants as FS,closeSync,fstatSync,lstatSync,openSync,writeSync,renameSync,unlinkSync} from 'node:fs';
3
+ import {constants as FS,closeSync,fstatSync,lstatSync,openSync,readSync,writeSync,renameSync,unlinkSync} from 'node:fs';
4
4
  import {dirname,isAbsolute} from 'node:path';
5
5
  import {createTraceRetention} from './trace-retention.mjs';
6
6
 
@@ -76,7 +76,6 @@ const nullable=(v,test,code)=>{
76
76
  if(v!==undefined&&v!==null&&!test(v))throw fail(code);
77
77
  return v??null;
78
78
  };
79
- export function createTrace(){return {traceId:randomUUID(),spanId:randomUUID()};}
80
79
  function normalize(v,epoch,seq){
81
80
  keys(v,ALLOWED);
82
81
  if(!EVENT.test(v.event||'')||!COMPONENTS.has(v.component)||
@@ -149,12 +148,25 @@ export function createTraceWriter({
149
148
  throw fail('TRACE_ROTATION_INVALID');
150
149
  const epoch=randomUUID();let seq=0,failures=0,lastError=null,rotations=0;
151
150
  const retention=createTraceRetention({filePath,maxSegments,retentionDays,secureFile});
151
+ const terminated=(fd,size)=>{
152
+ if(size===0)return true;
153
+ const tail=Buffer.allocUnsafe(1);
154
+ return readSync(fd,tail,0,1,size-1)===1&&tail[0]===10;
155
+ };
152
156
  const rotateIfNeeded=lineBytes=>{
153
157
  // Legacy data is never moved until an operator explicitly enables
154
158
  // rotation after preserving its historical evidence.
155
159
  if(!enableRotation)return;
156
160
  const old=secureFile(filePath);
157
161
  if(!old||old.size+lineBytes<=rotateBytes)return;
162
+ // Rotation must not hide a torn active tail in a historical segment
163
+ // while making the next Writer append appear fully confirmed.
164
+ const source=openSync(filePath,FS.O_RDONLY|FS.O_NOFOLLOW);
165
+ try{
166
+ const actual=fstatSync(source);
167
+ if(actual.ino!==old.ino||actual.dev!==old.dev||actual.size!==old.size
168
+ ||!terminated(source,actual.size))throw fail('TRACE_UNTERMINATED_TAIL');
169
+ }finally{closeSync(source)}
158
170
  const oldest=filePath+'.'+maxSegments;
159
171
  if(secureFile(oldest))unlinkSync(oldest);
160
172
  for(let i=maxSegments-1;i>=1;i--){
@@ -169,11 +181,20 @@ export function createTraceWriter({
169
181
  try{
170
182
  rotateIfNeeded(bytes(entry)+1);
171
183
  secureFile(filePath);
172
- fd=openSync(filePath,FS.O_WRONLY|FS.O_APPEND|FS.O_CREAT|FS.O_NOFOLLOW,0o600);
184
+ fd=openSync(filePath,FS.O_RDWR|FS.O_APPEND|FS.O_CREAT|FS.O_NOFOLLOW,0o600);
173
185
  const st=fstatSync(fd);
174
186
  if(!st.isFile()||(st.mode&0o077)||
175
187
  process.getuid&&st.uid!==process.getuid())throw fail('TRACE_FILE_UNTRUSTED');
176
- writeSync(fd,JSON.stringify(entry)+'\n');
188
+ // Fail closed on a partially persisted prior record. A new append
189
+ // must never concatenate onto unverified historical JSONL evidence.
190
+ if(!terminated(fd,st.size))throw fail('TRACE_UNTERMINATED_TAIL');
191
+ const line=Buffer.from(JSON.stringify(entry)+'\n');
192
+ let written=0;
193
+ while(written<line.length){
194
+ const count=writeSync(fd,line,written,line.length-written);
195
+ if(count<=0)throw fail('TRACE_WRITE_INCOMPLETE');
196
+ written+=count;
197
+ }
177
198
  seq++;lastError=null;
178
199
  return {eventId:entry.eventId,traceId:entry.traceId,
179
200
  writerEpoch:epoch,writerSeq:seq};
@@ -196,8 +217,11 @@ export function createTraceWriter({
196
217
  };
197
218
  const health=()=>{
198
219
  const retained=retention.health();
199
- return {status:lastError||retained.error?'TRACE_DEGRADED':'OK',
200
- errorCode:lastError||retained.error,failures,writerEpoch:epoch,writerSeq:seq,
220
+ // A successful later append cannot reconstruct a lost earlier event.
221
+ // Keep the writer degraded for this epoch until an independent audit.
222
+ const historyGap=failures>0?'TRACE_WRITE_HISTORY_GAP':null;
223
+ return {status:lastError||retained.error||historyGap?'TRACE_DEGRADED':'OK',
224
+ errorCode:lastError||retained.error||historyGap,failures,writerEpoch:epoch,writerSeq:seq,
201
225
  rotationEnabled:enableRotation,rotations,retention:retained};
202
226
  };
203
227
  return {record,recordControl,health};
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tomflow/chatloop-trace",
3
- "version": "0.4.5",
3
+ "version": "0.4.6",
4
4
  "description": "Trace SDK and scoped read-only diagnostics for Chat Loop",
5
5
  "type": "module",
6
6
  "engines": {
package/package.json CHANGED
@@ -3,7 +3,7 @@
3
3
  "publishConfig": {
4
4
  "access": "public"
5
5
  },
6
- "version": "0.9.44",
6
+ "version": "0.9.45",
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.12",
37
- "@tomflow/chatloop-trace": "0.4.5",
36
+ "@tomflow/chatloop-context": "0.6.13",
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.12"
40
+ "@tomflow/chatloop-extension": "0.4.13"
41
41
  },
42
42
  "bundleDependencies": [
43
43
  "@tomflow/chatloop-context",
@@ -49,8 +49,8 @@
49
49
  "node": ">=24"
50
50
  },
51
51
  "optionalDependencies": {
52
- "@tomflow/chatloop-tunnel-darwin-arm64": "0.0.25",
53
- "@tomflow/chatloop-tunnel-darwin-x64": "0.0.25"
52
+ "@tomflow/chatloop-tunnel-darwin-arm64": "0.0.26",
53
+ "@tomflow/chatloop-tunnel-darwin-x64": "0.0.26"
54
54
  },
55
55
  "exports": {
56
56
  ".": "./index.mjs"
@@ -1,6 +1,7 @@
1
1
  // Context owns its own schemas, permissions and receipt protocol.
2
2
  import {contextGateway} from '@tomflow/chatloop-context';
3
3
  const names=contextGateway.tools.map(tool=>tool.name);
4
+ const ERROR_CODE=/^[A-Z][A-Z0-9_]{1,95}$/;
4
5
  const fail=code=>({isError:true,content:[{type:'text',text:code}]});
5
6
  export const provider=Object.freeze({
6
7
  id:'context',order:3,names,
@@ -13,7 +14,10 @@ export const provider=Object.freeze({
13
14
  try{
14
15
  const result=await context.runContextGateway(name,args);
15
16
  return {content:[{type:'text',text:JSON.stringify(result)}]};
16
- }catch(e){return fail(e.code||e.message||'CONTEXT_OPERATION_FAILED')}
17
+ }catch(e){
18
+ return fail(ERROR_CODE.test(e?.code||'')
19
+ ?e.code:'CONTEXT_OPERATION_FAILED');
20
+ }
17
21
  }
18
22
  });
19
23
  }
@@ -35,6 +35,8 @@ const fixtureTool={name:'ping',description:'Inert lifecycle test health check',
35
35
  const toolsFor=t=>t.kind==='mcp-child'?desktopTools:t.kind==='fixture'?[fixtureTool]:[];
36
36
  const prefix=id=>id.replaceAll('-','_')+'__';
37
37
  const fail=code=>({isError:true,content:[{type:'text',text:code}]});
38
+ const ERROR_CODE=/^[A-Z][A-Z0-9_]{1,95}$/;
39
+ const uncertain=id=>'OPERATION_UNCONFIRMED:'+id;
38
40
  export const provider=Object.freeze({
39
41
  id:'desktop',order:0,
40
42
  names:[...desktopTools.map(t=>'desktop_commander__'+t.name),
@@ -61,18 +63,33 @@ export const provider=Object.freeze({
61
63
  if(!process.env.CHAT_LOOP_LOCAL_TOOLS_STATE_DIR&&
62
64
  !process.env.CHAT_LOOP_LOCAL_TOOLS_FIXTURES&&release.runtimeNeedsUpgrade())
63
65
  return fail('RUNTIME_UPGRADE_REQUIRED');
66
+ const requestId=randomUUID();
64
67
  try{
65
- const deadlineMs=control.toolCallDeadlineMs(args),requestId=randomUUID();
68
+ const deadlineMs=control.toolCallDeadlineMs(args);
66
69
  const res=await control.talk({contract:control.CONTRACT,requestId,
67
70
  action:'call',scope:'tool',toolId:route.toolId,
68
71
  name:route.localName,args,deadlineMs},deadlineMs+2000);
69
- if(res.status!=='OK')return fail(res.error?.code==='TIMEOUT'
70
- ?'OPERATION_UNCONFIRMED:'+requestId
71
- :res.error?.code||'TOOL_UNAVAILABLE');
72
+ if(res?.contract!==control.CONTRACT||res.requestId!==requestId)
73
+ return fail(uncertain(requestId));
74
+ if(res.status!=='OK'){
75
+ const code=res.error?.code;
76
+ return fail(['TIMEOUT','UNKNOWN_RESULT','TOOL_UNAVAILABLE',
77
+ 'MCP_ERROR','INVALID_REPLY'].includes(code)
78
+ ?uncertain(requestId)
79
+ :ERROR_CODE.test(code||'')?code:'TOOL_UNAVAILABLE');
80
+ }
81
+ if(!res.result||typeof res.result!=='object'
82
+ ||!Array.isArray(res.result.content))
83
+ return fail(uncertain(requestId));
72
84
  return res.result;
73
85
  }catch(e){
74
- return fail(['ENOENT','ECONNREFUSED'].includes(e.code)
75
- ?'TOOL_UNAVAILABLE':e.code||'MANAGER_UNAVAILABLE');
86
+ const code=e?.code;
87
+ if(['TIMEOUT','UNKNOWN_RESULT','INVALID_REPLY','EPIPE',
88
+ 'ECONNRESET','ECONNABORTED'].includes(code))
89
+ return fail(uncertain(requestId));
90
+ return fail(['ENOENT','ECONNREFUSED'].includes(code)
91
+ ?'TOOL_UNAVAILABLE'
92
+ :ERROR_CODE.test(code||'')?code:'MANAGER_UNAVAILABLE');
76
93
  }
77
94
  }
78
95
  });
@@ -12,6 +12,8 @@ const TYPE=/^[a-zA-Z0-9][a-zA-Z0-9.+/-]{0,79}$/;
12
12
  const err=code=>Object.assign(Error(code),{code});
13
13
  const result=data=>({content:[{type:'text',text:JSON.stringify(data)}],
14
14
  structuredContent:data});
15
+ // Trace transport must never reject into a caller's business execution.
16
+ async function notifyLost(port){try{await port?.lost?.()}catch{}}
15
17
  async function observeDocument(port,event,documentId,traceRef,errorCode){
16
18
  if(typeof port?.observe!=='function'||!IDENT.test(documentId||'')
17
19
  ||!UUID.test(traceRef||''))return false;
@@ -20,10 +22,10 @@ async function observeDocument(port,event,documentId,traceRef,errorCode){
20
22
  status:errorCode?'FAILED':'CONFIRMED',
21
23
  ...(errorCode?{errorCode}:{})});
22
24
  if(reply?.status!=='OK'||!UUID.test(reply.eventId||'')){
23
- port?.lost?.();return false;
25
+ await notifyLost(port);return false;
24
26
  }
25
27
  return true;
26
- }catch{port?.lost?.();return false}
28
+ }catch{await notifyLost(port);return false}
27
29
  }
28
30
  const pure=(x,keys)=>x&&typeof x==='object'&&!Array.isArray(x)
29
31
  &&Object.keys(x).every(k=>keys.includes(k));
@@ -38,7 +40,7 @@ const documentSchema={type:'object',additionalProperties:false,
38
40
  }};
39
41
  const tools=[
40
42
  {name:'chat_loop_document__show',
41
- description:'Display an independent rich Document App with full-source copy. Set document.format to text/markdown for Markdown headings, lists and tables (also the default). The caller Skill owns content, versions and approval. Call this BEFORE the separate Form App; never put Form controls in Document.',
43
+ description:'Display an independent rich Document App with full-source copy. Set document.format to text/markdown for Markdown headings, lists and tables (also the default). The caller Skill owns content, versions and approval. For R/P reviews, call this BEFORE the separate Form App; Document may also be used independently. Never put Form controls in Document.',
42
44
  inputSchema:{type:'object',additionalProperties:false,required:['document'],
43
45
  properties:{documentId:{type:'string',pattern:IDENT.source},
44
46
  document:documentSchema}},
@@ -105,10 +105,11 @@ export function validExtensionArgs(name,args){
105
105
  return true;
106
106
  }
107
107
 
108
- // Extension remains the sole Browser Owner. This provider delegates to its
109
- // pinned CLI and never sends a ChatGPT message from the Gateway itself.
108
+ // Extension remains the sole Browser Owner. This provider delegates to the
109
+ // official versioned CLI (resolved via npm latest), never sends from Gateway.
110
110
 
111
111
  const fail=code=>({isError:true,content:[{type:'text',text:code}]});
112
+ const ERROR_CODE=/^[A-Z][A-Z0-9_]{1,95}$/;
112
113
  const prefix='chat_loop_extension__';
113
114
  export const provider=Object.freeze({
114
115
  id:'extension',order:1,
@@ -134,8 +135,9 @@ export const provider=Object.freeze({
134
135
  }catch{/* Logging never changes action status or retry safety. */}
135
136
  });
136
137
  return result;
137
- }catch(e){return fail(['ENOENT','ECONNREFUSED'].includes(e.code)
138
- ?'TOOL_UNAVAILABLE':e.code||'MANAGER_UNAVAILABLE')}
138
+ }catch(e){return fail(['ENOENT','ECONNREFUSED'].includes(e?.code)
139
+ ?'TOOL_UNAVAILABLE'
140
+ :ERROR_CODE.test(e?.code||'')?e.code:'MANAGER_UNAVAILABLE')}
139
141
  }
140
142
  });
141
143
  }
@@ -13,6 +13,8 @@ const UUID=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]
13
13
  const fail=code=>Object.assign(Error(code),{code});
14
14
  const ok=value=>({content:[{type:'text',text:JSON.stringify(value)}],
15
15
  structuredContent:value});
16
+ // Observability failure cannot reject an App business result.
17
+ async function notifyLost(form){try{await form?.lost?.()}catch{}}
16
18
  const filled=(value,max)=>typeof value==='string'
17
19
  &&value.trim().length>0&&value.length<=max;
18
20
  const shape=(value,fields)=>value&&typeof value==='object'
@@ -51,7 +53,7 @@ const cardSchema={type:'object',additionalProperties:false,required:REQUIRED_CAR
51
53
  }};
52
54
  const tools=[
53
55
  {name:'chat_loop_form__prepare',description:
54
- 'Render a generic single-select Form with caller-defined options and optional text input. Business documents belong in the caller ChatGPT message, never in this Form. Preserve caller formId or generate a UUID and traceRef. Form returns selection data but does not trigger Chat messages, business approvals, or workflow transitions.',
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.',
55
57
  inputSchema:{type:'object',additionalProperties:false,required:['card'],
56
58
  properties:{formId:{type:'string',pattern:FORM_ID.source},card:cardSchema}},
57
59
  annotations:{readOnlyHint:false},
@@ -142,10 +144,10 @@ async function observeForm(form,event,formId,traceRef,errorCode){
142
144
  ...(errorCode?{errorCode}:{})
143
145
  });
144
146
  if(result?.status!=='OK'||!UUID.test(result.eventId||'')){
145
- form?.lost?.();return false;
147
+ await notifyLost(form);return false;
146
148
  }
147
149
  return true;
148
- }catch{form?.lost?.();return false}
150
+ }catch{await notifyLost(form);return false}
149
151
  }
150
152
  function prepare(args){
151
153
  const formId=args?.formId===undefined?randomUUID():args.formId;
@@ -18,14 +18,22 @@ export const provider=Object.freeze({
18
18
  ||typeof args.requestId!=='string'
19
19
  ||!requestIdPattern.test(args.requestId))return fail('INVALID_ARGUMENT');
20
20
  try{
21
+ const lookupId=randomUUID();
21
22
  const res=await control.talk({
22
- contract:control.CONTRACT,action:'receipt',requestId:randomUUID(),
23
+ contract:control.CONTRACT,action:'receipt',requestId:lookupId,
23
24
  targetRequestId:args.requestId},4000);
24
- return res.status==='OK'&&res.operation
25
- ?{content:[{type:'text',text:JSON.stringify({operation:res.operation})}]}
26
- :fail('RECEIPT_UNAVAILABLE');
27
- }catch(e){return fail(['ENOENT','ECONNREFUSED'].includes(e.code)
28
- ?'TOOL_UNAVAILABLE':e.code||'MANAGER_UNAVAILABLE')}
25
+ const operation=res?.operation;
26
+ if(res?.contract!==control.CONTRACT||res.requestId!==lookupId
27
+ ||res.status!=='OK'||!operation||typeof operation!=='object'
28
+ ||Array.isArray(operation)
29
+ ||!['RUNNING','COMPLETED','FAILED','UNCONFIRMED','UNKNOWN']
30
+ .includes(operation.state))
31
+ return fail('RECEIPT_UNAVAILABLE');
32
+ return {content:[{type:'text',text:JSON.stringify({operation})}]};
33
+ }catch(e){return fail(['ENOENT','ECONNREFUSED'].includes(e?.code)
34
+ ?'TOOL_UNAVAILABLE'
35
+ :/^[A-Z][A-Z0-9_]{1,95}$/.test(e?.code||'')
36
+ ?e.code:'MANAGER_UNAVAILABLE')}
29
37
  }
30
38
  });
31
39
  }
@@ -1,6 +1,7 @@
1
1
  // Trace observes but never grants business write rights or Browser Owner.
2
2
  import {traceDiagnoseTool,traceStageTool} from '../lib/trace-gateway.mjs';
3
3
  const names=[traceDiagnoseTool.name,traceStageTool.name];
4
+ const ERROR_CODE=/^[A-Z][A-Z0-9_]{1,95}$/;
4
5
  const fail=code=>({isError:true,content:[{type:'text',text:code}]});
5
6
  export const provider=Object.freeze({
6
7
  id:'trace',order:4,names,
@@ -20,8 +21,8 @@ export const provider=Object.freeze({
20
21
  :null;
21
22
  if(result===null)return fail('UNKNOWN_TOOL');
22
23
  return {content:[{type:'text',text:JSON.stringify(result)}]};
23
- }catch(e){return fail(e.code||(
24
- name===traceStageTool.name?'TRACE_STAGE_FAILED':'TRACE_DIAGNOSE_FAILED'))}
24
+ }catch(e){return fail(ERROR_CODE.test(e?.code||'')?e.code:
25
+ name===traceStageTool.name?'TRACE_STAGE_FAILED':'TRACE_DIAGNOSE_FAILED')}
25
26
  }
26
27
  });
27
28
  }