@briefcase-ai/auto 0.0.0-stage → 5.0.0

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 (42) hide show
  1. package/README.md +102 -2
  2. package/dist/activate.d.ts +35 -0
  3. package/dist/activate.js +108 -0
  4. package/dist/auto.d.ts +92 -0
  5. package/dist/auto.js +350 -0
  6. package/dist/context.d.ts +49 -0
  7. package/dist/context.js +82 -0
  8. package/dist/detect.d.ts +26 -0
  9. package/dist/detect.js +127 -0
  10. package/dist/esbuild.d.ts +40 -0
  11. package/dist/esbuild.js +55 -0
  12. package/dist/exporters.d.ts +196 -0
  13. package/dist/exporters.js +405 -0
  14. package/dist/index.d.ts +16 -0
  15. package/dist/index.js +14 -0
  16. package/dist/instrument/anthropic.d.ts +40 -0
  17. package/dist/instrument/anthropic.js +178 -0
  18. package/dist/instrument/bedrock.d.ts +53 -0
  19. package/dist/instrument/bedrock.js +256 -0
  20. package/dist/instrument/core.d.ts +257 -0
  21. package/dist/instrument/core.js +772 -0
  22. package/dist/instrument/google-genai.d.ts +71 -0
  23. package/dist/instrument/google-genai.js +289 -0
  24. package/dist/instrument/openai.d.ts +68 -0
  25. package/dist/instrument/openai.js +293 -0
  26. package/dist/instrument/stainless.d.ts +41 -0
  27. package/dist/instrument/stainless.js +151 -0
  28. package/dist/loader.d.ts +79 -0
  29. package/dist/loader.js +202 -0
  30. package/dist/observe.d.ts +60 -0
  31. package/dist/observe.js +246 -0
  32. package/dist/pipeline.d.ts +48 -0
  33. package/dist/pipeline.js +155 -0
  34. package/dist/record.d.ts +54 -0
  35. package/dist/record.js +55 -0
  36. package/dist/register.d.ts +9 -0
  37. package/dist/register.js +12 -0
  38. package/dist/state.d.ts +25 -0
  39. package/dist/state.js +29 -0
  40. package/dist/util.d.ts +51 -0
  41. package/dist/util.js +198 -0
  42. package/package.json +82 -4
package/README.md CHANGED
@@ -1,3 +1,103 @@
1
- # Temporary Holding Version
1
+ # @briefcase-ai/auto
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Zero-code decision capture for Node. One decision record per call made through
4
+ `openai`, `@anthropic-ai/sdk`, `@google/genai` and `@aws-sdk/client-bedrock-runtime`, with the
5
+ same field names and `decision_type` values as Python's `briefcase.auto()`.
6
+
7
+ ```bash
8
+ npm install @briefcase-ai/auto
9
+ node --import @briefcase-ai/auto/register app.js # records on stderr as JSON lines
10
+ BRIEFCASE_EXPORTER=runs.jsonl node --import @briefcase-ai/auto/register app.js
11
+ ```
12
+
13
+ With the Python CLI (`briefcase-ai exec` sets `BRIEFCASE_AUTO=1`):
14
+
15
+ ```bash
16
+ NODE_OPTIONS=--import=@briefcase-ai/auto/register briefcase-ai exec -- node app.js
17
+ ```
18
+
19
+ In code:
20
+
21
+ ```ts
22
+ import { observe, auto, instrument, withWorkflow, shutdown } from "@briefcase-ai/auto";
23
+
24
+ observe(); // or observe("runs.jsonl"), observe("https://collector.example.com/v1/decisions")
25
+ auto(); // { captureContent?, maxContentChars?, skip?, only?, streamUsage?, contextVersion?, redact?, eager? }
26
+ instrument(client); // only for an SDK copy auto() cannot reach (bundled into the app); returns client
27
+
28
+ await withWorkflow("claim-123", async () => {
29
+ await openai.chat.completions.create({ ... }); // records carry the same workflow_id
30
+ });
31
+
32
+ await shutdown(); // flush before a short script exits
33
+ ```
34
+
35
+ Node >= 26, ESM with type declarations, no runtime dependencies. The provider SDKs and
36
+ `@opentelemetry/api` are optional peer dependencies.
37
+
38
+ ## Bundled apps and worker threads
39
+
40
+ - esbuild: `plugins: [briefcaseAuto()]` from `@briefcase-ai/auto/esbuild` keeps inlined SDKs
41
+ recordable; or `external: SDK_PACKAGES` (same module) to leave them in `node_modules`; or
42
+ `instrument(client)`. An inlined SDK that none of these covers is reported once on stderr.
43
+ - Worker threads are instrumented by the same preload; their records go to the main thread's
44
+ destination, also when a worker is terminated. Pass a workflow id to a worker through
45
+ `workerData` and `withWorkflow(name, fn, { workflowId })`.
46
+
47
+ ## Destinations
48
+
49
+ Same order and variables as Python's `briefcase.observe()`:
50
+
51
+ 1. `BRIEFCASE_EXPORTER`: `console`, `memory`, `*.jsonl`, `https://...` (POSTs
52
+ `{"records": [...]}`, bearer token from `BRIEFCASE_EXPORTER_TOKEN`; plain `http://` only
53
+ to loopback), or `otlp`.
54
+ 2. `OTEL_EXPORTER_OTLP_TRACES_ENDPOINT` / `OTEL_EXPORTER_OTLP_ENDPOINT`: OTLP/HTTP JSON, one
55
+ `briefcase.decision` span per record (attributes as Python's `OTelExporter`).
56
+ 3. The console (stderr).
57
+
58
+ Records go through a bounded in-memory queue (`exportStats()` reports dropped and failed
59
+ counts). Timers never keep the process alive; queued records are sent when the event loop
60
+ empties and on SIGTERM / SIGINT.
61
+
62
+ ## Activation rule for the preload
63
+
64
+ - `--import @briefcase-ai/auto/register` on the command line: on.
65
+ - Through `NODE_OPTIONS` only: on only with `BRIEFCASE_AUTO=1` (so npm, tsc and test runners
66
+ that inherit `NODE_OPTIONS` stay quiet).
67
+ - `BRIEFCASE_AUTO=0`: off. `BRIEFCASE_CAPTURE_CONTENT=none|hash|full` (default none),
68
+ `BRIEFCASE_AUTO_SKIP=openai,anthropic,google-genai,bedrock`, `BRIEFCASE_AUTO_EAGER=1`
69
+ (patch every installed SDK copy at startup instead of when the app loads it).
70
+
71
+ ## Patch techniques (verified against the installed packages)
72
+
73
+ | SDK | Version | Technique | ESM | CJS |
74
+ |---|---|---|---|---|
75
+ | openai | 7.62.0 | `create` on the resource class prototypes; the returned `APIPromise` is kept and only its `responsePromise` / `parseResponse` fields are wrapped; streams keep their object, with the `iterator` field wrapped | yes (both copies patched) | yes |
76
+ | @anthropic-ai/sdk | 1.12.0 | same as openai (`Messages.prototype.create`, regular and beta); `messages.stream()` and `.parse()` go through `create` | yes | yes |
77
+ | @google/genai | 3.6.1 | `generateContent` / `generateContentStream` are per-instance properties: an accessor on `Models.prototype` wraps them as the constructor assigns them; clients created before that are recorded through the internal methods they call on `Models.prototype` | yes | yes |
78
+ | @aws-sdk/client-bedrock-runtime | 3.1175.0 | an own `send` on `BedrockRuntimeClient.prototype` adds an `initialize` middleware to each client's middleware stack | one CJS copy serves both | yes |
79
+
80
+ Dual packages load their ESM and CommonJS builds as separate classes. Each copy is patched
81
+ when the application loads it: a synchronous load hook (`module.registerHooks`) appends one
82
+ statement to the few SDK files that hold patch targets, which hands the module's exports to
83
+ `auto()` after the module body has run. An app that never imports an SDK never loads it, and
84
+ an ESM app never loads the CommonJS copy (`--import` startup cost went from about +356 ms to
85
+ about +36 ms p50 with all four SDKs installed; see the docs). Named ESM imports themselves are
86
+ never reassigned: only prototypes and instances are touched. An SDK whose layout differs is
87
+ skipped whole with one warning; `status()` says why.
88
+
89
+ See `docs/features/typescript-auto.md` in the repository for limits and troubleshooting.
90
+
91
+ ## Development
92
+
93
+ ```bash
94
+ npm install
95
+ npm run typecheck && npm test && npm run build
96
+ ```
97
+
98
+ Tests are offline: each SDK gets canned JSON / SSE / AWS event-stream bodies through its own
99
+ transport hook, or a local HTTP / HTTP/2 server (bundled-app tests build real esbuild bundles;
100
+ worker tests run real `worker_threads`). `npm run bench:startup` measures the preload's
101
+ startup cost. The cross-language tests also run the repository's Python `briefcase`
102
+ package (OTelExporter, the OTLP receiver parser, HTTPExporter) when `python3` can import it,
103
+ and are skipped otherwise.
@@ -0,0 +1,35 @@
1
+ /**
2
+ * Zero-code activation, used by `register.ts` (`node --import
3
+ * @briefcase-ai/auto/register app.js`). The rule:
4
+ *
5
+ * - `BRIEFCASE_AUTO=0` (or `false`): never activates.
6
+ * - `BRIEFCASE_AUTO=1`: activates.
7
+ * - Otherwise it activates only when `--import @briefcase-ai/auto/register`
8
+ * (or `--require`) is on this process's own command line
9
+ * (`process.execArgv`). A register module that arrives only through an
10
+ * inherited `NODE_OPTIONS` does nothing without `BRIEFCASE_AUTO=1`:
11
+ * `NODE_OPTIONS` reaches every Node process started below it (npm, tsc,
12
+ * test runners, editors), and those should not start exporting records.
13
+ * `briefcase-ai exec` sets `BRIEFCASE_AUTO=1` itself.
14
+ *
15
+ * It runs on the main thread and in worker threads (a worker inherits the
16
+ * parent's `execArgv` and environment, so the same rule applies there; a
17
+ * worker's records go to the main thread when the main thread is
18
+ * observing, see observe.ts). Activation calls `observe()`
19
+ * (destination from the environment) and `auto()` with
20
+ * `BRIEFCASE_CAPTURE_CONTENT` (none | hash | full, default none) and
21
+ * `BRIEFCASE_AUTO_SKIP` (comma-separated provider names) and
22
+ * `BRIEFCASE_AUTO_EAGER=1` (patch every installed SDK copy up front instead
23
+ * of when the application loads it). Nothing here
24
+ * throws into the program: a failure is reported in one stderr line and the
25
+ * program runs uninstrumented.
26
+ */
27
+ import { type AutoStatus } from "./auto.js";
28
+ /** True when one of `registerPaths` is preloaded by this process's own command line. */
29
+ export declare function preloadedOnCommandLine(execArgv: readonly string[], registerPaths: readonly string[]): boolean;
30
+ export interface Activation {
31
+ active: boolean;
32
+ reason: string;
33
+ status?: AutoStatus;
34
+ }
35
+ export declare function activate(env: Record<string, string | undefined>, explicit: boolean): Activation;
@@ -0,0 +1,108 @@
1
+ /**
2
+ * Zero-code activation, used by `register.ts` (`node --import
3
+ * @briefcase-ai/auto/register app.js`). The rule:
4
+ *
5
+ * - `BRIEFCASE_AUTO=0` (or `false`): never activates.
6
+ * - `BRIEFCASE_AUTO=1`: activates.
7
+ * - Otherwise it activates only when `--import @briefcase-ai/auto/register`
8
+ * (or `--require`) is on this process's own command line
9
+ * (`process.execArgv`). A register module that arrives only through an
10
+ * inherited `NODE_OPTIONS` does nothing without `BRIEFCASE_AUTO=1`:
11
+ * `NODE_OPTIONS` reaches every Node process started below it (npm, tsc,
12
+ * test runners, editors), and those should not start exporting records.
13
+ * `briefcase-ai exec` sets `BRIEFCASE_AUTO=1` itself.
14
+ *
15
+ * It runs on the main thread and in worker threads (a worker inherits the
16
+ * parent's `execArgv` and environment, so the same rule applies there; a
17
+ * worker's records go to the main thread when the main thread is
18
+ * observing, see observe.ts). Activation calls `observe()`
19
+ * (destination from the environment) and `auto()` with
20
+ * `BRIEFCASE_CAPTURE_CONTENT` (none | hash | full, default none) and
21
+ * `BRIEFCASE_AUTO_SKIP` (comma-separated provider names) and
22
+ * `BRIEFCASE_AUTO_EAGER=1` (patch every installed SDK copy up front instead
23
+ * of when the application loads it). Nothing here
24
+ * throws into the program: a failure is reported in one stderr line and the
25
+ * program runs uninstrumented.
26
+ */
27
+ import { resolve } from "node:path";
28
+ import { auto, markStartup, PROVIDER_NAMES } from "./auto.js";
29
+ import { observe } from "./observe.js";
30
+ const PRELOAD_FLAGS = new Set(["--import", "--require", "-r", "--loader", "--experimental-loader"]);
31
+ /** True when one of `registerPaths` is preloaded by this process's own command line. */
32
+ export function preloadedOnCommandLine(execArgv, registerPaths) {
33
+ const matches = (value) => {
34
+ if (/^@briefcase-ai\/auto\/register(\.js)?$/.test(value))
35
+ return true;
36
+ let candidate = value;
37
+ if (candidate.startsWith("file:")) {
38
+ try {
39
+ candidate = new URL(candidate).pathname;
40
+ }
41
+ catch {
42
+ return false;
43
+ }
44
+ }
45
+ return registerPaths.some((p) => resolve(candidate) === p);
46
+ };
47
+ for (let i = 0; i < execArgv.length; i++) {
48
+ const arg = execArgv[i];
49
+ const eq = arg.indexOf("=");
50
+ if (eq > 0 && PRELOAD_FLAGS.has(arg.slice(0, eq))) {
51
+ if (matches(arg.slice(eq + 1)))
52
+ return true;
53
+ }
54
+ else if (PRELOAD_FLAGS.has(arg) && i + 1 < execArgv.length) {
55
+ if (matches(execArgv[i + 1]))
56
+ return true;
57
+ i++;
58
+ }
59
+ }
60
+ return false;
61
+ }
62
+ function report(message) {
63
+ try {
64
+ process.stderr.write(`briefcase: ${message}\n`);
65
+ }
66
+ catch {
67
+ // never break the program
68
+ }
69
+ }
70
+ export function activate(env, explicit) {
71
+ const flag = (env["BRIEFCASE_AUTO"] ?? "").trim().toLowerCase();
72
+ if (flag === "0" || flag === "false")
73
+ return { active: false, reason: "BRIEFCASE_AUTO=0" };
74
+ if (flag !== "1" && flag !== "true" && !explicit) {
75
+ return { active: false, reason: "loaded through NODE_OPTIONS without BRIEFCASE_AUTO=1" };
76
+ }
77
+ try {
78
+ let content = (env["BRIEFCASE_CAPTURE_CONTENT"] ?? "none").trim().toLowerCase();
79
+ if (!["none", "hash", "full"].includes(content)) {
80
+ report(`ignoring BRIEFCASE_CAPTURE_CONTENT=${JSON.stringify(content)} (expected none, hash or full); content capture stays off`);
81
+ content = "none";
82
+ }
83
+ const skip = (env["BRIEFCASE_AUTO_SKIP"] ?? "")
84
+ .split(",")
85
+ .map((s) => s.trim())
86
+ .filter((s) => s);
87
+ const unknown = skip.filter((s) => !PROVIDER_NAMES.includes(s));
88
+ if (unknown.length)
89
+ report(`ignoring unknown names in BRIEFCASE_AUTO_SKIP: ${unknown.join(", ")}`);
90
+ observe();
91
+ const eager = ["1", "true"].includes((env["BRIEFCASE_AUTO_EAGER"] ?? "").trim().toLowerCase());
92
+ // The preload runs before any application module: from here the load hook sees every SDK load.
93
+ if (!eager)
94
+ markStartup();
95
+ const status = auto({
96
+ captureContent: content,
97
+ skip: skip.filter((s) => PROVIDER_NAMES.includes(s)),
98
+ eager,
99
+ });
100
+ return { active: true, reason: flag === "1" || flag === "true" ? "BRIEFCASE_AUTO=1" : "--import on the command line", status };
101
+ }
102
+ catch (error) {
103
+ const name = error instanceof Error ? error.name : "Error";
104
+ const message = error instanceof Error ? error.message : String(error);
105
+ report(`auto-instrumentation is disabled for this process (${name}: ${message})`);
106
+ return { active: false, reason: `failed: ${message}` };
107
+ }
108
+ }
package/dist/auto.d.ts ADDED
@@ -0,0 +1,92 @@
1
+ /**
2
+ * `auto()`: instrument every installed provider SDK; `instrument()`,
3
+ * `undo()` and `status()`.
4
+ *
5
+ * Same provider names and decision types as Python's `briefcase.auto()`.
6
+ * A package that is not installed is skipped silently; one that is installed
7
+ * but does not have the verified layout is skipped with one warning and is
8
+ * never half-patched. Calling `auto()` again does not wrap anything twice.
9
+ */
10
+ import { type PatchTarget, type ProviderReport, type SdkFile, Instrumentor, loadCopies } from "./instrument/core.js";
11
+ import { type WatchedFile } from "./loader.js";
12
+ import type { PipelineStats } from "./pipeline.js";
13
+ export interface AutoOptions {
14
+ /**
15
+ * Record prompt / completion content. `false` / "none" (default): nothing.
16
+ * `true` / "full": content, each string cut at `maxContentChars`.
17
+ * "hash": a SHA-256 digest and a character count instead.
18
+ */
19
+ captureContent?: boolean | "none" | "hash" | "full";
20
+ /** Bound on each captured string (default 8000). */
21
+ maxContentChars?: number;
22
+ /** Applied to every captured string in "full" mode; a throwing hook yields "<redaction-failed>". */
23
+ redact?: (text: string) => string;
24
+ /** Added to every record as `context_version`. */
25
+ contextVersion?: string;
26
+ /** openai: request `stream_options.include_usage` on chat streams (adds a usage-only final chunk). */
27
+ streamUsage?: boolean;
28
+ /** Provider names to leave alone: "openai", "anthropic", "google-genai", "bedrock". */
29
+ skip?: string[];
30
+ /** Only these providers. */
31
+ only?: string[];
32
+ /**
33
+ * Load and patch every installed SDK copy (ESM and CommonJS) now, instead
34
+ * of patching each copy when the application loads it. Costs startup
35
+ * time; useful only to make `status()` final immediately.
36
+ */
37
+ eager?: boolean;
38
+ }
39
+ type TargetsFn = (inst: Instrumentor, modules: Record<string, Record<string, unknown> | undefined>, format: string) => PatchTarget[] | {
40
+ targets: PatchTarget[];
41
+ verify: () => string | null;
42
+ };
43
+ interface ProviderSpec {
44
+ name: string;
45
+ packageName: string;
46
+ verifiedVersion: string;
47
+ specifiers: string[];
48
+ files: SdkFile[];
49
+ targets: TargetsFn;
50
+ }
51
+ export declare const PROVIDERS: ProviderSpec[];
52
+ export declare const PROVIDER_NAMES: string[];
53
+ export declare const WATCHED: WatchedFile[];
54
+ export declare function setCopyLoaderForTests(loader: typeof loadCopies | null): void;
55
+ /**
56
+ * Instruments every installed provider SDK (or those named in `only`).
57
+ * Each SDK copy is patched when the application loads it (or now, if it
58
+ * is already loaded); `eager: true` loads and patches every installed copy
59
+ * immediately. Safe to call more than once: a provider that is already
60
+ * instrumented is left as it is. Records are only produced once
61
+ * `observe()` has set a destination.
62
+ */
63
+ export declare function auto(input?: AutoOptions): AutoStatus;
64
+ /** Marks the load hook as installed before any application module (called by the preload). */
65
+ export declare function markStartup(): void;
66
+ /**
67
+ * Instruments the SDK copy a client (or client class) belongs to, by its
68
+ * prototypes: for an SDK bundled into the application, or any copy
69
+ * `auto()` cannot reach. Every client of that copy, created before or
70
+ * after, is covered. Returns `target` unchanged. Never throws: an object
71
+ * that is not a supported client is reported once on stderr.
72
+ *
73
+ * Supported: `new OpenAI()` / `OpenAI`, `new Anthropic()` / `Anthropic`,
74
+ * `new GoogleGenAI()` (or its `.models`, or `Models`), and
75
+ * `new BedrockRuntimeClient()` / `new BedrockRuntime()` / either class.
76
+ */
77
+ export declare function instrument<T>(target: T, input?: AutoOptions): T;
78
+ export interface AutoStatus {
79
+ observing: boolean;
80
+ destination: string | null;
81
+ providers: Omit<ProviderReport, "instrumentor">[];
82
+ stats: PipelineStats;
83
+ }
84
+ /**
85
+ * Restores what `auto()` patched (one provider, or all). A target that
86
+ * someone else re-patched after `auto()` is left in place and listed under
87
+ * `refusedUndo`; our wrapper inside it stops recording.
88
+ */
89
+ export declare function undo(name?: string): AutoStatus;
90
+ /** What is patched, what was skipped and why, and the export counters. */
91
+ export declare function status(): AutoStatus;
92
+ export {};