@tomflow/chatloop-tools 0.9.20 → 0.9.22

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 (137) hide show
  1. package/node_modules/@tomflow/chatloop-context/README.md +240 -0
  2. package/node_modules/@tomflow/chatloop-context/bin/cli.mjs +48 -0
  3. package/node_modules/@tomflow/chatloop-context/capabilities/approval.mjs +151 -0
  4. package/node_modules/@tomflow/chatloop-context/capabilities/context.mjs +376 -0
  5. package/node_modules/@tomflow/chatloop-context/capabilities/document.mjs +266 -0
  6. package/node_modules/@tomflow/chatloop-context/capabilities/evidence.mjs +134 -0
  7. package/node_modules/@tomflow/chatloop-context/capabilities/presentation.mjs +82 -0
  8. package/node_modules/@tomflow/chatloop-context/capabilities/project.mjs +349 -0
  9. package/node_modules/@tomflow/chatloop-context/capabilities/sdk.mjs +72 -0
  10. package/node_modules/@tomflow/chatloop-context/capabilities/start.mjs +73 -0
  11. package/node_modules/@tomflow/chatloop-context/capabilities/task.mjs +507 -0
  12. package/node_modules/@tomflow/chatloop-context/capabilities.generated.mjs +11 -0
  13. package/node_modules/@tomflow/chatloop-context/docs/interfaces.md +182 -0
  14. package/node_modules/@tomflow/chatloop-context/docs/operator-and-migration.md +277 -0
  15. package/node_modules/@tomflow/chatloop-context/index.mjs +233 -0
  16. package/node_modules/@tomflow/chatloop-context/lib/api-log.mjs +86 -0
  17. package/node_modules/@tomflow/chatloop-context/lib/approval-policy.mjs +24 -0
  18. package/node_modules/@tomflow/chatloop-context/lib/capability-catalog.generated.json +1989 -0
  19. package/node_modules/@tomflow/chatloop-context/lib/capability-router.mjs +67 -0
  20. package/node_modules/@tomflow/chatloop-context/lib/cli-commands.mjs +280 -0
  21. package/node_modules/@tomflow/chatloop-context/lib/context-cli.mjs +298 -0
  22. package/node_modules/@tomflow/chatloop-context/lib/context-migration.mjs +280 -0
  23. package/node_modules/@tomflow/chatloop-context/lib/core/context.mjs +115 -0
  24. package/node_modules/@tomflow/chatloop-context/lib/core/evidence.mjs +51 -0
  25. package/node_modules/@tomflow/chatloop-context/lib/core/health.mjs +55 -0
  26. package/node_modules/@tomflow/chatloop-context/lib/core/migration.mjs +262 -0
  27. package/node_modules/@tomflow/chatloop-context/lib/core/project.mjs +246 -0
  28. package/node_modules/@tomflow/chatloop-context/lib/core/review.mjs +147 -0
  29. package/node_modules/@tomflow/chatloop-context/lib/core/run.mjs +343 -0
  30. package/node_modules/@tomflow/chatloop-context/lib/core/store.mjs +391 -0
  31. package/node_modules/@tomflow/chatloop-context/lib/core/task.mjs +166 -0
  32. package/node_modules/@tomflow/chatloop-context/lib/line-review.mjs +13 -0
  33. package/node_modules/@tomflow/chatloop-context/lib/methods.mjs +111 -0
  34. package/node_modules/@tomflow/chatloop-context/lib/operations.mjs +107 -0
  35. package/node_modules/@tomflow/chatloop-context/lib/orphan-operator.mjs +117 -0
  36. package/node_modules/@tomflow/chatloop-context/lib/process-inventory.mjs +20 -0
  37. package/node_modules/@tomflow/chatloop-context/lib/project-branch.mjs +312 -0
  38. package/node_modules/@tomflow/chatloop-context/lib/project-diagnostic.mjs +153 -0
  39. package/node_modules/@tomflow/chatloop-context/lib/project-guards.mjs +19 -0
  40. package/node_modules/@tomflow/chatloop-context/lib/project-store.mjs +115 -0
  41. package/node_modules/@tomflow/chatloop-context/lib/trusted-run.mjs +86 -0
  42. package/node_modules/@tomflow/chatloop-context/lib/workspace-operator.mjs +169 -0
  43. package/node_modules/@tomflow/chatloop-context/package.json +40 -0
  44. package/node_modules/@tomflow/chatloop-context/scripts/build-capabilities.mjs +114 -0
  45. package/node_modules/@tomflow/chatloop-extension/README.md +94 -0
  46. package/node_modules/@tomflow/chatloop-extension/actions.generated.mjs +11 -0
  47. package/node_modules/@tomflow/chatloop-extension/bin/cli.mjs +141 -0
  48. package/node_modules/@tomflow/chatloop-extension/bin/native-host.mjs +109 -0
  49. package/node_modules/@tomflow/chatloop-extension/capabilities/chat_dom.mjs +1 -0
  50. package/node_modules/@tomflow/chatloop-extension/capabilities/chat_screenshot.mjs +1 -0
  51. package/node_modules/@tomflow/chatloop-extension/capabilities/chat_text.mjs +1 -0
  52. package/node_modules/@tomflow/chatloop-extension/capabilities/clean.mjs +1 -0
  53. package/node_modules/@tomflow/chatloop-extension/capabilities/continue.mjs +1 -0
  54. package/node_modules/@tomflow/chatloop-extension/capabilities/handoff.mjs +1 -0
  55. package/node_modules/@tomflow/chatloop-extension/capabilities/reload.mjs +1 -0
  56. package/node_modules/@tomflow/chatloop-extension/capabilities/start.mjs +1 -0
  57. package/node_modules/@tomflow/chatloop-extension/capabilities/status.mjs +1 -0
  58. package/node_modules/@tomflow/chatloop-extension/extension/actions/clean.js +120 -0
  59. package/node_modules/@tomflow/chatloop-extension/extension/actions/common.js +180 -0
  60. package/node_modules/@tomflow/chatloop-extension/extension/actions/continue.js +322 -0
  61. package/node_modules/@tomflow/chatloop-extension/extension/actions/dom.js +2 -0
  62. package/node_modules/@tomflow/chatloop-extension/extension/actions/handoff.js +378 -0
  63. package/node_modules/@tomflow/chatloop-extension/extension/actions/index.js +2 -0
  64. package/node_modules/@tomflow/chatloop-extension/extension/actions/model-intent.js +54 -0
  65. package/node_modules/@tomflow/chatloop-extension/extension/actions/read-mode.js +9 -0
  66. package/node_modules/@tomflow/chatloop-extension/extension/actions/reload.js +20 -0
  67. package/node_modules/@tomflow/chatloop-extension/extension/actions/screenshot.js +69 -0
  68. package/node_modules/@tomflow/chatloop-extension/extension/actions/start.js +287 -0
  69. package/node_modules/@tomflow/chatloop-extension/extension/actions/status.js +23 -0
  70. package/node_modules/@tomflow/chatloop-extension/extension/actions/text.js +2 -0
  71. package/node_modules/@tomflow/chatloop-extension/extension/background.js +16 -0
  72. package/node_modules/@tomflow/chatloop-extension/extension/clean.html +5 -0
  73. package/node_modules/@tomflow/chatloop-extension/extension/content.js +40 -0
  74. package/node_modules/@tomflow/chatloop-extension/extension/continue.html +9 -0
  75. package/node_modules/@tomflow/chatloop-extension/extension/dom.html +17 -0
  76. package/node_modules/@tomflow/chatloop-extension/extension/handoff.html +9 -0
  77. package/node_modules/@tomflow/chatloop-extension/extension/loop/action-catalog.generated.js +2 -0
  78. package/node_modules/@tomflow/chatloop-extension/extension/loop/api-aspect.generated.js +275 -0
  79. package/node_modules/@tomflow/chatloop-extension/extension/loop/api-observation-queue.generated.js +76 -0
  80. package/node_modules/@tomflow/chatloop-extension/extension/loop/core.js +107 -0
  81. package/node_modules/@tomflow/chatloop-extension/extension/loop/index.js +36 -0
  82. package/node_modules/@tomflow/chatloop-extension/extension/loop/observer-approval.js +227 -0
  83. package/node_modules/@tomflow/chatloop-extension/extension/loop/observer-inspect.js +144 -0
  84. package/node_modules/@tomflow/chatloop-extension/extension/loop/observer-poll.js +171 -0
  85. package/node_modules/@tomflow/chatloop-extension/extension/loop/observer-recovery.js +109 -0
  86. package/node_modules/@tomflow/chatloop-extension/extension/loop/observer.js +154 -0
  87. package/node_modules/@tomflow/chatloop-extension/extension/loop/resources.js +254 -0
  88. package/node_modules/@tomflow/chatloop-extension/extension/manifest.json +42 -0
  89. package/node_modules/@tomflow/chatloop-extension/extension/popup.html +25 -0
  90. package/node_modules/@tomflow/chatloop-extension/extension/popup.js +93 -0
  91. package/node_modules/@tomflow/chatloop-extension/extension/reload.html +17 -0
  92. package/node_modules/@tomflow/chatloop-extension/extension/screenshot.html +17 -0
  93. package/node_modules/@tomflow/chatloop-extension/extension/start.html +6 -0
  94. package/node_modules/@tomflow/chatloop-extension/extension/status.html +6 -0
  95. package/node_modules/@tomflow/chatloop-extension/extension/text.html +17 -0
  96. package/node_modules/@tomflow/chatloop-extension/extension/worker/action-result.js +136 -0
  97. package/node_modules/@tomflow/chatloop-extension/extension/worker/action-take.js +220 -0
  98. package/node_modules/@tomflow/chatloop-extension/extension/worker/admission.js +122 -0
  99. package/node_modules/@tomflow/chatloop-extension/extension/worker/adopt-prepare.js +155 -0
  100. package/node_modules/@tomflow/chatloop-extension/extension/worker/adopt-recovery.js +185 -0
  101. package/node_modules/@tomflow/chatloop-extension/extension/worker/adopt-result.js +120 -0
  102. package/node_modules/@tomflow/chatloop-extension/extension/worker/bootstrap.js +172 -0
  103. package/node_modules/@tomflow/chatloop-extension/extension/worker/manual.js +165 -0
  104. package/node_modules/@tomflow/chatloop-extension/extension/worker/readiness.js +244 -0
  105. package/node_modules/@tomflow/chatloop-extension/extension/worker/router.js +181 -0
  106. package/node_modules/@tomflow/chatloop-extension/extension/worker/scheduler.js +147 -0
  107. package/node_modules/@tomflow/chatloop-extension/extension/worker/turn-failure.js +197 -0
  108. package/node_modules/@tomflow/chatloop-extension/extension/worker/turn-finished.js +200 -0
  109. package/node_modules/@tomflow/chatloop-extension/index.mjs +71 -0
  110. package/node_modules/@tomflow/chatloop-extension/lib/action-routing.mjs +18 -0
  111. package/node_modules/@tomflow/chatloop-extension/lib/api-observation-queue.mjs +74 -0
  112. package/node_modules/@tomflow/chatloop-extension/lib/bridge.mjs +208 -0
  113. package/node_modules/@tomflow/chatloop-extension/lib/browser-launch.mjs +40 -0
  114. package/node_modules/@tomflow/chatloop-extension/lib/context-binding.mjs +45 -0
  115. package/node_modules/@tomflow/chatloop-extension/lib/context-ipc.mjs +111 -0
  116. package/node_modules/@tomflow/chatloop-extension/lib/owner-evidence.mjs +67 -0
  117. package/node_modules/@tomflow/chatloop-extension/lib/session-file.mjs +120 -0
  118. package/node_modules/@tomflow/chatloop-extension/package.json +38 -0
  119. package/node_modules/@tomflow/chatloop-extension/scripts/build-actions.mjs +133 -0
  120. package/node_modules/@tomflow/chatloop-trace/README.md +105 -0
  121. package/node_modules/@tomflow/chatloop-trace/events/context.api.mjs +23 -0
  122. package/node_modules/@tomflow/chatloop-trace/events/typed.api.call.mjs +22 -0
  123. package/node_modules/@tomflow/chatloop-trace/events.generated.mjs +4 -0
  124. package/node_modules/@tomflow/chatloop-trace/index.mjs +59 -0
  125. package/node_modules/@tomflow/chatloop-trace/lib/api-aspect.mjs +273 -0
  126. package/node_modules/@tomflow/chatloop-trace/lib/trace-reader.mjs +265 -0
  127. package/node_modules/@tomflow/chatloop-trace/lib/trace.mjs +205 -0
  128. package/node_modules/@tomflow/chatloop-trace/package.json +30 -0
  129. package/node_modules/@tomflow/chatloop-trace/scripts/build-events.mjs +68 -0
  130. package/node_modules/ps-list/index.d.ts +76 -0
  131. package/node_modules/ps-list/index.js +366 -0
  132. package/node_modules/ps-list/license +9 -0
  133. package/node_modules/ps-list/package.json +44 -0
  134. package/node_modules/ps-list/readme.md +56 -0
  135. package/node_modules/ps-list/vendor/fastlist-0.3.0-x64.exe +0 -0
  136. package/node_modules/ps-list/vendor/fastlist-0.3.0-x86.exe +0 -0
  137. package/package.json +10 -2
@@ -0,0 +1,133 @@
1
+ // Extension action definitions are assembled at build time, never discovered
2
+ // by a privileged running Chrome Worker or Native Host.
3
+ import {readFileSync,readdirSync,writeFileSync,unlinkSync,existsSync} from 'node:fs';
4
+ import {dirname,join,resolve} from 'node:path';
5
+ import {fileURLToPath,pathToFileURL} from 'node:url';
6
+ import {createHash} from 'node:crypto';
7
+ const root=dirname(dirname(fileURLToPath(import.meta.url)));
8
+ const fail=code=>Object.assign(Error(code),{code});
9
+ const originals=['chat_text','chat_dom','chat_screenshot','reload',
10
+ 'continue','handoff','clean','status','start'];
11
+ const privilegedKinds=Object.freeze({chat_text:'eye-read',chat_dom:'eye-read',
12
+ chat_screenshot:'eye-screenshot',reload:'eye-reload',
13
+ continue:'owner-intent',handoff:'owner-intent',clean:'owner-clean',
14
+ status:'owner-status',start:'owner-start'});
15
+ // Existing timeout and receipt projection are part of the public action
16
+ // behavior; a descriptor edit must not silently change side-effect handling.
17
+ const builtinBehavior=Object.freeze({
18
+ chat_text:[27000,true],chat_dom:[27000,true],
19
+ chat_screenshot:[27000,false],reload:[27000,false],
20
+ continue:[27000,true],handoff:[27000,true],clean:[27000,true],
21
+ status:[27000,true],start:[310000,true]
22
+ });
23
+ const builtinRoute=Object.freeze({
24
+ chat_text:['text.html','chat text'],chat_dom:['dom.html','chat dom'],
25
+ chat_screenshot:['screenshot.html','chat screenshot'],
26
+ reload:['reload.html','reload'],continue:['continue.html','continue'],
27
+ handoff:['handoff.html','handoff'],clean:['clean.html','clean'],
28
+ status:['status.html','status'],start:['start.html','start']
29
+ });
30
+ const generatedMarker='<!-- GENERATED BY build-actions.mjs -->';
31
+ export async function compileActions(source=join(root,'capabilities'),
32
+ extension=join(root,'extension')){
33
+ const files=readdirSync(source).filter(f=>f.endsWith('.mjs')).sort();
34
+ const ids=new Set(),pages=new Set(),clis=new Set(),actions=[];
35
+ if(!files.length)throw fail('EXTENSION_ACTIONS_EMPTY');
36
+ for(const file of files){
37
+ if(!/^[a-z][a-z0-9_]*\.mjs$/.test(file))
38
+ throw fail('EXTENSION_CAPABILITY_FILENAME_INVALID');
39
+ const path=join(source,file);
40
+ const hash=createHash('sha256').update(readFileSync(path)).digest('hex');
41
+ const {capability:c}=await import(pathToFileURL(path).href+'?sha256='+hash);
42
+ if(!c||c.id!==file.slice(0,-4)||
43
+ !/^[a-z][a-z0-9_]*$/.test(c.id)||
44
+ !/^[a-z][a-z0-9-]*\.html$/.test(c.page)||
45
+ !Array.isArray(c.cli)||!c.cli.length||
46
+ c.cli.some(t=>typeof t!=='string'||!/^[a-z][a-z0-9-]*$/.test(t))||
47
+ !Number.isSafeInteger(c.waitMs)||c.waitMs<1||c.waitMs>310000||
48
+ typeof c.textResult!=='boolean'||typeof c.description!=='string'||
49
+ !c.description.trim()||ids.has(c.id)||pages.has(c.page)||
50
+ clis.has(c.cli.join(' ')))
51
+ throw fail('EXTENSION_CAPABILITY_INVALID');
52
+ ids.add(c.id);pages.add(c.page);clis.add(c.cli.join(' '));
53
+ const newAction=!originals.includes(c.id);
54
+ if(!newAction && privilegedKinds[c.id]!==c.kind)
55
+ throw fail('EXTENSION_ACTION_AUTHORITY_CHANGED');
56
+ if(!newAction && (c.page!==builtinRoute[c.id][0]||
57
+ c.cli.join(' ')!==builtinRoute[c.id][1]))
58
+ throw fail('EXTENSION_BUILTIN_ROUTE_CHANGED');
59
+ if(!newAction && (c.waitMs!==builtinBehavior[c.id][0]||
60
+ c.textResult!==builtinBehavior[c.id][1]))
61
+ throw fail('EXTENSION_BUILTIN_BEHAVIOR_CHANGED');
62
+ if(newAction && !c.textResult)
63
+ throw fail('EXTENSION_READ_RESULT_REQUIRED');
64
+ if(c.kind==='eye-read'&&(!c.id.startsWith('chat_')||
65
+ !['text','dom'].includes(c.readMode)))
66
+ throw fail('EXTENSION_EYE_READ_MODE_INVALID');
67
+ if(newAction && c.kind!=='eye-read')
68
+ throw fail('EXTENSION_PRIVILEGED_ACTION_REVIEW_REQUIRED');
69
+ if((c.id==='chat_text'&&c.readMode!=='text')||
70
+ (c.id==='chat_dom'&&c.readMode!=='dom'))
71
+ throw fail('EXTENSION_BUILTIN_EYE_MODE_CHANGED');
72
+ const page=join(extension,c.page);
73
+ const generated=existsSync(page)&&
74
+ readFileSync(page,'utf8').startsWith(generatedMarker);
75
+ if(!existsSync(page) && !newAction)
76
+ throw fail('EXTENSION_ACTION_PAGE_MISSING');
77
+ if(existsSync(page)&&!generated){
78
+ const expected='actions/'+(c.id.startsWith('chat_')?c.id.slice(5):c.id)+'.js';
79
+ if(!readFileSync(page,'utf8').includes(expected))
80
+ throw fail('EXTENSION_ACTION_EXECUTOR_MISMATCH');
81
+ }
82
+ actions.push({...c,file,generated:newAction});
83
+ }
84
+ actions.sort((a,b)=>(
85
+ (originals.indexOf(a.id)<0?99:originals.indexOf(a.id))-
86
+ (originals.indexOf(b.id)<0?99:originals.indexOf(b.id))
87
+ ||a.id.localeCompare(b.id)));
88
+ const imports=actions.map((a,i)=>
89
+ "import {capability as a"+i+"} from './capabilities/"+a.file+"';").join('\n');
90
+ const node='// GENERATED by scripts/build-actions.mjs — do not edit.\n'+
91
+ imports+'\nexport const actionCapabilities=Object.freeze(['+
92
+ actions.map((_,i)=>'a'+i).join(',')+']);\n';
93
+ const eye=Object.fromEntries(actions.filter(a=>a.kind.startsWith('eye-'))
94
+ .map(a=>[a.id,{page:a.page,kind:a.kind,readMode:a.readMode??null}]));
95
+ const browser='// GENERATED by scripts/build-actions.mjs — do not edit.\n'+
96
+ 'globalThis.ChatLoopEyeCatalogV1=Object.freeze('+JSON.stringify(eye)+');\n';
97
+ const aliases={};
98
+ for(const a of actions.filter(a=>a.generated)){
99
+ aliases[a.page]=generatedMarker+'\n<!doctype html><html><head><meta charset="utf-8">'+
100
+ '<title>Chat Loop read action</title></head><body>'+
101
+ '<p id="status"></p><p id="details"></p>'+
102
+ '<script src="actions/common.js"></script>'+
103
+ '<script src="actions/read-mode.js" data-action="'+a.id+
104
+ '" data-read-mode="'+a.readMode+'"></script></body></html>\n';
105
+ }
106
+ return {node,browser,aliases};
107
+ }
108
+ async function main(){
109
+ const ext=join(root,'extension'),expected=await compileActions();
110
+ const manifest=JSON.parse(readFileSync(join(ext,'manifest.json'),'utf8'));
111
+ const pkg=JSON.parse(readFileSync(join(root,'package.json'),'utf8'));
112
+ if(manifest.version!==pkg.version||manifest.manifest_version!==3)
113
+ throw fail('EXTENSION_PACKAGE_VERSION_MISMATCH');
114
+ const targets=[[join(root,'actions.generated.mjs'),expected.node],
115
+ [join(ext,'loop','action-catalog.generated.js'),expected.browser],
116
+ ...Object.entries(expected.aliases).map(([page,html])=>[join(ext,page),html])];
117
+ const orphan=readdirSync(ext).filter(f=>f.endsWith('.html')&&
118
+ !Object.hasOwn(expected.aliases,f)&&
119
+ readFileSync(join(ext,f),'utf8').startsWith(generatedMarker));
120
+ if(process.argv.includes('--check')){
121
+ if(orphan.length||targets.some(([file,value])=>!existsSync(file)||
122
+ readFileSync(file,'utf8')!==value))
123
+ throw fail('EXTENSION_ACTIONS_STALE');
124
+ if(process.env.npm_lifecycle_event!=='prepack')
125
+ console.log('EXTENSION_ACTIONS_CURRENT');
126
+ }else{
127
+ for(const page of orphan)unlinkSync(join(ext,page));
128
+ for(const [file,value] of targets)writeFileSync(file,value);
129
+ console.log('EXTENSION_ACTIONS_BUILT');
130
+ }
131
+ }
132
+ if(process.argv[1]&&resolve(process.argv[1])===fileURLToPath(import.meta.url))
133
+ await main();
@@ -0,0 +1,105 @@
1
+ # @tomflow/chatloop-trace
2
+
3
+ Trace is the **read-only evidence/observation domain**, not a business
4
+ authorization, receipt authority, browser driver or second job scheduler.
5
+ The existing Tools Supervisor remains the sole authoritative Trace JSONL
6
+ writer; Tools Trace Gateway provides scoped diagnosis only.
7
+
8
+ ## Public npm SDK
9
+
10
+ The root exposes two data APIs, a shared AOP factory and one opt-in, non-authoritative observation port:
11
+
12
+ - `subscribeTraceApiLog(listener)`: Tools attaches a best-effort collector
13
+ to the existing Supervisor. The writer's own `record/recordControl`
14
+ telemetry is filtered at that boundary to prevent feedback loops. A
15
+ standalone SDK stays installable and never creates another logging service.
16
+ - `createTraceWriter({filePath})`: the Supervisor invokes
17
+ `record(event)`, `recordControl(event,detail)` and `health()`.
18
+ - `createTraceReader({filePath,allowedProjects})`: the Gateway invokes
19
+ `diagnose({projectRef,traceId|sessionRef,maxEvents})`, `apiUsage({windowMinutes,limit})`
20
+ or `health()`. `apiUsage` requires a Reader explicitly scoped to
21
+ `api_system` and returns only grouped method names, counts, success/failure
22
+ totals and calls/minute; it never returns request content.
23
+ No raw `query`, no CLI, service, daemon, additional storage or Browser Owner.
24
+
25
+ The Trace SDK source version is specified by its package manifest. Existing Tools versions retain
26
+ their independently pinned Trace version until separately verified and
27
+ upgraded; tests here do not prove a deployed Supervisor changed.
28
+
29
+ ## Event contracts and extension
30
+
31
+ `events/<event-id>.mjs` owns the schema-v2 domain-specific validator,
32
+ error code and human purpose for a typed event family. The single
33
+ `scripts/build-events.mjs` command composes these **at build time** into
34
+ `events.generated.mjs`; `index.mjs` injects the static catalog into
35
+ the private Writer/Reader implementation. No runtime scanning, external
36
+ registration, secondary hand-maintained API catalog or duplicated validation
37
+ between writing and reading.
38
+
39
+ New typed event families must use the `typed.*` namespace. Removing a
40
+ specialized module makes that typed event **unregistered**: the Writer rejects
41
+ it, and the Reader treats old/forged matching lines as untrusted. Historical
42
+ generic event names retain their established read/write behavior.
43
+
44
+ The canonical envelope also reserves the `api` field exclusively for
45
+ `context.api`. **No newly declared typed event can claim API metadata**, even
46
+ with a permissive validator. Each validator receives a read-only copy of the
47
+ event: it cannot rewrite an event's `projectRef`, status or identifiers during
48
+ writing or diagnosis. A family may declare a `usageName(event)` projection
49
+ to join scoped API usage aggregation without modifying Reader's event dispatch.
50
+ New typed families must namespace projected names under their own family ID;
51
+ this does not add Project permissions or authorize actions.
52
+
53
+ The built-in `context.api` event is protected: it requires
54
+ `component=context`, status `BEGIN/CONFIRMED/FAILED`, and only
55
+ `api:{name,surface,mode}` with validated values. Removing or weakening
56
+ this contract blocks the build. Generic events cannot add `api` or new
57
+ arbitrary payload fields. Additional event families can constrain the
58
+ **same reviewed v2 envelope** without modifying the Writer/Reader Core.
59
+ Adding new envelope fields or granting new write authority is a separate
60
+ schema/security change, not a plugin escape hatch.
61
+
62
+ To add a typed event contract:
63
+
64
+ 1. Create `events/<id>.mjs` exporting
65
+ `capability={id,schemaVersion:2,errorCode,description,validate(v)}`
66
+ (and optional `usageName(v)` for safe usage aggregation).
67
+ 2. Run `npm run build:events`; it regenerates the only static catalog.
68
+ 3. Run `npm run build:events:check`, `npm test` and workspace `npm run check`.
69
+
70
+ `test/event-composition.test.mjs` verifies that a temporary additional
71
+ event contract is accepted by **both** the Writer and the Reader and can be
72
+ removed without modifying existing Core code. Malformed or unauthorized
73
+ event-family records are rejected in both directions.
74
+
75
+ ## Immutable observability boundaries
76
+
77
+ All newly written records use schema v2 with a bounded, canonical JSONL
78
+ envelope: `time`, `eventId`, `traceId`, `spanId`, optional
79
+ `parentSpanId`, `writerEpoch`, `writerSeq`, `component`, `event`,
80
+ `status`, scoped `projectRef/taskRef/sessionRef`, `generation`,
81
+ `requestId/actionId/evidenceRef`, optional `api`, `durationMs`,
82
+ and `errorCode`.
83
+
84
+ No user content, cookies, credentials, raw tool arguments or arbitrary
85
+ nested result objects can enter v2 records. Existing legacy evidence is
86
+ read-only, never migrated into a new current receipt or permission.
87
+
88
+ The SDK verifies file owner, permissions, symlink safety and bounds event
89
+ and query sizes. Diagnostics expose truncation, corrupted lines, writer
90
+ restarts, legacy records and pending receipts as **uncertainty**. They never
91
+ grant approval, Context write rights, Owner transfer or automatic retry.
92
+ A missing or interrupted Writer must be checked against the authoritative
93
+ business receipt, not inferred from a Trace event.
94
+
95
+ The npm package includes only the SDK root, generated event catalog,
96
+ event definitions, private implementation and this README. It contains no
97
+ independent API documentation or unnecessary executable.
98
+
99
+ ## Shared API observation factory
100
+
101
+ `createApiAspect(packageName, {sink})` is the **only public Node AOP implementation**, exported from `@tomflow/chatloop-trace`. Context, Tools, Extension Native/CLI and Darwin Tunnel packages import it through their pinned npm dependency rather than embedding duplicated source. Each consumer supplies only its typed, authorized transport/metadata adapter. Its `observe`, `methods`, `described`, `describedMethods`, `subscribe`, `health`, and `drain` facets preserve business results while reporting non-authoritative audit outcomes.
102
+
103
+ AOP `health().delivered` measures delivery attempts, **not Writer persistence**. A `drain()` success only confirms that tracked sinks have not reported failure; authoritative persistence requires an accepted Trace Writer receipt with matching request ID and event ID. Audit loss or uncertain delivery must not change a business result.
104
+
105
+ The Chrome MV3 Worker cannot import the Node npm SDK, so `scripts/build-api-aspects.mjs` emits a version-checked static browser script from the same canonical Trace source. The browser script is the sole generated runtime copy; no separate Writer is created.
@@ -0,0 +1,23 @@
1
+ // Only v2 Context API observations use the typed api field. Other event
2
+ // families cannot impersonate these records, including from disk.
3
+ const API_NAME=/^[a-z][A-Za-z0-9._-]{1,89}$/;
4
+ const SURFACES=new Set(['sdk','gateway','operator','trusted']);
5
+ const MODES=new Set(['read','write','unknown','internal','operator']);
6
+ const object=value=>value!==null&&typeof value==='object'&&!Array.isArray(value);
7
+ export const capability=Object.freeze({
8
+ id:'context.api',
9
+ schemaVersion:2,
10
+ errorCode:'TRACE_INVALID_API',
11
+ description:'Typed Context API BEGIN/CONFIRMED/FAILED function boundary',
12
+ // Query projection travels with the event contract, not a Reader switch.
13
+ usageName:v=>'context.'+v.api.surface+'.'+v.api.name,
14
+ validate(v){
15
+ const api=v?.api;
16
+ return v?.component==='context'&&
17
+ ['BEGIN','CONFIRMED','FAILED'].includes(v?.status)&&
18
+ object(api)&&Object.keys(api).length===3&&
19
+ Object.keys(api).every(k=>['name','surface','mode'].includes(k))&&
20
+ typeof api.name==='string'&&API_NAME.test(api.name)&&
21
+ SURFACES.has(api.surface)&&MODES.has(api.mode);
22
+ }
23
+ });
@@ -0,0 +1,22 @@
1
+ // Sanitized aggregateable MCP call event. No arguments, results or URLs.
2
+ // This system-local telemetry scope is not a Context Project or approval.
3
+ const METHOD=/^[a-z][A-Za-z0-9_.:-]{1,126}$/;
4
+ const CODE=/^[A-Z][A-Z0-9_]{1,95}$/;
5
+ export const capability=Object.freeze({
6
+ id:'typed.api.call',schemaVersion:2,errorCode:'TRACE_INVALID_API_USAGE',
7
+ description:'Generic public API begin/completion/failure with safe method identity',
8
+ usageName:v=>v.apiName,
9
+ validate(v){
10
+ return v?.component==='gateway'&&
11
+ v.projectRef==='api_system'&&
12
+ ['BEGIN','CONFIRMED','FAILED'].includes(v.status)&&
13
+ typeof v.apiName==='string'&&METHOD.test(v.apiName)&&
14
+ v.api===undefined&&v.taskRef===undefined&&v.sessionRef===undefined&&
15
+ v.actionId===undefined&&v.evidenceRef===undefined&&
16
+ (v.status==='FAILED'
17
+ ?typeof v.errorCode==='string'&&CODE.test(v.errorCode)
18
+ :v.errorCode===undefined)&&
19
+ (v.status==='BEGIN'?v.durationMs===undefined
20
+ :Number.isSafeInteger(v.durationMs)&&v.durationMs>=0);
21
+ }
22
+ });
@@ -0,0 +1,4 @@
1
+ // GENERATED by scripts/build-events.mjs — do not edit.
2
+ import {capability as e0} from './events/context.api.mjs';
3
+ import {capability as e1} from './events/typed.api.call.mjs';
4
+ export const eventCapabilities=Object.freeze([e0,e1]);
@@ -0,0 +1,59 @@
1
+ import {createApiAspect as createSharedApiAspect} from './lib/api-aspect.mjs';
2
+ const apiAspect=createSharedApiAspect('@tomflow/chatloop-trace',
3
+ {bufferUntilSubscribe:true});
4
+ // Shared AOP factory is a versioned public SDK capability. Consumers reuse
5
+ // it directly; only MV3 browsers require a generated static script.
6
+ export const createApiAspect=apiAspect.observe('createApiAspect',
7
+ (packageName,options)=>{
8
+ const facet=createSharedApiAspect(packageName,options);
9
+ // The public current() method must inspect its caller's async context,
10
+ // before the logging span changes that context.
11
+ const current=apiAspect.observe('aspect.current',facet.current,'sdk',
12
+ {preserveCallerContext:true});
13
+ return apiAspect.methods(Object.freeze({...facet,current}),'aspect');
14
+ });
15
+ // Tools composes this opt-in soft observation port into its one Supervisor.
16
+ // Never store telemetry in Trace SDK by creating a second writer.
17
+ export const subscribeTraceApiLog=apiAspect.subscribe;
18
+ // Two data capabilities, shared AOP factory and one observation port. Correlation-id
19
+ // generation and schema constants remain private implementation details.
20
+ import {eventCapabilities} from './events.generated.mjs';
21
+ import {configureTraceEvents,createTraceReader as openReader,createTraceWriter as openWriter} from './lib/trace.mjs';
22
+ configureTraceEvents(eventCapabilities);
23
+ export const createTraceWriter=apiAspect.observe('createTraceWriter',
24
+ options=>{
25
+ const writer=openWriter(options);
26
+ // The writer is the single logging owner. Send only its public method
27
+ // observations through its raw private append path: calling the public
28
+ // record() here would recursively observe its own audit events.
29
+ const writerAspect=createSharedApiAspect('@tomflow/chatloop-trace',{
30
+ sink:event=>{
31
+ try{
32
+ writer.record({event:'typed.api.call',component:'gateway',
33
+ projectRef:'api_system',traceId:event.traceId,spanId:event.spanId,
34
+ ...(event.parentSpanId?{parentSpanId:event.parentSpanId}:{}),
35
+ apiName:'trace.'+event.api,
36
+ status:event.phase==='BEGIN'?'BEGIN':event.phase==='OK'
37
+ ?'CONFIRMED':'FAILED',
38
+ ...(event.phase!=='BEGIN'?{durationMs:event.durationMs}:{}),
39
+ ...(event.phase==='FAILED'?{errorCode:event.errorCode}:{})});
40
+ return true;
41
+ }catch{return false} // Soft audit must never modify an API result.
42
+ }
43
+ });
44
+ // The self-observation queue is bounded. Expose loss in the existing
45
+ // Writer health receipt so a missing audit can never look like PASS.
46
+ return writerAspect.methods(Object.freeze({...writer,
47
+ health:()=>({...writer.health(),apiObservation:writerAspect.health()})
48
+ }),'writer');
49
+ });
50
+
51
+ // Only the scoped diagnostic contract is used outside Trace. Keep raw query
52
+ // available internally for the private reader's own diagnostic algorithm.
53
+ export const createTraceReader=apiAspect.observe('createTraceReader',
54
+ options=>{
55
+ const reader=openReader(options);
56
+ return apiAspect.methods(Object.freeze({diagnose:reader.diagnose,
57
+ apiUsage:reader.apiUsage,health:reader.health}),
58
+ 'reader');
59
+ });
@@ -0,0 +1,273 @@
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
+ export 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
+ export 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
+ export 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
+ }