@tomflow/chatloop-tools 0.9.64 → 0.9.70
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/node_modules/@tomflow/chatloop-context/README.md +296 -0
- package/node_modules/@tomflow/chatloop-context/bin/cli.mjs +48 -0
- package/node_modules/@tomflow/chatloop-context/capabilities/approval.mjs +151 -0
- package/node_modules/@tomflow/chatloop-context/capabilities/context.mjs +376 -0
- package/node_modules/@tomflow/chatloop-context/capabilities/document.mjs +290 -0
- package/node_modules/@tomflow/chatloop-context/capabilities/evidence.mjs +134 -0
- package/node_modules/@tomflow/chatloop-context/capabilities/presentation.mjs +82 -0
- package/node_modules/@tomflow/chatloop-context/capabilities/project.mjs +349 -0
- package/node_modules/@tomflow/chatloop-context/capabilities/sdk.mjs +72 -0
- package/node_modules/@tomflow/chatloop-context/capabilities/start.mjs +73 -0
- package/node_modules/@tomflow/chatloop-context/capabilities/task.mjs +507 -0
- package/node_modules/@tomflow/chatloop-context/capabilities.generated.mjs +11 -0
- package/node_modules/@tomflow/chatloop-context/docs/interfaces.md +261 -0
- package/node_modules/@tomflow/chatloop-context/docs/operator-and-migration.md +277 -0
- package/node_modules/@tomflow/chatloop-context/index.mjs +238 -0
- package/node_modules/@tomflow/chatloop-context/lib/api-log.mjs +86 -0
- package/node_modules/@tomflow/chatloop-context/lib/approval-policy.mjs +77 -0
- package/node_modules/@tomflow/chatloop-context/lib/capability-catalog.generated.json +2036 -0
- package/node_modules/@tomflow/chatloop-context/lib/capability-router.mjs +69 -0
- package/node_modules/@tomflow/chatloop-context/lib/cli-commands.mjs +338 -0
- package/node_modules/@tomflow/chatloop-context/lib/context-cli.mjs +298 -0
- package/node_modules/@tomflow/chatloop-context/lib/context-migration.mjs +286 -0
- package/node_modules/@tomflow/chatloop-context/lib/core/context.mjs +117 -0
- package/node_modules/@tomflow/chatloop-context/lib/core/evidence.mjs +51 -0
- package/node_modules/@tomflow/chatloop-context/lib/core/health.mjs +134 -0
- package/node_modules/@tomflow/chatloop-context/lib/core/migration.mjs +262 -0
- package/node_modules/@tomflow/chatloop-context/lib/core/project.mjs +246 -0
- package/node_modules/@tomflow/chatloop-context/lib/core/review.mjs +180 -0
- package/node_modules/@tomflow/chatloop-context/lib/core/run-cancel.mjs +68 -0
- package/node_modules/@tomflow/chatloop-context/lib/core/run-recovery.mjs +112 -0
- package/node_modules/@tomflow/chatloop-context/lib/core/run.mjs +367 -0
- package/node_modules/@tomflow/chatloop-context/lib/core/store.mjs +398 -0
- package/node_modules/@tomflow/chatloop-context/lib/core/task.mjs +264 -0
- package/node_modules/@tomflow/chatloop-context/lib/line-review.mjs +13 -0
- package/node_modules/@tomflow/chatloop-context/lib/methods.mjs +111 -0
- package/node_modules/@tomflow/chatloop-context/lib/operations.mjs +107 -0
- package/node_modules/@tomflow/chatloop-context/lib/orphan-operator.mjs +118 -0
- package/node_modules/@tomflow/chatloop-context/lib/process-inventory.mjs +20 -0
- package/node_modules/@tomflow/chatloop-context/lib/project-branch.mjs +316 -0
- package/node_modules/@tomflow/chatloop-context/lib/project-diagnostic.mjs +153 -0
- package/node_modules/@tomflow/chatloop-context/lib/project-guards.mjs +19 -0
- package/node_modules/@tomflow/chatloop-context/lib/project-store.mjs +117 -0
- package/node_modules/@tomflow/chatloop-context/lib/trusted-run.mjs +142 -0
- package/node_modules/@tomflow/chatloop-context/lib/workspace-operator.mjs +169 -0
- package/node_modules/@tomflow/chatloop-context/package.json +38 -0
- package/node_modules/@tomflow/chatloop-context/scripts/build-capabilities.mjs +114 -0
- package/node_modules/@tomflow/chatloop-extension/README.md +190 -0
- package/node_modules/@tomflow/chatloop-extension/actions.generated.mjs +13 -0
- package/node_modules/@tomflow/chatloop-extension/bin/cli.mjs +168 -0
- package/node_modules/@tomflow/chatloop-extension/bin/native-host.mjs +246 -0
- package/node_modules/@tomflow/chatloop-extension/capabilities/chat_dom.mjs +1 -0
- package/node_modules/@tomflow/chatloop-extension/capabilities/chat_screenshot.mjs +1 -0
- package/node_modules/@tomflow/chatloop-extension/capabilities/chat_text.mjs +1 -0
- package/node_modules/@tomflow/chatloop-extension/capabilities/clean.mjs +1 -0
- package/node_modules/@tomflow/chatloop-extension/capabilities/continue.mjs +1 -0
- package/node_modules/@tomflow/chatloop-extension/capabilities/entry_test.mjs +1 -0
- package/node_modules/@tomflow/chatloop-extension/capabilities/handoff.mjs +1 -0
- package/node_modules/@tomflow/chatloop-extension/capabilities/reload.mjs +1 -0
- package/node_modules/@tomflow/chatloop-extension/capabilities/session.mjs +1 -0
- package/node_modules/@tomflow/chatloop-extension/capabilities/start.mjs +1 -0
- package/node_modules/@tomflow/chatloop-extension/capabilities/status.mjs +1 -0
- package/node_modules/@tomflow/chatloop-extension/extension/actions/clean.js +123 -0
- package/node_modules/@tomflow/chatloop-extension/extension/actions/common.js +183 -0
- package/node_modules/@tomflow/chatloop-extension/extension/actions/continue.js +390 -0
- package/node_modules/@tomflow/chatloop-extension/extension/actions/dom.js +2 -0
- package/node_modules/@tomflow/chatloop-extension/extension/actions/entry_test.js +241 -0
- package/node_modules/@tomflow/chatloop-extension/extension/actions/handoff-scoped.js +143 -0
- package/node_modules/@tomflow/chatloop-extension/extension/actions/handoff.js +399 -0
- package/node_modules/@tomflow/chatloop-extension/extension/actions/index.js +2 -0
- package/node_modules/@tomflow/chatloop-extension/extension/actions/model-intent.js +60 -0
- package/node_modules/@tomflow/chatloop-extension/extension/actions/read-mode.js +9 -0
- package/node_modules/@tomflow/chatloop-extension/extension/actions/reload.js +20 -0
- package/node_modules/@tomflow/chatloop-extension/extension/actions/screenshot.js +77 -0
- package/node_modules/@tomflow/chatloop-extension/extension/actions/session.js +95 -0
- package/node_modules/@tomflow/chatloop-extension/extension/actions/start.js +329 -0
- package/node_modules/@tomflow/chatloop-extension/extension/actions/status.js +38 -0
- package/node_modules/@tomflow/chatloop-extension/extension/actions/text.js +2 -0
- package/node_modules/@tomflow/chatloop-extension/extension/background.js +33 -0
- package/node_modules/@tomflow/chatloop-extension/extension/clean.html +5 -0
- package/node_modules/@tomflow/chatloop-extension/extension/content.js +40 -0
- package/node_modules/@tomflow/chatloop-extension/extension/continue.html +9 -0
- package/node_modules/@tomflow/chatloop-extension/extension/dom.html +17 -0
- package/node_modules/@tomflow/chatloop-extension/extension/entry_test.html +6 -0
- package/node_modules/@tomflow/chatloop-extension/extension/handoff.html +9 -0
- package/node_modules/@tomflow/chatloop-extension/extension/loop/action-catalog.generated.js +2 -0
- package/node_modules/@tomflow/chatloop-extension/extension/loop/api-aspect.generated.js +275 -0
- package/node_modules/@tomflow/chatloop-extension/extension/loop/api-observation-queue.generated.js +84 -0
- package/node_modules/@tomflow/chatloop-extension/extension/loop/core.js +107 -0
- package/node_modules/@tomflow/chatloop-extension/extension/loop/index.js +36 -0
- package/node_modules/@tomflow/chatloop-extension/extension/loop/observer-approval.js +299 -0
- package/node_modules/@tomflow/chatloop-extension/extension/loop/observer-inspect.js +144 -0
- package/node_modules/@tomflow/chatloop-extension/extension/loop/observer-poll.js +172 -0
- package/node_modules/@tomflow/chatloop-extension/extension/loop/observer-recovery.js +109 -0
- package/node_modules/@tomflow/chatloop-extension/extension/loop/observer.js +211 -0
- package/node_modules/@tomflow/chatloop-extension/extension/loop/resource-maintenance.js +159 -0
- package/node_modules/@tomflow/chatloop-extension/extension/loop/resources.js +399 -0
- package/node_modules/@tomflow/chatloop-extension/extension/manifest.json +43 -0
- package/node_modules/@tomflow/chatloop-extension/extension/popup.html +25 -0
- package/node_modules/@tomflow/chatloop-extension/extension/popup.js +99 -0
- package/node_modules/@tomflow/chatloop-extension/extension/reload.html +17 -0
- package/node_modules/@tomflow/chatloop-extension/extension/screenshot.html +17 -0
- package/node_modules/@tomflow/chatloop-extension/extension/session.html +7 -0
- package/node_modules/@tomflow/chatloop-extension/extension/start.html +6 -0
- package/node_modules/@tomflow/chatloop-extension/extension/status.html +6 -0
- package/node_modules/@tomflow/chatloop-extension/extension/text.html +17 -0
- package/node_modules/@tomflow/chatloop-extension/extension/worker/action-result.js +136 -0
- package/node_modules/@tomflow/chatloop-extension/extension/worker/action-take.js +218 -0
- package/node_modules/@tomflow/chatloop-extension/extension/worker/admission.js +127 -0
- package/node_modules/@tomflow/chatloop-extension/extension/worker/adopt-prepare.js +296 -0
- package/node_modules/@tomflow/chatloop-extension/extension/worker/adopt-recovery.js +186 -0
- package/node_modules/@tomflow/chatloop-extension/extension/worker/adopt-result.js +126 -0
- package/node_modules/@tomflow/chatloop-extension/extension/worker/bootstrap.js +287 -0
- package/node_modules/@tomflow/chatloop-extension/extension/worker/manual.js +163 -0
- package/node_modules/@tomflow/chatloop-extension/extension/worker/readiness.js +345 -0
- package/node_modules/@tomflow/chatloop-extension/extension/worker/router.js +209 -0
- package/node_modules/@tomflow/chatloop-extension/extension/worker/scheduler.js +385 -0
- package/node_modules/@tomflow/chatloop-extension/extension/worker/session-control.js +75 -0
- package/node_modules/@tomflow/chatloop-extension/extension/worker/task-action-v2.js +278 -0
- package/node_modules/@tomflow/chatloop-extension/extension/worker/task-cancel-recovery-v2.js +52 -0
- package/node_modules/@tomflow/chatloop-extension/extension/worker/task-cancel-v2.js +93 -0
- package/node_modules/@tomflow/chatloop-extension/extension/worker/task-continue-recovery-v2.js +78 -0
- package/node_modules/@tomflow/chatloop-extension/extension/worker/task-handoff-recovery-v2.js +148 -0
- package/node_modules/@tomflow/chatloop-extension/extension/worker/task-handoff-v2.js +325 -0
- package/node_modules/@tomflow/chatloop-extension/extension/worker/task-hold-recovery-v2.js +109 -0
- package/node_modules/@tomflow/chatloop-extension/extension/worker/task-intent-dispatch-v2.js +220 -0
- package/node_modules/@tomflow/chatloop-extension/extension/worker/task-intent-v2.js +106 -0
- package/node_modules/@tomflow/chatloop-extension/extension/worker/task-owner-resolver.js +110 -0
- package/node_modules/@tomflow/chatloop-extension/extension/worker/task-recover-v2.js +209 -0
- package/node_modules/@tomflow/chatloop-extension/extension/worker/task-routes-v2.js +357 -0
- package/node_modules/@tomflow/chatloop-extension/extension/worker/task-run-store.js +400 -0
- package/node_modules/@tomflow/chatloop-extension/extension/worker/task-scheduler.js +78 -0
- package/node_modules/@tomflow/chatloop-extension/extension/worker/task-start-v2.js +361 -0
- package/node_modules/@tomflow/chatloop-extension/extension/worker/task-terminal-v2.js +235 -0
- package/node_modules/@tomflow/chatloop-extension/extension/worker/turn-failure.js +197 -0
- package/node_modules/@tomflow/chatloop-extension/extension/worker/turn-finished.js +205 -0
- package/node_modules/@tomflow/chatloop-extension/index.mjs +78 -0
- package/node_modules/@tomflow/chatloop-extension/lib/action-routing.mjs +19 -0
- package/node_modules/@tomflow/chatloop-extension/lib/api-observation-queue.mjs +82 -0
- package/node_modules/@tomflow/chatloop-extension/lib/bridge.mjs +378 -0
- package/node_modules/@tomflow/chatloop-extension/lib/browser-launch.mjs +89 -0
- package/node_modules/@tomflow/chatloop-extension/lib/context-binding.mjs +45 -0
- package/node_modules/@tomflow/chatloop-extension/lib/context-ipc.mjs +122 -0
- package/node_modules/@tomflow/chatloop-extension/lib/owner-evidence.mjs +75 -0
- package/node_modules/@tomflow/chatloop-extension/lib/owner-kernel-lock.mjs +106 -0
- package/node_modules/@tomflow/chatloop-extension/lib/owner-ledger.mjs +316 -0
- package/node_modules/@tomflow/chatloop-extension/lib/owner-locked-write.mjs +30 -0
- package/node_modules/@tomflow/chatloop-extension/lib/scoped-cancel-v2.mjs +190 -0
- package/node_modules/@tomflow/chatloop-extension/lib/scoped-continue-v2.mjs +214 -0
- package/node_modules/@tomflow/chatloop-extension/lib/scoped-handoff-v2.mjs +338 -0
- package/node_modules/@tomflow/chatloop-extension/lib/scoped-native-control.mjs +398 -0
- package/node_modules/@tomflow/chatloop-extension/lib/scoped-recovery-v2.mjs +234 -0
- package/node_modules/@tomflow/chatloop-extension/lib/scoped-retire-v2.mjs +70 -0
- package/node_modules/@tomflow/chatloop-extension/lib/scoped-terminal-v2.mjs +143 -0
- package/node_modules/@tomflow/chatloop-extension/lib/session-file.mjs +228 -0
- package/node_modules/@tomflow/chatloop-extension/package.json +36 -0
- package/node_modules/@tomflow/chatloop-extension/scripts/build-actions.mjs +138 -0
- package/node_modules/@tomflow/chatloop-trace/README.md +118 -0
- package/node_modules/@tomflow/chatloop-trace/events/context.api.mjs +23 -0
- package/node_modules/@tomflow/chatloop-trace/events/typed.api.call.mjs +22 -0
- package/node_modules/@tomflow/chatloop-trace/events.generated.mjs +4 -0
- package/node_modules/@tomflow/chatloop-trace/index.mjs +59 -0
- package/node_modules/@tomflow/chatloop-trace/lib/api-aspect.mjs +273 -0
- package/node_modules/@tomflow/chatloop-trace/lib/trace-reader.mjs +308 -0
- package/node_modules/@tomflow/chatloop-trace/lib/trace-retention.mjs +140 -0
- package/node_modules/@tomflow/chatloop-trace/lib/trace.mjs +236 -0
- package/node_modules/@tomflow/chatloop-trace/package.json +28 -0
- package/node_modules/@tomflow/chatloop-trace/scripts/build-events.mjs +68 -0
- package/node_modules/ps-list/index.d.ts +76 -0
- package/node_modules/ps-list/index.js +366 -0
- package/node_modules/ps-list/license +9 -0
- package/node_modules/ps-list/package.json +44 -0
- package/node_modules/ps-list/readme.md +56 -0
- package/node_modules/ps-list/vendor/fastlist-0.3.0-x64.exe +0 -0
- package/node_modules/ps-list/vendor/fastlist-0.3.0-x86.exe +0 -0
- package/package.json +12 -4
|
@@ -0,0 +1,118 @@
|
|
|
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,retentionDays=30})`: the Supervisor invokes
|
|
17
|
+
`record(event)`, `recordControl(event,detail)` and `health()`. The single
|
|
18
|
+
Writer prunes only parseable records older than the configured retention
|
|
19
|
+
window at startup and daily across its active file and bounded rotation
|
|
20
|
+
segments. Unknown/malformed-age lines are preserved; source identity and
|
|
21
|
+
permissions are rechecked before atomic replacement. A file with no expired
|
|
22
|
+
records is not rewritten or replaced. Retention results are visible in
|
|
23
|
+
`health().retention`.
|
|
24
|
+
- `createTraceReader({filePath,allowedProjects})`: the Gateway invokes
|
|
25
|
+
`diagnose({projectRef,traceId|sessionRef,maxEvents})`, `apiUsage({windowMinutes,limit})`
|
|
26
|
+
or `health()`. `apiUsage` requires a Reader explicitly scoped to
|
|
27
|
+
`api_system` and returns only grouped method names, counts, success/failure
|
|
28
|
+
totals and calls/minute; it never returns request content.
|
|
29
|
+
No raw `query`, no CLI, service, daemon, additional storage or Browser Owner.
|
|
30
|
+
|
|
31
|
+
The Trace SDK source version is specified by its package manifest. Existing Tools versions retain
|
|
32
|
+
their independently pinned Trace version until separately verified and
|
|
33
|
+
upgraded; tests here do not prove a deployed Supervisor changed.
|
|
34
|
+
|
|
35
|
+
## Event contracts and extension
|
|
36
|
+
|
|
37
|
+
`events/<event-id>.mjs` owns the schema-v2 domain-specific validator,
|
|
38
|
+
error code and human purpose for a typed event family. The single
|
|
39
|
+
`scripts/build-events.mjs` command composes these **at build time** into
|
|
40
|
+
`events.generated.mjs`; `index.mjs` injects the static catalog into
|
|
41
|
+
the private Writer/Reader implementation. No runtime scanning, external
|
|
42
|
+
registration, secondary hand-maintained API catalog or duplicated validation
|
|
43
|
+
between writing and reading.
|
|
44
|
+
|
|
45
|
+
New typed event families must use the `typed.*` namespace. Removing a
|
|
46
|
+
specialized module makes that typed event **unregistered**: the Writer rejects
|
|
47
|
+
it, and the Reader treats old/forged matching lines as untrusted. Historical
|
|
48
|
+
generic event names retain their established read/write behavior.
|
|
49
|
+
|
|
50
|
+
The canonical envelope also reserves the `api` field exclusively for
|
|
51
|
+
`context.api`. **No newly declared typed event can claim API metadata**, even
|
|
52
|
+
with a permissive validator. Each validator receives a read-only copy of the
|
|
53
|
+
event: it cannot rewrite an event's `projectRef`, status or identifiers during
|
|
54
|
+
writing or diagnosis. A family may declare a `usageName(event)` projection
|
|
55
|
+
to join scoped API usage aggregation without modifying Reader's event dispatch.
|
|
56
|
+
New typed families must namespace projected names under their own family ID;
|
|
57
|
+
this does not add Project permissions or authorize actions.
|
|
58
|
+
|
|
59
|
+
The built-in `context.api` event is protected: it requires
|
|
60
|
+
`component=context`, status `BEGIN/CONFIRMED/FAILED`, and only
|
|
61
|
+
`api:{name,surface,mode}` with validated values. Removing or weakening
|
|
62
|
+
this contract blocks the build. Generic events cannot add `api` or new
|
|
63
|
+
arbitrary payload fields. Additional event families can constrain the
|
|
64
|
+
**same reviewed v2 envelope** without modifying the Writer/Reader Core.
|
|
65
|
+
Adding new envelope fields or granting new write authority is a separate
|
|
66
|
+
schema/security change, not a plugin escape hatch.
|
|
67
|
+
|
|
68
|
+
To add a typed event contract:
|
|
69
|
+
|
|
70
|
+
1. Create `events/<id>.mjs` exporting
|
|
71
|
+
`capability={id,schemaVersion:2,errorCode,description,validate(v)}`
|
|
72
|
+
(and optional `usageName(v)` for safe usage aggregation).
|
|
73
|
+
2. Run `npm run build:events`; it regenerates the only static catalog.
|
|
74
|
+
3. Run `npm run build:events:check`, `npm test` and workspace `npm run check`.
|
|
75
|
+
|
|
76
|
+
`test/event-composition.test.mjs` verifies that a temporary additional
|
|
77
|
+
event contract is accepted by **both** the Writer and the Reader and can be
|
|
78
|
+
removed without modifying existing Core code. Malformed or unauthorized
|
|
79
|
+
event-family records are rejected in both directions.
|
|
80
|
+
|
|
81
|
+
## Immutable observability boundaries
|
|
82
|
+
|
|
83
|
+
All newly written records use schema v2 with a bounded, canonical JSONL
|
|
84
|
+
envelope: `time`, `eventId`, `traceId`, `spanId`, optional
|
|
85
|
+
`parentSpanId`, `writerEpoch`, `writerSeq`, `component`, `event`,
|
|
86
|
+
`status`, scoped `projectRef/taskRef/sessionRef`, `generation`,
|
|
87
|
+
`requestId/actionId/evidenceRef`, optional `api`, `durationMs`,
|
|
88
|
+
and `errorCode`.
|
|
89
|
+
|
|
90
|
+
No user content, cookies, credentials, raw tool arguments or arbitrary
|
|
91
|
+
nested result objects can enter v2 records. Existing legacy evidence is
|
|
92
|
+
read-only, never migrated into a new current receipt or permission.
|
|
93
|
+
|
|
94
|
+
The SDK verifies file owner, permissions, symlink safety and bounds event
|
|
95
|
+
and query sizes. Scoped readers stream logs up to 2 GiB without loading the
|
|
96
|
+
full JSONL file into memory; individual lines are bounded to 8 KiB and
|
|
97
|
+
diagnostic deduplication is capped at 200,000 event IDs (excess fails closed,
|
|
98
|
+
never becomes a complete report). The Writer refuses to append or rotate a
|
|
99
|
+
file whose final JSONL record lacks its newline terminator, preserving torn
|
|
100
|
+
evidence instead of reporting a false write success. The default 30-day
|
|
101
|
+
retention keeps normal operational history within the read bound.
|
|
102
|
+
Diagnostics expose truncation, corrupted lines, writer
|
|
103
|
+
restarts, legacy records and pending receipts as **uncertainty**. They never
|
|
104
|
+
grant approval, Context write rights, Owner transfer or automatic retry.
|
|
105
|
+
A missing or interrupted Writer must be checked against the authoritative
|
|
106
|
+
business receipt, not inferred from a Trace event.
|
|
107
|
+
|
|
108
|
+
The npm package includes only the SDK root, generated event catalog,
|
|
109
|
+
event definitions, private implementation and this README. It contains no
|
|
110
|
+
independent API documentation or unnecessary executable.
|
|
111
|
+
|
|
112
|
+
## Shared API observation factory
|
|
113
|
+
|
|
114
|
+
`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.
|
|
115
|
+
|
|
116
|
+
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.
|
|
117
|
+
|
|
118
|
+
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,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
|
+
}
|