@tomflow/chatloop-tools 0.9.16 → 0.9.17

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 (145) hide show
  1. package/index.mjs +4 -0
  2. package/lib/gateway.mjs +15 -3
  3. package/lib/mcp-tool-router.mjs +50 -3
  4. package/node_modules/@tomflow/chatloop-context/README.md +240 -0
  5. package/node_modules/@tomflow/chatloop-context/bin/cli.mjs +48 -0
  6. package/node_modules/@tomflow/chatloop-context/capabilities/approval.mjs +151 -0
  7. package/node_modules/@tomflow/chatloop-context/capabilities/context.mjs +376 -0
  8. package/node_modules/@tomflow/chatloop-context/capabilities/document.mjs +266 -0
  9. package/node_modules/@tomflow/chatloop-context/capabilities/evidence.mjs +134 -0
  10. package/node_modules/@tomflow/chatloop-context/capabilities/presentation.mjs +82 -0
  11. package/node_modules/@tomflow/chatloop-context/capabilities/project.mjs +349 -0
  12. package/node_modules/@tomflow/chatloop-context/capabilities/sdk.mjs +72 -0
  13. package/node_modules/@tomflow/chatloop-context/capabilities/start.mjs +73 -0
  14. package/node_modules/@tomflow/chatloop-context/capabilities/task.mjs +507 -0
  15. package/node_modules/@tomflow/chatloop-context/capabilities.generated.mjs +11 -0
  16. package/node_modules/@tomflow/chatloop-context/docs/interfaces.md +182 -0
  17. package/node_modules/@tomflow/chatloop-context/docs/operator-and-migration.md +277 -0
  18. package/node_modules/@tomflow/chatloop-context/index.mjs +233 -0
  19. package/node_modules/@tomflow/chatloop-context/lib/api-log.mjs +86 -0
  20. package/node_modules/@tomflow/chatloop-context/lib/approval-policy.mjs +24 -0
  21. package/node_modules/@tomflow/chatloop-context/lib/capability-catalog.generated.json +1989 -0
  22. package/node_modules/@tomflow/chatloop-context/lib/capability-router.mjs +67 -0
  23. package/node_modules/@tomflow/chatloop-context/lib/cli-commands.mjs +280 -0
  24. package/node_modules/@tomflow/chatloop-context/lib/context-cli.mjs +298 -0
  25. package/node_modules/@tomflow/chatloop-context/lib/context-migration.mjs +280 -0
  26. package/node_modules/@tomflow/chatloop-context/lib/core/context.mjs +115 -0
  27. package/node_modules/@tomflow/chatloop-context/lib/core/evidence.mjs +51 -0
  28. package/node_modules/@tomflow/chatloop-context/lib/core/health.mjs +55 -0
  29. package/node_modules/@tomflow/chatloop-context/lib/core/migration.mjs +262 -0
  30. package/node_modules/@tomflow/chatloop-context/lib/core/project.mjs +246 -0
  31. package/node_modules/@tomflow/chatloop-context/lib/core/review.mjs +147 -0
  32. package/node_modules/@tomflow/chatloop-context/lib/core/run.mjs +343 -0
  33. package/node_modules/@tomflow/chatloop-context/lib/core/store.mjs +391 -0
  34. package/node_modules/@tomflow/chatloop-context/lib/core/task.mjs +166 -0
  35. package/node_modules/@tomflow/chatloop-context/lib/line-review.mjs +13 -0
  36. package/node_modules/@tomflow/chatloop-context/lib/methods.mjs +111 -0
  37. package/node_modules/@tomflow/chatloop-context/lib/operations.mjs +107 -0
  38. package/node_modules/@tomflow/chatloop-context/lib/orphan-operator.mjs +117 -0
  39. package/node_modules/@tomflow/chatloop-context/lib/process-inventory.mjs +20 -0
  40. package/node_modules/@tomflow/chatloop-context/lib/project-branch.mjs +312 -0
  41. package/node_modules/@tomflow/chatloop-context/lib/project-diagnostic.mjs +153 -0
  42. package/node_modules/@tomflow/chatloop-context/lib/project-guards.mjs +19 -0
  43. package/node_modules/@tomflow/chatloop-context/lib/project-store.mjs +115 -0
  44. package/node_modules/@tomflow/chatloop-context/lib/trusted-run.mjs +86 -0
  45. package/node_modules/@tomflow/chatloop-context/lib/workspace-operator.mjs +169 -0
  46. package/node_modules/@tomflow/chatloop-context/package.json +40 -0
  47. package/node_modules/@tomflow/chatloop-context/scripts/build-capabilities.mjs +114 -0
  48. package/node_modules/@tomflow/chatloop-extension/README.md +94 -0
  49. package/node_modules/@tomflow/chatloop-extension/actions.generated.mjs +11 -0
  50. package/node_modules/@tomflow/chatloop-extension/bin/cli.mjs +141 -0
  51. package/node_modules/@tomflow/chatloop-extension/bin/native-host.mjs +109 -0
  52. package/node_modules/@tomflow/chatloop-extension/capabilities/chat_dom.mjs +1 -0
  53. package/node_modules/@tomflow/chatloop-extension/capabilities/chat_screenshot.mjs +1 -0
  54. package/node_modules/@tomflow/chatloop-extension/capabilities/chat_text.mjs +1 -0
  55. package/node_modules/@tomflow/chatloop-extension/capabilities/clean.mjs +1 -0
  56. package/node_modules/@tomflow/chatloop-extension/capabilities/continue.mjs +1 -0
  57. package/node_modules/@tomflow/chatloop-extension/capabilities/handoff.mjs +1 -0
  58. package/node_modules/@tomflow/chatloop-extension/capabilities/reload.mjs +1 -0
  59. package/node_modules/@tomflow/chatloop-extension/capabilities/start.mjs +1 -0
  60. package/node_modules/@tomflow/chatloop-extension/capabilities/status.mjs +1 -0
  61. package/node_modules/@tomflow/chatloop-extension/extension/actions/clean.js +120 -0
  62. package/node_modules/@tomflow/chatloop-extension/extension/actions/common.js +180 -0
  63. package/node_modules/@tomflow/chatloop-extension/extension/actions/continue.js +322 -0
  64. package/node_modules/@tomflow/chatloop-extension/extension/actions/dom.js +2 -0
  65. package/node_modules/@tomflow/chatloop-extension/extension/actions/handoff.js +378 -0
  66. package/node_modules/@tomflow/chatloop-extension/extension/actions/index.js +2 -0
  67. package/node_modules/@tomflow/chatloop-extension/extension/actions/model-intent.js +54 -0
  68. package/node_modules/@tomflow/chatloop-extension/extension/actions/read-mode.js +9 -0
  69. package/node_modules/@tomflow/chatloop-extension/extension/actions/reload.js +20 -0
  70. package/node_modules/@tomflow/chatloop-extension/extension/actions/screenshot.js +69 -0
  71. package/node_modules/@tomflow/chatloop-extension/extension/actions/start.js +287 -0
  72. package/node_modules/@tomflow/chatloop-extension/extension/actions/status.js +23 -0
  73. package/node_modules/@tomflow/chatloop-extension/extension/actions/text.js +2 -0
  74. package/node_modules/@tomflow/chatloop-extension/extension/background.js +16 -0
  75. package/node_modules/@tomflow/chatloop-extension/extension/clean.html +5 -0
  76. package/node_modules/@tomflow/chatloop-extension/extension/content.js +40 -0
  77. package/node_modules/@tomflow/chatloop-extension/extension/continue.html +9 -0
  78. package/node_modules/@tomflow/chatloop-extension/extension/dom.html +17 -0
  79. package/node_modules/@tomflow/chatloop-extension/extension/handoff.html +9 -0
  80. package/node_modules/@tomflow/chatloop-extension/extension/loop/action-catalog.generated.js +2 -0
  81. package/node_modules/@tomflow/chatloop-extension/extension/loop/api-aspect.generated.js +275 -0
  82. package/node_modules/@tomflow/chatloop-extension/extension/loop/api-observation-queue.generated.js +76 -0
  83. package/node_modules/@tomflow/chatloop-extension/extension/loop/core.js +107 -0
  84. package/node_modules/@tomflow/chatloop-extension/extension/loop/index.js +36 -0
  85. package/node_modules/@tomflow/chatloop-extension/extension/loop/observer-approval.js +227 -0
  86. package/node_modules/@tomflow/chatloop-extension/extension/loop/observer-inspect.js +144 -0
  87. package/node_modules/@tomflow/chatloop-extension/extension/loop/observer-poll.js +171 -0
  88. package/node_modules/@tomflow/chatloop-extension/extension/loop/observer-recovery.js +109 -0
  89. package/node_modules/@tomflow/chatloop-extension/extension/loop/observer.js +154 -0
  90. package/node_modules/@tomflow/chatloop-extension/extension/loop/resources.js +254 -0
  91. package/node_modules/@tomflow/chatloop-extension/extension/manifest.json +42 -0
  92. package/node_modules/@tomflow/chatloop-extension/extension/popup.html +25 -0
  93. package/node_modules/@tomflow/chatloop-extension/extension/popup.js +93 -0
  94. package/node_modules/@tomflow/chatloop-extension/extension/reload.html +17 -0
  95. package/node_modules/@tomflow/chatloop-extension/extension/screenshot.html +17 -0
  96. package/node_modules/@tomflow/chatloop-extension/extension/start.html +6 -0
  97. package/node_modules/@tomflow/chatloop-extension/extension/status.html +6 -0
  98. package/node_modules/@tomflow/chatloop-extension/extension/text.html +17 -0
  99. package/node_modules/@tomflow/chatloop-extension/extension/worker/action-result.js +136 -0
  100. package/node_modules/@tomflow/chatloop-extension/extension/worker/action-take.js +220 -0
  101. package/node_modules/@tomflow/chatloop-extension/extension/worker/admission.js +122 -0
  102. package/node_modules/@tomflow/chatloop-extension/extension/worker/adopt-prepare.js +155 -0
  103. package/node_modules/@tomflow/chatloop-extension/extension/worker/adopt-recovery.js +185 -0
  104. package/node_modules/@tomflow/chatloop-extension/extension/worker/adopt-result.js +120 -0
  105. package/node_modules/@tomflow/chatloop-extension/extension/worker/bootstrap.js +172 -0
  106. package/node_modules/@tomflow/chatloop-extension/extension/worker/manual.js +165 -0
  107. package/node_modules/@tomflow/chatloop-extension/extension/worker/readiness.js +244 -0
  108. package/node_modules/@tomflow/chatloop-extension/extension/worker/router.js +181 -0
  109. package/node_modules/@tomflow/chatloop-extension/extension/worker/scheduler.js +147 -0
  110. package/node_modules/@tomflow/chatloop-extension/extension/worker/turn-failure.js +197 -0
  111. package/node_modules/@tomflow/chatloop-extension/extension/worker/turn-finished.js +200 -0
  112. package/node_modules/@tomflow/chatloop-extension/index.mjs +71 -0
  113. package/node_modules/@tomflow/chatloop-extension/lib/action-routing.mjs +18 -0
  114. package/node_modules/@tomflow/chatloop-extension/lib/api-observation-queue.mjs +74 -0
  115. package/node_modules/@tomflow/chatloop-extension/lib/bridge.mjs +208 -0
  116. package/node_modules/@tomflow/chatloop-extension/lib/browser-launch.mjs +40 -0
  117. package/node_modules/@tomflow/chatloop-extension/lib/context-binding.mjs +45 -0
  118. package/node_modules/@tomflow/chatloop-extension/lib/context-ipc.mjs +111 -0
  119. package/node_modules/@tomflow/chatloop-extension/lib/owner-evidence.mjs +67 -0
  120. package/node_modules/@tomflow/chatloop-extension/lib/session-file.mjs +120 -0
  121. package/node_modules/@tomflow/chatloop-extension/package.json +38 -0
  122. package/node_modules/@tomflow/chatloop-extension/scripts/build-actions.mjs +133 -0
  123. package/node_modules/@tomflow/chatloop-trace/README.md +105 -0
  124. package/node_modules/@tomflow/chatloop-trace/events/context.api.mjs +23 -0
  125. package/node_modules/@tomflow/chatloop-trace/events/typed.api.call.mjs +22 -0
  126. package/node_modules/@tomflow/chatloop-trace/events.generated.mjs +4 -0
  127. package/node_modules/@tomflow/chatloop-trace/index.mjs +59 -0
  128. package/node_modules/@tomflow/chatloop-trace/lib/api-aspect.mjs +273 -0
  129. package/node_modules/@tomflow/chatloop-trace/lib/trace-reader.mjs +265 -0
  130. package/node_modules/@tomflow/chatloop-trace/lib/trace.mjs +205 -0
  131. package/node_modules/@tomflow/chatloop-trace/package.json +30 -0
  132. package/node_modules/@tomflow/chatloop-trace/scripts/build-events.mjs +68 -0
  133. package/node_modules/ps-list/index.d.ts +76 -0
  134. package/node_modules/ps-list/index.js +366 -0
  135. package/node_modules/ps-list/license +9 -0
  136. package/node_modules/ps-list/package.json +44 -0
  137. package/node_modules/ps-list/readme.md +56 -0
  138. package/node_modules/ps-list/vendor/fastlist-0.3.0-x64.exe +0 -0
  139. package/node_modules/ps-list/vendor/fastlist-0.3.0-x86.exe +0 -0
  140. package/package.json +23 -8
  141. package/providers/form.mjs +68 -8
  142. package/scripts/build-form-app.mjs +27 -0
  143. package/ui/form/review-app.js +128 -0
  144. package/ui/form/review.html +859 -0
  145. package/ui/form/review.template.html +45 -0
@@ -0,0 +1,275 @@
1
+ // Canonical Node AOP observer exported by Trace; only MV3 uses a generated copy.
2
+ // Soft evidence only: no parameters, results, URLs, secrets or model content.
3
+ const SAFE=/^[a-zA-Z][a-zA-Z0-9_.:-]{0,126}$/;
4
+ const PACKAGE=/^@[a-z0-9][a-z0-9._-]{0,45}\/[a-z0-9][a-z0-9._-]{0,80}$/;
5
+ const UUID=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
6
+ const safe=(s,fallback='api.unknown')=>typeof s==='string'&&SAFE.test(s)?s:fallback;
7
+ const code=e=>typeof e?.code==='string'&&/^[A-Z][A-Z0-9_]{1,95}$/.test(e.code)
8
+ ?e.code:'API_FAILED';
9
+ const uid=()=>{
10
+ try{return globalThis.crypto.randomUUID()}catch{
11
+ const hex='0123456789abcdef',h=n=>Array.from({length:n},
12
+ ()=>hex[Math.floor(Math.random()*16)]).join('');
13
+ return h(8)+'-'+h(4)+'-4'+h(3)+'-a'+h(3)+'-'+h(12);
14
+ }
15
+ };
16
+ const schedule=typeof setImmediate==='function'?setImmediate:fn=>setTimeout(fn,0);
17
+ const clock=()=>typeof performance!=='undefined'&&typeof performance.now==='function'
18
+ ?performance.now():Date.now();
19
+ const MAX_PENDING=4096,MAX_BATCH=128;
20
+ const CONTEXT_KEY=Symbol.for('chat-loop.observation.async-context.v1');
21
+ // Process-local correlation only, never an authorization or plugin registry.
22
+ const contextStore=()=>{
23
+ if(typeof process==='undefined'||typeof process.getBuiltinModule!=='function')return null;
24
+ try{
25
+ if(!process[CONTEXT_KEY]){
26
+ const {AsyncLocalStorage}=process.getBuiltinModule('node:async_hooks');
27
+ Object.defineProperty(process,CONTEXT_KEY,{
28
+ value:new AsyncLocalStorage(),enumerable:false,configurable:false
29
+ });
30
+ }
31
+ return process[CONTEXT_KEY];
32
+ }catch{return null}
33
+ };
34
+ const validParent=v=>v&&UUID.test(v.traceId||'')&&UUID.test(v.spanId||'');
35
+ function currentApiTrace(){
36
+ try{
37
+ const local=contextStore()?.getStore();
38
+ if(validParent(local))return {traceId:local.traceId,spanId:local.spanId};
39
+ // Child-process context is sanitized correlation metadata, not trust.
40
+ const value=typeof process!=='undefined'?process.env?.CHAT_LOOP_API_PARENT:null;
41
+ if(typeof value!=='string'||value.length>180)return null;
42
+ const parsed=JSON.parse(value);
43
+ return validParent(parsed)?{traceId:parsed.traceId,spanId:parsed.spanId}:null;
44
+ }catch{return null}
45
+ }
46
+ function withApiTraceParent(parent,fn){
47
+ if(typeof fn!=='function')throw TypeError('API_TRACE_CALLBACK_REQUIRED');
48
+ if(!validParent(parent))throw TypeError('API_TRACE_PARENT_INVALID');
49
+ const storage=contextStore();
50
+ return storage?storage.run({traceId:parent.traceId,spanId:parent.spanId},fn):fn();
51
+ }
52
+ function createApiAspect(packageName,{sink,bufferUntilSubscribe=false}={}){
53
+ const packageId=typeof packageName==='string'&&PACKAGE.test(packageName)
54
+ ?packageName:'unknown';
55
+ const queue=[],bootstrap=[],listeners=new Set(),inFlight=new Set(),
56
+ stats={emitted:0,delivered:0,dropped:0,sinkFailures:0};
57
+ let scheduled=false;
58
+ const output=typeof sink==='function'?sink:record=>{
59
+ // Trace's own public factory is called before the Tools observer can
60
+ // subscribe. Retain only bounded metadata until its first subscriber.
61
+ if(bufferUntilSubscribe&&!listeners.size){
62
+ if(bootstrap.length>=MAX_PENDING){stats.dropped++;return false}
63
+ bootstrap.push(record);
64
+ return;
65
+ }
66
+ if(listeners.size){
67
+ const pending=[];
68
+ for(const listener of [...listeners]){
69
+ try{
70
+ const result=listener(record);
71
+ if(result&&typeof result.then==='function')
72
+ pending.push(Promise.resolve(result).then(
73
+ value=>{if(value===false)stats.sinkFailures++},
74
+ ()=>{stats.sinkFailures++}
75
+ ));
76
+ else if(result===false)stats.sinkFailures++;
77
+ }catch{stats.sinkFailures++}
78
+ }
79
+ // The drain boundary must also wait for async subscribers, not merely
80
+ // the event queue. A listener failure stays soft but is diagnosed.
81
+ return pending.length?Promise.all(pending):undefined;
82
+ }
83
+ if(typeof process==='undefined'||!process.stderr?.write||
84
+ process.env.CHAT_LOOP_API_LOG_STDERR==='0'){
85
+ stats.dropped++;
86
+ return false;
87
+ }
88
+ process.stderr.write('CHAT_LOOP_API_LOG '+JSON.stringify(record)+'\n');
89
+ };
90
+ const flush=()=>{
91
+ scheduled=false;
92
+ for(let i=0;i<MAX_BATCH&&queue.length;i++){
93
+ const item=queue.shift();
94
+ try{
95
+ const result=output(item);
96
+ stats.delivered++;
97
+ // A synchronous explicit rejection must never count as successful
98
+ // delivery merely because the queue is empty.
99
+ if(result===false)stats.sinkFailures++;
100
+ if(result&&typeof result.then==='function'){
101
+ const pending=Promise.resolve(result);
102
+ inFlight.add(pending);
103
+ pending.then(value=>{if(value===false)stats.sinkFailures++},
104
+ ()=>{stats.sinkFailures++}).finally(()=>{inFlight.delete(pending)})
105
+ .catch(()=>{stats.sinkFailures++});
106
+ }
107
+ }catch{stats.sinkFailures++}
108
+ }
109
+ if(queue.length){scheduled=true;schedule(flush)}
110
+ };
111
+ const emit=event=>{
112
+ try{
113
+ if(queue.length>=MAX_PENDING){stats.dropped++;return}
114
+ queue.push(Object.freeze(event));stats.emitted++;
115
+ if(!scheduled){scheduled=true;schedule(flush)}
116
+ }catch{stats.dropped++}
117
+ };
118
+ function observe(name,fn,surface='sdk',options={}){
119
+ if(typeof fn!=='function')throw TypeError('API_ASPECT_TARGET_REQUIRED');
120
+ const api=safe(name),layer=safe(surface,'sdk');
121
+ return new Proxy(fn,{
122
+ get(target,key,receiver){
123
+ if(key===Symbol.for('chat-loop.api-observed.v1'))return true;
124
+ return Reflect.get(target,key,receiver);
125
+ },
126
+ apply(target,thisArg,args){
127
+ let started,base;
128
+ try{
129
+ // MCP requests are fresh user operations, not children of a
130
+ // long-lived CLI/server bootstrap event listener registration.
131
+ // Browser callbacks lack Node AsyncLocalStorage; a narrowly scoped
132
+ // explicit parent links the async reply to its actual dispatch span.
133
+ const explicit=validParent(options?.parent)?options.parent:null;
134
+ const callId=uid(),parent=explicit||(layer==='mcp'?null:currentApiTrace());
135
+ started=clock();
136
+ base={contract:'chat-loop.api-call.v1',package:packageId,
137
+ api,surface:layer,callId,
138
+ traceId:parent?.traceId||callId,spanId:callId,
139
+ parentSpanId:parent?.spanId||null};
140
+ }catch{/* Never fail a target due to tracing. */}
141
+ const mark=(phase,error)=>{
142
+ if(!base)return;
143
+ try{
144
+ emit({...base,phase,time:new Date().toISOString(),
145
+ durationMs:phase==='BEGIN'?null:Math.max(0,Math.round(clock()-started)),
146
+ errorCode:phase==='FAILED'?code(error):null});
147
+ }catch{/* Non-authoritative telemetry. */}
148
+ };
149
+ mark('BEGIN');
150
+ // Only sanitized correlation IDs may cross from the AOP boundary into
151
+ // the hosting callback. A faulty observer must never affect the call.
152
+ if(base&&typeof options?.onBegin==='function'){
153
+ try{options.onBegin(Object.freeze({traceId:base.traceId,spanId:base.spanId}));}
154
+ catch{stats.sinkFailures++}
155
+ }
156
+ const execute=()=>Reflect.apply(target,thisArg,args);
157
+ let result;
158
+ try{
159
+ const storage=base?contextStore():null;
160
+ // A context-inspection API must see its caller's span, not the
161
+ // observation span created to record the inspection itself.
162
+ result=storage&&!options?.preserveCallerContext
163
+ ?storage.run({traceId:base.traceId,spanId:base.spanId},execute)
164
+ :execute();
165
+ }catch(e){mark('FAILED',e);throw e}
166
+ const failed=value=>{
167
+ try{return (layer==='mcp'&&value?.isError===true)
168
+ ||(layer==='browser'&&api.startsWith('browser.dispatch.')&&value===false)}
169
+ catch{stats.sinkFailures++;return false}
170
+ };
171
+ const failureCode=()=>({code:layer==='browser'
172
+ ?'BROWSER_MESSAGE_UNHANDLED':'MCP_TOOL_ERROR'});
173
+ // Do not assimilate arbitrary user thenables for telemetry: invoking
174
+ // their then() could cause a second business side effect. Observe native
175
+ // Promises only, otherwise record the synchronous return boundary.
176
+ let nativePromise=false;
177
+ try{nativePromise=result instanceof Promise}catch{stats.sinkFailures++}
178
+ if(nativePromise){
179
+ // Preserve the exact native Promise object and rejection semantics.
180
+ try{Promise.resolve(result).then(
181
+ value=>{
182
+ const isError=failed(value);
183
+ mark(isError?'FAILED':'OK',
184
+ isError?failureCode():undefined);
185
+ },
186
+ error=>mark('FAILED',error)
187
+ ).catch(()=>{stats.sinkFailures++});}
188
+ catch{stats.sinkFailures++}
189
+ return result;
190
+ }
191
+ const isError=failed(result);
192
+ mark(isError?'FAILED':'OK',
193
+ isError?failureCode():undefined);
194
+ return result;
195
+ }});
196
+ }
197
+ // A contract-driven facade for APIs whose safe name/ACL references
198
+ // depend on their arguments (Context). Domain code stays unaware of AOP.
199
+ function described(target,describe,onBegin){
200
+ if(typeof target!=='function'||typeof describe!=='function')
201
+ throw TypeError('API_ASPECT_TARGET_REQUIRED');
202
+ return new Proxy(target,{
203
+ get(fn,key,receiver){
204
+ if(key===Symbol.for('chat-loop.api-observed.v1'))return true;
205
+ return Reflect.get(fn,key,receiver);
206
+ },
207
+ apply(fn,thisArg,args){
208
+ let detail;
209
+ try{detail=describe(args)??{}}catch{detail={api:'api.invalid',mode:'unknown'}}
210
+ const wrapped=observe(detail.api,()=>Reflect.apply(fn,thisArg,args),
211
+ detail.surface??'sdk',{
212
+ onBegin:ids=>{if(typeof onBegin==='function')onBegin(detail,ids)}
213
+ });
214
+ return wrapped();
215
+ }
216
+ });
217
+ }
218
+ // One public method facade for both fixed-name SDK APIs and Context's
219
+ // descriptor-driven APIs. Neither case duplicates Proxy/cache mechanics.
220
+ function mapMethods(instance,wrap,descriptors=null){
221
+ if(!instance||typeof instance!=='object')return instance;
222
+ if(descriptors)
223
+ for(const [key,item] of Object.entries(Object.getOwnPropertyDescriptors(instance)))
224
+ if(typeof item.value==='function'&&!Object.hasOwn(descriptors,key))
225
+ throw TypeError('API_AUDIT_DESCRIPTOR_MISSING:'+key);
226
+ const facade={...instance},cache=new Map();
227
+ return new Proxy(facade,{
228
+ get(object,key,receiver){
229
+ const value=Reflect.get(object,key,receiver);
230
+ if(typeof value!=='function'||typeof key!=='string'
231
+ ||(descriptors&&!Object.hasOwn(descriptors,key)))return value;
232
+ // Existing public proxies already own a complete BEGIN/terminal pair.
233
+ if(value[Symbol.for('chat-loop.api-observed.v1')]===true)return value;
234
+ if(!cache.has(key))cache.set(key,wrap(key,value));
235
+ return cache.get(key);
236
+ },
237
+ set(){return false},defineProperty(){return false},deleteProperty(){return false}
238
+ });
239
+ }
240
+ const describedMethods=(instance,descriptors,onBegin)=>mapMethods(
241
+ instance,(key,value)=>described(value,descriptors[key],onBegin),descriptors);
242
+ const methods=(instance,prefix,surface='sdk')=>mapMethods(
243
+ instance,(key,value)=>observe(prefix+'.'+key,value,surface));
244
+ // Short-lived CLI/Native entrypoints may wait for telemetry *after* replying.
245
+ // No call to drain is made from a business execution path.
246
+ async function drain(timeoutMs=300){
247
+ const budget=Number.isSafeInteger(timeoutMs)?Math.max(0,Math.min(timeoutMs,750)):300;
248
+ const deadline=Date.now()+budget;
249
+ while(queue.length||bootstrap.length||scheduled||inFlight.size){
250
+ if(Date.now()>=deadline)return false;
251
+ await new Promise(resolve=>setTimeout(resolve,Math.min(10,deadline-Date.now())));
252
+ }
253
+ // Clearing a queue is not evidence of successful transport. A failed
254
+ // sink or overflow remains an explicit incomplete audit outcome.
255
+ return stats.dropped===0&&stats.sinkFailures===0;
256
+ }
257
+ const subscribe=observe('subscribeApiLog',listener=>{
258
+ if(typeof listener!=='function')throw TypeError('API_LOG_LISTENER_REQUIRED');
259
+ listeners.add(listener);
260
+ if(bootstrap.length){
261
+ const capacity=Math.max(0,MAX_PENDING-queue.length);
262
+ const replay=bootstrap.splice(0,capacity);
263
+ if(bootstrap.length){stats.dropped+=bootstrap.length;bootstrap.length=0}
264
+ queue.unshift(...replay);
265
+ if(queue.length&&!scheduled){scheduled=true;schedule(flush)}
266
+ }
267
+ return ()=>listeners.delete(listener);
268
+ },'internal');
269
+ return Object.freeze({observe,methods,described,describedMethods,subscribe,drain,
270
+ health:()=>Object.freeze({...stats,pending:queue.length+bootstrap.length,
271
+ bootstrap:bootstrap.length,inFlight:inFlight.size}),
272
+ current:currentApiTrace,withParent:withApiTraceParent});
273
+ }
274
+
275
+ globalThis.ChatLoopApiAspectV1=Object.freeze({createApiAspect});
@@ -0,0 +1,76 @@
1
+ // Keep each API span ordered at the existing single Supervisor writer.
2
+ // Telemetry is best-effort: it neither changes nor retries the business call.
3
+ // Concurrent spans are allowed; BEGIN and terminal of one call never race.
4
+ function createOrderedApiObservationSender(deliver,{parallel=8,capacity=2048}={}){
5
+ if(typeof deliver!=='function'||!Number.isInteger(parallel)||parallel<1||
6
+ !Number.isInteger(capacity)||capacity<2)throw TypeError('OBSERVATION_SENDER_INVALID');
7
+ const waiting=[],active=new Set();
8
+ const health={submitted:0,confirmed:0,dropped:0,failed:0,lastFailureCode:null};
9
+ let running=0,scheduled=false;
10
+ function pump(){
11
+ scheduled=false;
12
+ while(running<parallel){
13
+ const position=waiting.findIndex(({record})=>!active.has(record.callId));
14
+ if(position<0)return;
15
+ const [{record,resolve}]=waiting.splice(position,1),id=record.callId;
16
+ running++;active.add(id);
17
+ let success=false;
18
+ Promise.resolve().then(()=>deliver(record)).then(result=>{
19
+ success=result!==false;
20
+ if(success)health.confirmed++;
21
+ else{health.failed++;health.lastFailureCode='OBSERVATION_REJECTED'}
22
+ },error=>{
23
+ health.failed++;
24
+ health.lastFailureCode=/^[A-Z][A-Z0-9_]{1,95}$/.test(error?.code||'')
25
+ ?error.code:'OBSERVATION_TRANSPORT_FAILED';
26
+ }).finally(()=>{
27
+ // Keep later terminal evidence even when BEGIN transport failed:
28
+ // an orphan terminal is an auditable gap, not an invisible call.
29
+ active.delete(id);running--;resolve(success);schedule();
30
+ });
31
+ }
32
+ }
33
+ function schedule(){
34
+ if(scheduled)return;
35
+ scheduled=true;queueMicrotask(pump);
36
+ }
37
+ function send(record){
38
+ health.submitted++;
39
+ if(waiting.length>=capacity){
40
+ health.dropped++;
41
+ health.lastFailureCode='OBSERVATION_QUEUE_FULL';
42
+ return Promise.resolve(false);
43
+ }
44
+ return new Promise(resolve=>{waiting.push({record,resolve});schedule()});
45
+ }
46
+ return Object.freeze({send,
47
+ health:()=>Object.freeze({...health,pending:waiting.length,inFlight:running})});
48
+ }
49
+
50
+ // One bounded CLI/Native process-exit gate, after the business reply.
51
+ // The Trace AOP queue and this transport have separate async backlogs.
52
+ // Never count "queue empty" as "Writer accepted the records".
53
+ function createObservationDrain(aspect,sender){
54
+ if(typeof aspect?.drain!=='function'||typeof aspect?.health!=='function'
55
+ ||typeof sender?.health!=='function')throw TypeError('OBSERVATION_DRAIN_INVALID');
56
+ return async function drain(timeoutMs=4200){
57
+ const budget=Number.isSafeInteger(timeoutMs)
58
+ ?Math.max(0,Math.min(timeoutMs,6000)):4200;
59
+ const deadline=Date.now()+budget;
60
+ let state;
61
+ do{
62
+ const remaining=Math.max(1,deadline-Date.now());
63
+ await aspect.drain(Math.min(750,remaining));
64
+ const a=aspect.health(),s=sender.health();
65
+ state={pending:a.pending+s.pending,inFlight:a.inFlight+s.inFlight,
66
+ dropped:a.dropped+s.dropped,failed:a.sinkFailures+s.failed,
67
+ submitted:s.submitted,confirmed:s.confirmed,
68
+ lastFailureCode:s.lastFailureCode};
69
+ if(state.pending===0&&state.inFlight===0)break;
70
+ }while(Date.now()<deadline);
71
+ return Object.freeze({...state,status:state.pending||state.inFlight
72
+ ?'TIMEOUT':state.dropped||state.failed?'LOG_GAP':'OK'});
73
+ };
74
+ }
75
+
76
+ globalThis.ChatLoopApiObservationV1=Object.freeze({createOrderedApiObservationSender});
@@ -0,0 +1,107 @@
1
+ // Deterministic protocol primitives. No backend, model call, or business interpretation.
2
+ (() => {
3
+ const MARKER = /^\[CHAT_LOOP_STATUS:(CONTINUE|DONE|BLOCKED|HANDOFF)\]$/;
4
+ const ALL_MARKERS = /\[CHAT_LOOP_STATUS:(?:CONTINUE|DONE|BLOCKED|HANDOFF)\]/g;
5
+ function parseStatus(text) {
6
+ if (typeof text !== "string") return "UNKNOWN";
7
+ const lines = text.trim().split(/\r?\n/);
8
+ const match = MARKER.exec(lines.at(-1)?.trim() || "");
9
+ if (!match) return "UNKNOWN";
10
+ const markers = text.match(ALL_MARKERS) || [];
11
+ // Status is a protocol line, not any occurrence of its token in prose.
12
+ // A reply may describe a previous Turn as, e.g., "it ended with
13
+ // [CHAT_LOOP_STATUS:CONTINUE]" and still legitimately finish with DONE.
14
+ // Require exactly one standalone status line, at the end. Never accept
15
+ // two standalone statuses (even if they have the same value).
16
+ const standalone = lines.filter(line => MARKER.test(line.trim()));
17
+ // Historical HANDOFF packets may embed prior standalone statuses. Keep
18
+ // its compatibility rule while requiring only one HANDOFF token total.
19
+ if (match[1] === "HANDOFF") {
20
+ return markers.filter(v => v === "[CHAT_LOOP_STATUS:HANDOFF]").length === 1
21
+ ? "HANDOFF" : "UNKNOWN";
22
+ }
23
+ if (standalone.length !== 1) return "UNKNOWN";
24
+ return match[1];
25
+ }
26
+ // The Worker owns all Chrome I/O and state transitions. Only deterministic
27
+ // identity, deadline and receipt policy lives here; no second state store.
28
+ const RUN_BUDGET_MS=4*60*60*1000;
29
+ const MODEL_RECEIPT_TTL_MS=24*60*60*1000;
30
+ const pathOf=url=>{
31
+ try{
32
+ const u=new URL(url),path=u.pathname.replace(/\/$/,'');
33
+ return u.origin==='https://chatgpt.com'
34
+ &&/^\/(?:c\/[0-9a-f-]{12,}|g\/[^/]+\/c\/[0-9a-f-]{12,})$/i.test(path)
35
+ ?path:'';
36
+ }catch{return ''}
37
+ };
38
+ const chatIdOf=url=>pathOf(url)?.match(/\/c\/([0-9a-f-]{12,})$/i)?.[1].toLowerCase()||null;
39
+ // Corrupt persisted values cannot extend an Owner past the 4-hour budget.
40
+ const windowMsOf=run=>Number.isSafeInteger(run?.windowMs)&&run.windowMs>0
41
+ ?Math.min(run.windowMs,RUN_BUDGET_MS):RUN_BUDGET_MS;
42
+ const deadlineOf=run=>Number.isSafeInteger(run?.startedAt)&&run.startedAt>0
43
+ ?run.startedAt+windowMsOf(run):null;
44
+ const clockActive=run=>run&&['RESERVED','PENDING','WAITING_REPLY'].includes(run.phase);
45
+ const terminalFenceVerified=run=>!run?.contextManaged||!run?.taskId
46
+ ||run.contextTerminalFence==='CONFIRMED';
47
+ // Keep only bounded metadata. A future timestamp is not valid evidence.
48
+ const receiptHistory=run=>{
49
+ if(!Array.isArray(run?.modelReceipts))return [];
50
+ const now=Date.now();
51
+ return run.modelReceipts.filter(x=>x&&typeof x.id==='string'
52
+ &&Number.isSafeInteger(x.updatedAt)&&x.updatedAt<=now
53
+ &&now-x.updatedAt<MODEL_RECEIPT_TTL_MS).slice(-16);
54
+ };
55
+ const updateModelReceipt=(run,id,change)=>{
56
+ if(!id)return run;
57
+ const records=receiptHistory(run);
58
+ const index=records.findIndex(x=>x.id===id);
59
+ const existing=index>=0?records.splice(index,1)[0]:{id};
60
+ return {...run,modelReceipts:[...records,
61
+ {...existing,...change,id,updatedAt:Date.now()}].slice(-16)};
62
+ };
63
+ const settleModelIntent=(run,status,reason)=>{
64
+ const pending=run?.modelIntent;
65
+ const finished=pending
66
+ ?updateModelReceipt(run,pending.id,{status,
67
+ reason:reason||run.reason||null,
68
+ actualAction:run.action||pending.action,
69
+ checkpointForwarded:false}):run;
70
+ const next={...finished};
71
+ delete next.modelIntent;
72
+ delete next.modelTurnToken;
73
+ return next;
74
+ };
75
+ // Observer supplies raw R/P proof. The Worker only accepts a canonical
76
+ // read-only evidence contract; it does not parse business approval text.
77
+ // This does NOT replace Context's own approval/Run authorizations.
78
+ const normalizeAdoptionEvidence=(proof,expected={})=>{
79
+ if(proof?.contract!=='chat-loop.turn-observer.v1'
80
+ ||proof.status!=='VERIFIED'
81
+ ||typeof proof.page!=='string'
82
+ ||pathOf('https://chatgpt.com'+proof.page)!==proof.page
83
+ ||!/^user:[^\\s]{8,}$/.test(proof.userKey||'')
84
+ ||!/^R[1-9][0-9]*$/.test(proof.rVersion||'')
85
+ ||!/^P[1-9][0-9]*$/.test(proof.pVersion||''))
86
+ return null;
87
+ const evidence={
88
+ page:proof.page,userKey:proof.userKey,
89
+ priorAssistantKey:proof.priorAssistantKey||null,
90
+ rVersion:proof.rVersion,pVersion:proof.pVersion,
91
+ postApprovalAssistantKey:proof.postApprovalAssistantKey||null
92
+ };
93
+ for(const field of Object.keys(expected)){
94
+ if(evidence[field]!==expected[field])return null;
95
+ }
96
+ return evidence;
97
+ };
98
+ const sameAdoptionEvidence=(a,b)=>Boolean(a&&b
99
+ &&['page','userKey','priorAssistantKey','rVersion','pVersion',
100
+ 'postApprovalAssistantKey'].every(field=>a[field]===b[field]));
101
+ // Preserve the original public Core contract used by Observer and Worker.
102
+ globalThis.ChatLoopCoreV1=Object.freeze({parseStatus});
103
+ globalThis.ChatLoopPolicyV1=Object.freeze({pathOf,chatIdOf,
104
+ windowMsOf,deadlineOf,clockActive,terminalFenceVerified,
105
+ MODEL_RECEIPT_TTL_MS,receiptHistory,updateModelReceipt,settleModelIntent,
106
+ normalizeAdoptionEvidence,sameAdoptionEvidence});
107
+ })();
@@ -0,0 +1,36 @@
1
+ // Browser Worker API root; npm index.mjs is for Node only.
2
+ importScripts('loop/core.js','loop/resources.js');
3
+ importScripts('loop/action-catalog.generated.js');
4
+ importScripts('loop/api-aspect.generated.js');
5
+ importScripts('loop/api-observation-queue.generated.js');
6
+ if(typeof globalThis.ChatLoopCoreV1?.parseStatus!=='function'
7
+ ||!globalThis.ChatLoopPolicyV1||!globalThis.ChatLoopResourcesV1)
8
+ throw Error('CHAT_LOOP_WORKER_API_UNAVAILABLE');
9
+ const auditSender=globalThis.ChatLoopApiObservationV1
10
+ ?.createOrderedApiObservationSender(entry=>{
11
+ const native=globalThis.chrome?.runtime?.sendNativeMessage;
12
+ if(typeof native!=='function')return false;
13
+ return Promise.resolve(native('com.tomflow.chatloop.extension',
14
+ {op:'api-observation',record:entry}))
15
+ .then(result=>result?.status==='RECORDED');
16
+ });
17
+ const apiAudit=globalThis.ChatLoopApiAspectV1?.createApiAspect(
18
+ '@tomflow/chatloop-extension',{sink:record=>{
19
+ // The Native transport never changes an Action/Owner result.
20
+ // Per-call ordering avoids a terminal overtaking its BEGIN.
21
+ const entry={callId:record.callId,
22
+ traceId:record.traceId,spanId:record.spanId,
23
+ ...(record.parentSpanId?{parentSpanId:record.parentSpanId}:{}),
24
+ apiName:'extension.'+record.api,phase:record.phase,
25
+ ...(record.durationMs!==null?{durationMs:record.durationMs}:{}),
26
+ ...(record.errorCode?{errorCode:record.errorCode}:{})};
27
+ return auditSender?.send(entry);
28
+ }});
29
+ if(!apiAudit)throw Error('CHAT_LOOP_WORKER_API_OBSERVER_UNAVAILABLE');
30
+ globalThis.ChatLoopWorkerApiV1=Object.freeze({
31
+ audit:apiAudit,
32
+ parseStatus:globalThis.ChatLoopCoreV1.parseStatus,
33
+ policy:globalThis.ChatLoopPolicyV1,
34
+ resources:globalThis.ChatLoopResourcesV1,
35
+ eyeCatalog:globalThis.ChatLoopEyeCatalogV1
36
+ });