@stackbone/sdk 0.1.0-alpha.8 → 0.1.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.
- package/CHANGELOG.md +6 -0
- package/README.md +0 -5
- package/observability/index.cjs +1 -1
- package/observability/index.cjs.map +1 -1
- package/observability/index.js +1 -1
- package/observability/index.js.map +1 -1
- package/package.json +1 -1
- package/stackbone-sdk-0.1.0.tgz +0 -0
- package/stackbone-sdk-0.1.0-alpha.8.tgz +0 -0
package/CHANGELOG.md
CHANGED
|
@@ -7,6 +7,12 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
|
|
7
7
|
|
|
8
8
|
## [Unreleased]
|
|
9
9
|
|
|
10
|
+
## [0.1.0] - 2026-07-01
|
|
11
|
+
|
|
12
|
+
### Changed
|
|
13
|
+
|
|
14
|
+
- **First stable release.** No API changes since `0.1.0-alpha.8`; promotes the SDK to a stable line so `npm i @stackbone/sdk` resolves it through the `latest` dist-tag and generated projects can pin it exactly.
|
|
15
|
+
|
|
10
16
|
## [0.1.0-alpha.8] - 2026-07-01
|
|
11
17
|
|
|
12
18
|
### Added
|
package/README.md
CHANGED
|
@@ -26,11 +26,6 @@ Official TypeScript SDK for [Stackbone](https://stackbone.ai) — the marketplac
|
|
|
26
26
|
`@stackbone/sdk` is the SDK every Stackbone workspace depends on. From a generated workspace:
|
|
27
27
|
|
|
28
28
|
```bash
|
|
29
|
-
# Alpha (today)
|
|
30
|
-
pnpm add @stackbone/sdk@alpha
|
|
31
|
-
|
|
32
|
-
# Once we cut a stable release the unscoped tag will resolve to the latest
|
|
33
|
-
# minor:
|
|
34
29
|
pnpm add @stackbone/sdk
|
|
35
30
|
```
|
|
36
31
|
|
package/observability/index.cjs
CHANGED
|
@@ -9,7 +9,7 @@ var __defProp = Object.defineProperty;
|
|
|
9
9
|
var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
|
|
10
10
|
|
|
11
11
|
// package.json
|
|
12
|
-
var version = "0.1.0
|
|
12
|
+
var version = "0.1.0";
|
|
13
13
|
var storage = new async_hooks.AsyncLocalStorage();
|
|
14
14
|
function getInvocationContext() {
|
|
15
15
|
return storage.getStore();
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../libs/sdk/package.json","../../../../libs/sdk/src/runtime/invocation-context.ts","../../../../libs/sdk/src/observability/logger.ts"],"names":["storage","AsyncLocalStorage","getInvocationContext","getStore","LOG_LEVELS","trace","debug","info","warn","error","fatal","DEFAULT_BATCH_SIZE","DEFAULT_INTERVAL_MS","DEFAULT_HTTP_TIMEOUT_MS","createPlatformLogger","options","otelEndpoint","undefined","mode","baseBindings","run_id","runId","installationId","agentId","destination","OtlpHttpDestination","endpoint","resourceAttributes","httpTimeoutMs","flushBatchSize","flushIntervalMs","fetchImpl","JsonlFileDestination","runsDir","defaultRunsDir","appendFileImpl","mkdirImpl","now","Date","buildLogger","opts","writeAt","level","msgOrObj","msg","time","levelNumber","record","String","Object","assign","ctx","trace_id","invocationId","handler","write","child","bindings","flush","close","path","appendFile","mkdir","inFlight","Promise","resolve","dirReady","p","d","recursive","line","JSON","stringify","then","dirname","process","stderr","Error","message","url","buffer","timer","closed","replace","fetch","push","length","armTimer","drained","splice","disarmTimer","post","catch","setTimeout","unref","clearTimeout","records","body","buildOtlpLogsBody","controller","AbortController","timeout","abort","resp","method","headers","signal","ok","text","status","slice","SDK_SCOPE","name","version","resourceLogs","resource","attributes","toOtlpAttributes","scopeLogs","scope","logRecords","map","toOtlpLogRecord","rest","timeUnixNano","severityNumber","severityText","stringValue","toOtlpAttributesFromUnknown","SEVERITY_TEXT_BY_LEVEL","fromEntries","entries","value","toUpperCase","attrs","key","out","Number","isInteger","intValue","doubleValue","boolValue","homedir"],"mappings":";;;;;;;;;;;AAEE,IAAA,OAAA,GAAW,eAAA;ACiDb,IAAMA,OAAAA,GAAU,IAAIC,6BAAAA,EAAAA;AAeb,SAASC,oBAAAA,GAAAA;AACd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kD,QAAAA,GAAAA;QAAKH,KAAAA,EAAO;AAAEO,UAAAA,QAAAA,EAAU3F,OAAOoF,KAAAA;AAAO;OAAE,CAAA;AAC3EI,WAAAA,GAAAA,CAAInD,IAAAA,CAAK;AAAEkD,QAAAA,GAAAA;QAAKH,KAAAA,EAAO;UAAEQ,WAAAA,EAAaR;AAAM;OAAE,CAAA;IACrD,CAAA,MAAA,IAAW,OAAOA,UAAU,SAAA,EAAW;AACrCI,MAAAA,GAAAA,CAAInD,IAAAA,CAAK;AAAEkD,QAAAA,GAAAA;QAAKH,KAAAA,EAAO;UAAES,SAAAA,EAAWT;AAAM;OAAE,CAAA;IAC9C,CAAA,MAAO;AACLI,MAAAA,GAAAA,CAAInD,IAAAA,CAAK;AAAEkD,QAAAA,GAAAA;QAAKH,KAAAA,EAAO;UAAEL,WAAAA,EAAaxD,IAAAA,CAAKC,UAAU4D,KAAAA;AAAO;OAAE,CAAA;AAChE,IAAA;AACF,EAAA;AACA,EAAA,OAAOI,GAAAA;AACT;AAhBSR,MAAAA,CAAAA,2BAAAA,EAAAA,6BAAAA,CAAAA;AAkBF,SAAS9F,cAAAA,GAAAA;AACd,EAAA,OAAO+B,YAAAA,CAAQ6E,UAAAA,EAAAA,EAAW,YAAA,EAAc,OAAO,MAAA,CAAA;AACjD;AAFgB5G,MAAAA,CAAAA,cAAAA,EAAAA,gBAAAA,CAAAA","file":"index.cjs","sourcesContent":["{\n \"name\": \"@stackbone/sdk\",\n \"version\": \"0.1.0-alpha.8\",\n \"license\": \"UNLICENSED\",\n \"description\": \"Official TypeScript SDK for Stackbone — the marketplace and managed runtime for containerized AI agents.\",\n \"type\": \"module\",\n \"sideEffects\": false,\n \"main\": \"./dist/index.cjs\",\n \"module\": \"./dist/index.js\",\n \"types\": \"./dist/index.d.ts\",\n \"exports\": {\n \".\": {\n \"import\": {\n \"types\": \"./dist/index.d.ts\",\n \"default\": \"./dist/index.js\"\n },\n \"require\": {\n \"types\": \"./dist/index.d.cts\",\n \"default\": \"./dist/index.cjs\"\n }\n },\n \"./db\": {\n \"import\": {\n \"types\": \"./dist/db/index.d.ts\",\n \"default\": \"./dist/db/index.js\"\n },\n \"require\": {\n \"types\": \"./dist/db/index.d.cts\",\n \"default\": \"./dist/db/index.cjs\"\n }\n },\n \"./workflow\": {\n \"import\": {\n \"types\": \"./dist/workflow.d.ts\",\n \"default\": \"./dist/workflow.js\"\n },\n \"require\": {\n \"types\": \"./dist/workflow.d.cts\",\n \"default\": \"./dist/workflow.cjs\"\n }\n },\n \"./connect\": {\n \"import\": {\n \"types\": \"./dist/connect.d.ts\",\n \"default\": \"./dist/connect.js\"\n },\n \"require\": {\n \"types\": \"./dist/connect.d.cts\",\n \"default\": \"./dist/connect.cjs\"\n }\n },\n \"./eve\": {\n \"import\": {\n \"types\": \"./dist/eve.d.ts\",\n \"default\": \"./dist/eve.js\"\n },\n \"require\": {\n \"types\": \"./dist/eve.d.cts\",\n \"default\": \"./dist/eve.cjs\"\n }\n },\n \"./db/testing\": {\n \"import\": {\n \"types\": \"./dist/db/testing/index.d.ts\",\n \"default\": \"./dist/db/testing/index.js\"\n },\n \"require\": {\n \"types\": \"./dist/db/testing/index.d.cts\",\n \"default\": \"./dist/db/testing/index.cjs\"\n }\n },\n \"./observability\": {\n \"import\": {\n \"types\": \"./dist/observability/index.d.ts\",\n \"default\": \"./dist/observability/index.js\"\n },\n \"require\": {\n \"types\": \"./dist/observability/index.d.cts\",\n \"default\": \"./dist/observability/index.cjs\"\n }\n },\n \"./queues/types\": {\n \"import\": {\n \"types\": \"./dist/queues/types.d.ts\",\n \"default\": \"./dist/queues/types.js\"\n },\n \"require\": {\n \"types\": \"./dist/queues/types.d.cts\",\n \"default\": \"./dist/queues/types.cjs\"\n }\n },\n \"./rag/schema\": {\n \"import\": {\n \"types\": \"./dist/rag/schema.d.ts\",\n \"default\": \"./dist/rag/schema.js\"\n },\n \"require\": {\n \"types\": \"./dist/rag/schema.d.cts\",\n \"default\": \"./dist/rag/schema.cjs\"\n }\n },\n \"./package.json\": \"./package.json\"\n },\n \"files\": [\n \"dist\",\n \"README.md\",\n \"CHANGELOG.md\"\n ],\n \"publishConfig\": {\n \"access\": \"public\"\n },\n \"engines\": {\n \"node\": \">=24\"\n },\n \"repository\": {\n \"type\": \"git\",\n \"url\": \"git+https://github.com/stackbone/stackbone.git\",\n \"directory\": \"libs/sdk\"\n },\n \"homepage\": \"https://stackbone.ai\",\n \"bugs\": {\n \"url\": \"https://github.com/stackbone/stackbone/issues\"\n },\n \"keywords\": [\n \"stackbone\",\n \"ai-agents\",\n \"agent-sdk\",\n \"containerized-agents\",\n \"openrouter\",\n \"rag\",\n \"pgvector\",\n \"drizzle\",\n \"openai\",\n \"postgres\"\n ],\n \"peerDependencies\": {\n \"@ai-sdk/openai-compatible\": \"*\",\n \"eve\": \"*\",\n \"workflow\": \"*\"\n },\n \"peerDependenciesMeta\": {\n \"@ai-sdk/openai-compatible\": {\n \"optional\": true\n },\n \"eve\": {\n \"optional\": true\n },\n \"workflow\": {\n \"optional\": true\n }\n },\n \"dependencies\": {\n \"@aws-sdk/client-s3\": \"^3.1038.0\",\n \"@aws-sdk/s3-request-presigner\": \"^3.1038.0\",\n \"@stackbone/crypto\": \"workspace:*\",\n \"@stackbone/prompt-compiler\": \"workspace:*\",\n \"@stackbone/rag-core\": \"workspace:*\",\n \"@stackbone/s3-client\": \"workspace:*\",\n \"@stackbone/validators\": \"workspace:*\",\n \"@testcontainers/postgresql\": \"^11.14.0\",\n \"drizzle-orm\": \"0.45.2\",\n \"openai\": \"^6.42.0\",\n \"postgres\": \"3.4.9\",\n \"unpdf\": \"^0.12.1\",\n \"zod\": \"^4.3.6\"\n }\n}\n","// Process-wide invocation context, propagated with `AsyncLocalStorage`.\n//\n// The runtime request handler wraps each `capability.run(...)` in this context\n// (see `@stackbone/agent-server`'s `request-handler`), so any code running\n// inside an invoke — the creator's handler, the SDK's own loggers, a stray\n// `console.log` — can recover the active `invocationId` / `runId` without the\n// handler having to thread them through every call.\n//\n// Why an ALS and not a plain module variable: the agent process serves invokes\n// concurrently (the node:http adapter does not serialise requests). A single\n// mutable \"current invocation\" would be clobbered the moment two invokes\n// overlap. `AsyncLocalStorage` keeps a separate store per async call tree, so\n// each invoke's logs stay correlated to the right run even under concurrency.\n//\n// `invocationId` is the value the canonical logs call `trace_id` (the control\n// plane mints it once per invoke and threads it through the envelope); `runId`\n// is the run the invoke belongs to.\n\nimport { AsyncLocalStorage } from 'node:async_hooks';\n\nexport interface InvocationContext {\n /** The envelope's `invocationId` — surfaced on log lines as `trace_id`. */\n readonly invocationId: string;\n /** The run this invoke belongs to — surfaced on log lines as `run_id`. */\n readonly runId: string;\n /**\n * The handler this invoke routed to — `invoke` for a direct entry or the\n * named job handler (e.g. `demo-log-job`) the dispatcher delivered to.\n * Surfaced on log lines as `handler` so the Studio logs trail can tell which\n * entrypoint emitted each line. Optional so a caller that binds a context\n * without routing info (older tests, lifecycle hooks) still type-checks.\n */\n readonly handler?: string;\n /**\n * The projected `run_steps.id` of the workflow step currently executing, when\n * the runtime can attribute the active async tree to one step. The\n * workflow-HITL helper reads it so an approval row can be anchored to the\n * exact step that requested it (`approvals.requested_by_step_id`, A6).\n *\n * GAP (2026-06-20): no caller populates this yet. The emulator binds the\n * invocation context once per WHOLE flow dispatch (see the runtime-mount\n * `flowPost` wrap), not per step, and the Workflow World runs as a FLAT tree\n * whose events carry `writer: null` / `executionContext: null`, so the\n * per-step World id is not visible at the point a `\"use step\"` runs. The seam\n * is threaded end-to-end (context → ambient approval client → INSERT) so the\n * column is stamped the moment a step id becomes available, without another\n * surface change. Until then it stays `undefined` and the column stays NULL.\n */\n readonly requestedByStepId?: string;\n}\n\nconst storage = new AsyncLocalStorage<InvocationContext>();\n\n/**\n * Runs `fn` with `context` bound as the active invocation. The context stays\n * available to every synchronous and asynchronous continuation rooted in this\n * call (i.e. across `await`s inside `fn`). Returns whatever `fn` returns.\n */\nexport function runWithInvocationContext<T>(context: InvocationContext, fn: () => T): T {\n return storage.run(context, fn);\n}\n\n/**\n * Returns the active invocation context, or `undefined` when called outside any\n * invoke (process boot, lifecycle events, tests that don't set one up).\n */\nexport function getInvocationContext(): InvocationContext | undefined {\n return storage.getStore();\n}\n\n/**\n * Ergonomic wrapper for callers that already hold a single correlation id and\n * want to bind it as the active run/trace for `fn` — the durable workflow step\n * call-site is the first such caller (F5): it knows the projected `run_id` and\n * the World run id, and wraps a step's execution so the step's logs and SDK\n * operations correlate to its run.\n *\n * It does NOT generate ids — that stays a caller concern, exactly like\n * `runWithInvocationContext`. `runId` and `invocationId` default to the single\n * `id` you pass, so `runWithCallerId(runId, fn)` binds a context where the run\n * and trace share that id; pass distinct values (e.g. the World run id as the\n * trace) via the options form.\n */\nexport function runWithCallerId<T>(\n id: string,\n fn: () => T,\n options?: { readonly invocationId?: string; readonly handler?: string },\n): T {\n const context: InvocationContext = {\n runId: id,\n invocationId: options?.invocationId ?? id,\n // Only attach `handler` when supplied: `exactOptionalPropertyTypes` forbids\n // an explicit `undefined` on an optional property.\n ...(options?.handler !== undefined ? { handler: options.handler } : {}),\n };\n return runWithInvocationContext(context, fn);\n}\n","import { appendFile, mkdir } from 'node:fs/promises';\nimport { homedir } from 'node:os';\nimport { dirname, resolve } from 'node:path';\n\nimport { version as SDK_VERSION } from '../../package.json';\nimport { getInvocationContext } from '../runtime/invocation-context';\n\n// Numeric levels match Pino so JSONL files produced in local mode work with\n// `pino-pretty` and other Pino-aware tooling without translation.\nexport const LOG_LEVELS = {\n trace: 10,\n debug: 20,\n info: 30,\n warn: 40,\n error: 50,\n fatal: 60,\n} as const;\n\nexport type LogLevelName = keyof typeof LOG_LEVELS;\nexport type LogLevelNumber = (typeof LOG_LEVELS)[LogLevelName];\n\nexport interface LogRecord {\n /** Pino-style numeric level. */\n level: LogLevelNumber;\n /** Epoch milliseconds. Pino uses `time` as a number. */\n time: number;\n msg: string;\n run_id: string;\n trace_id?: string;\n installation_id?: string;\n agent_id?: string;\n [key: string]: unknown;\n}\n\nexport interface PlatformLoggerOptions {\n runId: string;\n installationId?: string | undefined;\n agentId?: string | undefined;\n /**\n * When set (cloud), logs are batched and POSTed to `<endpoint>/v1/logs` as\n * OTLP/HTTP/JSON. When unset (local), logs are appended to\n * `<runsDir>/<runId>.jsonl`. Falls back to `OTEL_EXPORTER_OTLP_ENDPOINT`.\n */\n otelEndpoint?: string | undefined;\n /** Local-only: directory where JSONL files live. Defaults to `~/.stackbone/dev/runs`. */\n runsDir?: string | undefined;\n /** Cloud-only: extra OTel resource attributes to send with every batch. */\n resourceAttributes?: Record<string, string> | undefined;\n /** Cloud-only: HTTP timeout per OTLP POST in ms. Defaults to 5_000. */\n httpTimeoutMs?: number | undefined;\n /** Flush trigger by buffer size. Defaults to 50. */\n flushBatchSize?: number | undefined;\n /** Flush trigger by elapsed time (ms). Defaults to 1_000. */\n flushIntervalMs?: number | undefined;\n /** Test seam — fetch implementation. Defaults to global `fetch`. */\n fetchImpl?: typeof fetch | undefined;\n /** Test seam — `fs.appendFile`-shaped sink the local destination uses. */\n appendFileImpl?: ((path: string, data: string) => Promise<void>) | undefined;\n /** Test seam — `fs.mkdir`-shaped helper the local destination uses. */\n mkdirImpl?: ((path: string) => Promise<void>) | undefined;\n /** Test seam — clock for `time` field. Defaults to `Date.now`. */\n now?: (() => number) | undefined;\n /** Override mode resolution (skips the env detection). */\n mode?: PlatformLoggerMode | undefined;\n}\n\nexport type PlatformLoggerMode = 'local' | 'cloud';\n\nexport interface PinoLike {\n trace(msgOrObj: unknown, msg?: string): void;\n debug(msgOrObj: unknown, msg?: string): void;\n info(msgOrObj: unknown, msg?: string): void;\n warn(msgOrObj: unknown, msg?: string): void;\n error(msgOrObj: unknown, msg?: string): void;\n fatal(msgOrObj: unknown, msg?: string): void;\n}\n\nexport interface PlatformLogger extends PinoLike {\n readonly mode: PlatformLoggerMode;\n /** Bind extra fields and return a child logger sharing the same destination. */\n child(bindings: Record<string, unknown>): PlatformLogger;\n /** Force-flush pending writes (close file handle or POST OTLP batch). */\n flush(): Promise<void>;\n /** Stop accepting writes and release resources. */\n close(): Promise<void>;\n}\n\ninterface Destination {\n write(record: LogRecord): void;\n flush(): Promise<void>;\n close(): Promise<void>;\n}\n\nconst DEFAULT_BATCH_SIZE = 50;\nconst DEFAULT_INTERVAL_MS = 1_000;\nconst DEFAULT_HTTP_TIMEOUT_MS = 5_000;\n\n/**\n * Creates a Pino-aligned logger that writes JSONL to disk in local mode and\n * batches OTLP/HTTP/JSON log records to an OTel collector in cloud mode. Mode\n * is resolved from `OTEL_EXPORTER_OTLP_ENDPOINT` or the explicit override.\n */\nexport function createPlatformLogger(options: PlatformLoggerOptions): PlatformLogger {\n // The resolver is the single seam that reads `OTEL_EXPORTER_OTLP_ENDPOINT`.\n // Runtime code building a logger on the `@stackbone/sdk/observability`\n // subpath supplies `otelEndpoint` explicitly (typically plumbed from\n // `ResolvedConfig`). The `undefined` here means \"no `otelEndpoint` ⇒ local\n // JSONL mode\" (matches the docstring).\n const otelEndpoint = options.otelEndpoint ?? undefined;\n const mode: PlatformLoggerMode = options.mode ?? (otelEndpoint ? 'cloud' : 'local');\n\n const baseBindings: Record<string, unknown> = { run_id: options.runId };\n if (options.installationId !== undefined)\n baseBindings['installation_id'] = options.installationId;\n if (options.agentId !== undefined) baseBindings['agent_id'] = options.agentId;\n\n const destination: Destination =\n mode === 'cloud'\n ? new OtlpHttpDestination({\n endpoint: otelEndpoint ?? '',\n resourceAttributes: options.resourceAttributes ?? {},\n httpTimeoutMs: options.httpTimeoutMs ?? DEFAULT_HTTP_TIMEOUT_MS,\n flushBatchSize: options.flushBatchSize ?? DEFAULT_BATCH_SIZE,\n flushIntervalMs: options.flushIntervalMs ?? DEFAULT_INTERVAL_MS,\n ...(options.fetchImpl !== undefined ? { fetchImpl: options.fetchImpl } : {}),\n })\n : new JsonlFileDestination({\n runId: options.runId,\n runsDir: options.runsDir ?? defaultRunsDir(),\n ...(options.appendFileImpl !== undefined\n ? { appendFileImpl: options.appendFileImpl }\n : {}),\n ...(options.mkdirImpl !== undefined ? { mkdirImpl: options.mkdirImpl } : {}),\n });\n\n const now = options.now ?? Date.now;\n return buildLogger({ destination, baseBindings, mode, now });\n}\n\ninterface LoggerBuildOptions {\n destination: Destination;\n baseBindings: Record<string, unknown>;\n mode: PlatformLoggerMode;\n now: () => number;\n}\n\nfunction buildLogger(opts: LoggerBuildOptions): PlatformLogger {\n const writeAt = (level: LogLevelName, msgOrObj: unknown, msg?: string): void => {\n const time = opts.now();\n const levelNumber = LOG_LEVELS[level];\n const record: LogRecord = {\n level: levelNumber,\n time,\n msg: '',\n run_id: String(opts.baseBindings['run_id'] ?? ''),\n ...opts.baseBindings,\n };\n if (typeof msgOrObj === 'string') {\n record.msg = msgOrObj;\n } else if (msgOrObj && typeof msgOrObj === 'object') {\n Object.assign(record, msgOrObj);\n if (typeof msg === 'string') record.msg = msg;\n else if (typeof record.msg !== 'string') record.msg = '';\n }\n // Ambient invocation correlation: when used inside an invoke (the request\n // handler wraps `capability.run` in an AsyncLocalStorage context), stamp\n // `trace_id` / `run_id` from that context unless the caller already set them\n // explicitly via bindings or per-call meta. Outside an invoke there is no\n // context, so the records keep their previous shape.\n const ctx = getInvocationContext();\n if (ctx) {\n if (record.trace_id === undefined) record.trace_id = ctx.invocationId;\n if (!record.run_id) record.run_id = ctx.runId;\n if (record['handler'] === undefined && ctx.handler !== undefined) {\n record['handler'] = ctx.handler;\n }\n }\n opts.destination.write(record);\n };\n\n const child = (bindings: Record<string, unknown>): PlatformLogger =>\n buildLogger({ ...opts, baseBindings: { ...opts.baseBindings, ...bindings } });\n\n return {\n mode: opts.mode,\n trace: (msgOrObj, msg) => writeAt('trace', msgOrObj, msg),\n debug: (msgOrObj, msg) => writeAt('debug', msgOrObj, msg),\n info: (msgOrObj, msg) => writeAt('info', msgOrObj, msg),\n warn: (msgOrObj, msg) => writeAt('warn', msgOrObj, msg),\n error: (msgOrObj, msg) => writeAt('error', msgOrObj, msg),\n fatal: (msgOrObj, msg) => writeAt('fatal', msgOrObj, msg),\n child,\n flush: () => opts.destination.flush(),\n close: () => opts.destination.close(),\n };\n}\n\ninterface JsonlFileDestinationOptions {\n runId: string;\n runsDir: string;\n appendFileImpl?: (path: string, data: string) => Promise<void>;\n mkdirImpl?: (path: string) => Promise<void>;\n}\n\nclass JsonlFileDestination implements Destination {\n private readonly path: string;\n private readonly appendFile: (path: string, data: string) => Promise<void>;\n private readonly mkdir: (path: string) => Promise<void>;\n private inFlight: Promise<void> = Promise.resolve();\n private dirReady = false;\n\n constructor(opts: JsonlFileDestinationOptions) {\n this.path = resolve(opts.runsDir, `${opts.runId}.jsonl`);\n this.appendFile = opts.appendFileImpl ?? ((p, d) => appendFile(p, d, 'utf8'));\n this.mkdir =\n opts.mkdirImpl ??\n (async (p) => {\n await mkdir(p, { recursive: true });\n });\n }\n\n write(record: LogRecord): void {\n const line = `${JSON.stringify(record)}\\n`;\n this.inFlight = this.inFlight.then(async () => {\n if (!this.dirReady) {\n await this.mkdir(dirname(this.path));\n this.dirReady = true;\n }\n try {\n await this.appendFile(this.path, line);\n } catch (error) {\n process.stderr.write(\n `[stackbone/sdk] PlatformLogger JSONL write failed: ${error instanceof Error ? error.message : String(error)}\\n`,\n );\n }\n });\n }\n\n async flush(): Promise<void> {\n await this.inFlight;\n }\n\n async close(): Promise<void> {\n await this.flush();\n }\n}\n\ninterface OtlpHttpDestinationOptions {\n endpoint: string;\n resourceAttributes: Record<string, string>;\n httpTimeoutMs: number;\n flushBatchSize: number;\n flushIntervalMs: number;\n fetchImpl?: typeof fetch;\n}\n\n// OTLP/HTTP/JSON spec: OpenTelemetry Logs Data Model §B.1. Failures log to\n// stderr — telemetry must never block agent execution.\nclass OtlpHttpDestination implements Destination {\n private readonly url: string;\n private readonly resourceAttributes: Record<string, string>;\n private readonly httpTimeoutMs: number;\n private readonly flushBatchSize: number;\n private readonly flushIntervalMs: number;\n private readonly fetchImpl: typeof fetch;\n private buffer: LogRecord[] = [];\n private timer: NodeJS.Timeout | null = null;\n private inFlight: Promise<void> = Promise.resolve();\n private closed = false;\n\n constructor(opts: OtlpHttpDestinationOptions) {\n this.url = `${opts.endpoint.replace(/\\/+$/, '')}/v1/logs`;\n this.resourceAttributes = opts.resourceAttributes;\n this.httpTimeoutMs = opts.httpTimeoutMs;\n this.flushBatchSize = opts.flushBatchSize;\n this.flushIntervalMs = opts.flushIntervalMs;\n this.fetchImpl = opts.fetchImpl ?? fetch;\n }\n\n write(record: LogRecord): void {\n if (this.closed) return;\n this.buffer.push(record);\n if (this.buffer.length >= this.flushBatchSize) {\n void this.flush();\n } else {\n this.armTimer();\n }\n }\n\n async flush(): Promise<void> {\n await this.inFlight;\n if (this.buffer.length === 0) return;\n const drained = this.buffer.splice(0, this.buffer.length);\n this.disarmTimer();\n this.inFlight = this.post(drained).catch((error) => {\n process.stderr.write(\n `[stackbone/sdk] PlatformLogger OTLP POST failed: ${error instanceof Error ? error.message : String(error)}\\n`,\n );\n });\n await this.inFlight;\n }\n\n async close(): Promise<void> {\n this.closed = true;\n await this.flush();\n }\n\n private armTimer(): void {\n if (this.timer) return;\n this.timer = setTimeout(() => {\n this.timer = null;\n void this.flush();\n }, this.flushIntervalMs);\n this.timer.unref?.();\n }\n\n private disarmTimer(): void {\n if (this.timer) {\n clearTimeout(this.timer);\n this.timer = null;\n }\n }\n\n private async post(records: LogRecord[]): Promise<void> {\n const body = JSON.stringify(buildOtlpLogsBody(records, this.resourceAttributes));\n const controller = new AbortController();\n const timeout = setTimeout(() => controller.abort(), this.httpTimeoutMs);\n try {\n const resp = await this.fetchImpl(this.url, {\n method: 'POST',\n headers: { 'content-type': 'application/json' },\n body,\n signal: controller.signal,\n });\n if (!resp.ok) {\n const text = await resp.text().catch(() => '');\n throw new Error(`HTTP ${resp.status}${text ? `: ${text.slice(0, 200)}` : ''}`);\n }\n } finally {\n clearTimeout(timeout);\n }\n }\n}\n\ninterface OtlpKeyValue {\n key: string;\n value:\n | { stringValue: string }\n | { intValue: string }\n | { doubleValue: number }\n | { boolValue: boolean };\n}\n\ninterface OtlpResource {\n attributes: OtlpKeyValue[];\n}\n\ninterface OtlpLogRecord {\n timeUnixNano: string;\n severityNumber: number;\n severityText: string;\n body: { stringValue: string };\n attributes: OtlpKeyValue[];\n}\n\ninterface OtlpLogsBody {\n resourceLogs: Array<{\n resource: OtlpResource;\n scopeLogs: Array<{\n scope: { name: string; version: string };\n logRecords: OtlpLogRecord[];\n }>;\n }>;\n}\n\nconst SDK_SCOPE = { name: '@stackbone/sdk', version: SDK_VERSION };\n\nfunction buildOtlpLogsBody(\n records: LogRecord[],\n resourceAttributes: Record<string, string>,\n): OtlpLogsBody {\n return {\n resourceLogs: [\n {\n resource: { attributes: toOtlpAttributes(resourceAttributes) },\n scopeLogs: [\n {\n scope: SDK_SCOPE,\n logRecords: records.map(toOtlpLogRecord),\n },\n ],\n },\n ],\n };\n}\n\nfunction toOtlpLogRecord(record: LogRecord): OtlpLogRecord {\n const { level, time, msg, ...rest } = record;\n return {\n timeUnixNano: `${time * 1_000_000}`,\n severityNumber: level,\n severityText: severityText(level),\n body: { stringValue: msg },\n attributes: toOtlpAttributesFromUnknown(rest),\n };\n}\n\nconst SEVERITY_TEXT_BY_LEVEL: Record<number, string> = Object.fromEntries(\n Object.entries(LOG_LEVELS).map(([name, value]) => [value, name.toUpperCase()]),\n);\n\nfunction severityText(level: number): string {\n return SEVERITY_TEXT_BY_LEVEL[level] ?? 'INFO';\n}\n\nfunction toOtlpAttributes(attrs: Record<string, string>): OtlpKeyValue[] {\n return Object.entries(attrs).map(([key, value]) => ({\n key,\n value: { stringValue: value },\n }));\n}\n\nfunction toOtlpAttributesFromUnknown(attrs: Record<string, unknown>): OtlpKeyValue[] {\n const out: OtlpKeyValue[] = [];\n for (const [key, value] of Object.entries(attrs)) {\n if (value === null || value === undefined) continue;\n if (typeof value === 'string') {\n out.push({ key, value: { stringValue: value } });\n } else if (typeof value === 'number') {\n if (Number.isInteger(value)) out.push({ key, value: { intValue: String(value) } });\n else out.push({ key, value: { doubleValue: value } });\n } else if (typeof value === 'boolean') {\n out.push({ key, value: { boolValue: value } });\n } else {\n out.push({ key, value: { stringValue: JSON.stringify(value) } });\n }\n }\n return out;\n}\n\nexport function defaultRunsDir(): string {\n return resolve(homedir(), '.stackbone', 'dev', 'runs');\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../../../../libs/sdk/package.json","../../../../libs/sdk/src/runtime/invocation-context.ts","../../../../libs/sdk/src/observability/logger.ts"],"names":["storage","AsyncLocalStorage","getInvocationContext","getStore","LOG_LEVELS","trace","debug","info","warn","error","fatal","DEFAULT_BATCH_SIZE","DEFAULT_INTERVAL_MS","DEFAULT_HTTP_TIMEOUT_MS","createPlatformLogger","options","otelEndpoint","undefined","mode","baseBindings","run_id","runId","installationId","agentId","destination","OtlpHttpDestination","endpoint","resourceAttributes","httpTimeoutMs","flushBatchSize","flushIntervalMs","fetchImpl","JsonlFileDestination","runsDir","defaultRunsDir","appendFileImpl","mkdirImpl","now","Date","buildLogger","opts","writeAt","level","msgOrObj","msg","time","levelNumber","record","String","Object","assign","ctx","trace_id","invocationId","handler","write","child","bindings","flush","close","path","appendFile","mkdir","inFlight","Promise","resolve","dirReady","p","d","recursive","line","JSON","stringify","then","dirname","process","stderr","Error","message","url","buffer","timer","closed","replace","fetch","push","length","armTimer","drained","splice","disarmTimer","post","catch","setTimeout","unref","clearTimeout","records","body","buildOtlpLogsBody","controller","AbortController","timeout","abort","resp","method","headers","signal","ok","text","status","slice","SDK_SCOPE","name","version","resourceLogs","resource","attributes","toOtlpAttributes","scopeLogs","scope","logRecords","map","toOtlpLogRecord","rest","timeUnixNano","severityNumber","severityText","stringValue","toOtlpAttributesFromUnknown","SEVERITY_TEXT_BY_LEVEL","fromEntries","entries","value","toUpperCase","attrs","key","out","Number","isInteger","intValue","doubleValue","boolValue","homedir"],"mappings":";;;;;;;;;;;AAEE,IAAA,OAAA,GAAW,OAAA;ACiDb,IAAMA,OAAAA,GAAU,IAAIC,6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AUN,KAAAA,CAAAA,MAAY/C,IAAAA,CAAK;AAAEkD,QAAAA,GAAAA;QAAKH,KAAAA,EAAO;AAAEO,UAAAA,QAAAA,EAAU3F,OAAOoF,KAAAA;AAAO;OAAE,CAAA;AAC3EI,WAAAA,GAAAA,CAAInD,IAAAA,CAAK;AAAEkD,QAAAA,GAAAA;QAAKH,KAAAA,EAAO;UAAEQ,WAAAA,EAAaR;AAAM;OAAE,CAAA;IACrD,CAAA,MAAA,IAAW,OAAOA,UAAU,SAAA,EAAW;AACrCI,MAAAA,GAAAA,CAAInD,IAAAA,CAAK;AAAEkD,QAAAA,GAAAA;QAAKH,KAAAA,EAAO;UAAES,SAAAA,EAAWT;AAAM;OAAE,CAAA;IAC9C,CAAA,MAAO;AACLI,MAAAA,GAAAA,CAAInD,IAAAA,CAAK;AAAEkD,QAAAA,GAAAA;QAAKH,KAAAA,EAAO;UAAEL,WAAAA,EAAaxD,IAAAA,CAAKC,UAAU4D,KAAAA;AAAO;OAAE,CAAA;AAChE,IAAA;AACF,EAAA;AACA,EAAA,OAAOI,GAAAA;AACT;AAhBSR,MAAAA,CAAAA,2BAAAA,EAAAA,6BAAAA,CAAAA;AAkBF,SAAS9F,cAAAA,GAAAA;AACd,EAAA,OAAO+B,YAAAA,CAAQ6E,UAAAA,EAAAA,EAAW,YAAA,EAAc,OAAO,MAAA,CAAA;AACjD;AAFgB5G,MAAAA,CAAAA,cAAAA,EAAAA,gBAAAA,CAAAA","file":"index.cjs","sourcesContent":["{\n \"name\": \"@stackbone/sdk\",\n \"version\": \"0.1.0\",\n \"license\": \"UNLICENSED\",\n \"description\": \"Official TypeScript SDK for Stackbone — the marketplace and managed runtime for containerized AI agents.\",\n \"type\": \"module\",\n \"sideEffects\": false,\n \"main\": \"./dist/index.cjs\",\n \"module\": \"./dist/index.js\",\n \"types\": \"./dist/index.d.ts\",\n \"exports\": {\n \".\": {\n \"import\": {\n \"types\": \"./dist/index.d.ts\",\n \"default\": \"./dist/index.js\"\n },\n \"require\": {\n \"types\": \"./dist/index.d.cts\",\n \"default\": \"./dist/index.cjs\"\n }\n },\n \"./db\": {\n \"import\": {\n \"types\": \"./dist/db/index.d.ts\",\n \"default\": \"./dist/db/index.js\"\n },\n \"require\": {\n \"types\": \"./dist/db/index.d.cts\",\n \"default\": \"./dist/db/index.cjs\"\n }\n },\n \"./workflow\": {\n \"import\": {\n \"types\": \"./dist/workflow.d.ts\",\n \"default\": \"./dist/workflow.js\"\n },\n \"require\": {\n \"types\": \"./dist/workflow.d.cts\",\n \"default\": \"./dist/workflow.cjs\"\n }\n },\n \"./connect\": {\n \"import\": {\n \"types\": \"./dist/connect.d.ts\",\n \"default\": \"./dist/connect.js\"\n },\n \"require\": {\n \"types\": \"./dist/connect.d.cts\",\n \"default\": \"./dist/connect.cjs\"\n }\n },\n \"./eve\": {\n \"import\": {\n \"types\": \"./dist/eve.d.ts\",\n \"default\": \"./dist/eve.js\"\n },\n \"require\": {\n \"types\": \"./dist/eve.d.cts\",\n \"default\": \"./dist/eve.cjs\"\n }\n },\n \"./db/testing\": {\n \"import\": {\n \"types\": \"./dist/db/testing/index.d.ts\",\n \"default\": \"./dist/db/testing/index.js\"\n },\n \"require\": {\n \"types\": \"./dist/db/testing/index.d.cts\",\n \"default\": \"./dist/db/testing/index.cjs\"\n }\n },\n \"./observability\": {\n \"import\": {\n \"types\": \"./dist/observability/index.d.ts\",\n \"default\": \"./dist/observability/index.js\"\n },\n \"require\": {\n \"types\": \"./dist/observability/index.d.cts\",\n \"default\": \"./dist/observability/index.cjs\"\n }\n },\n \"./queues/types\": {\n \"import\": {\n \"types\": \"./dist/queues/types.d.ts\",\n \"default\": \"./dist/queues/types.js\"\n },\n \"require\": {\n \"types\": \"./dist/queues/types.d.cts\",\n \"default\": \"./dist/queues/types.cjs\"\n }\n },\n \"./rag/schema\": {\n \"import\": {\n \"types\": \"./dist/rag/schema.d.ts\",\n \"default\": \"./dist/rag/schema.js\"\n },\n \"require\": {\n \"types\": \"./dist/rag/schema.d.cts\",\n \"default\": \"./dist/rag/schema.cjs\"\n }\n },\n \"./package.json\": \"./package.json\"\n },\n \"files\": [\n \"dist\",\n \"README.md\",\n \"CHANGELOG.md\"\n ],\n \"publishConfig\": {\n \"access\": \"public\"\n },\n \"engines\": {\n \"node\": \">=24\"\n },\n \"repository\": {\n \"type\": \"git\",\n \"url\": \"git+https://github.com/stackbone/stackbone.git\",\n \"directory\": \"libs/sdk\"\n },\n \"homepage\": \"https://stackbone.ai\",\n \"bugs\": {\n \"url\": \"https://github.com/stackbone/stackbone/issues\"\n },\n \"keywords\": [\n \"stackbone\",\n \"ai-agents\",\n \"agent-sdk\",\n \"containerized-agents\",\n \"openrouter\",\n \"rag\",\n \"pgvector\",\n \"drizzle\",\n \"openai\",\n \"postgres\"\n ],\n \"peerDependencies\": {\n \"@ai-sdk/openai-compatible\": \"*\",\n \"eve\": \"*\",\n \"workflow\": \"*\"\n },\n \"peerDependenciesMeta\": {\n \"@ai-sdk/openai-compatible\": {\n \"optional\": true\n },\n \"eve\": {\n \"optional\": true\n },\n \"workflow\": {\n \"optional\": true\n }\n },\n \"dependencies\": {\n \"@aws-sdk/client-s3\": \"^3.1038.0\",\n \"@aws-sdk/s3-request-presigner\": \"^3.1038.0\",\n \"@stackbone/crypto\": \"workspace:*\",\n \"@stackbone/prompt-compiler\": \"workspace:*\",\n \"@stackbone/rag-core\": \"workspace:*\",\n \"@stackbone/s3-client\": \"workspace:*\",\n \"@stackbone/validators\": \"workspace:*\",\n \"@testcontainers/postgresql\": \"^11.14.0\",\n \"drizzle-orm\": \"0.45.2\",\n \"openai\": \"^6.42.0\",\n \"postgres\": \"3.4.9\",\n \"unpdf\": \"^0.12.1\",\n \"zod\": \"^4.3.6\"\n }\n}\n","// Process-wide invocation context, propagated with `AsyncLocalStorage`.\n//\n// The runtime request handler wraps each `capability.run(...)` in this context\n// (see `@stackbone/agent-server`'s `request-handler`), so any code running\n// inside an invoke — the creator's handler, the SDK's own loggers, a stray\n// `console.log` — can recover the active `invocationId` / `runId` without the\n// handler having to thread them through every call.\n//\n// Why an ALS and not a plain module variable: the agent process serves invokes\n// concurrently (the node:http adapter does not serialise requests). A single\n// mutable \"current invocation\" would be clobbered the moment two invokes\n// overlap. `AsyncLocalStorage` keeps a separate store per async call tree, so\n// each invoke's logs stay correlated to the right run even under concurrency.\n//\n// `invocationId` is the value the canonical logs call `trace_id` (the control\n// plane mints it once per invoke and threads it through the envelope); `runId`\n// is the run the invoke belongs to.\n\nimport { AsyncLocalStorage } from 'node:async_hooks';\n\nexport interface InvocationContext {\n /** The envelope's `invocationId` — surfaced on log lines as `trace_id`. */\n readonly invocationId: string;\n /** The run this invoke belongs to — surfaced on log lines as `run_id`. */\n readonly runId: string;\n /**\n * The handler this invoke routed to — `invoke` for a direct entry or the\n * named job handler (e.g. `demo-log-job`) the dispatcher delivered to.\n * Surfaced on log lines as `handler` so the Studio logs trail can tell which\n * entrypoint emitted each line. Optional so a caller that binds a context\n * without routing info (older tests, lifecycle hooks) still type-checks.\n */\n readonly handler?: string;\n /**\n * The projected `run_steps.id` of the workflow step currently executing, when\n * the runtime can attribute the active async tree to one step. The\n * workflow-HITL helper reads it so an approval row can be anchored to the\n * exact step that requested it (`approvals.requested_by_step_id`, A6).\n *\n * GAP (2026-06-20): no caller populates this yet. The emulator binds the\n * invocation context once per WHOLE flow dispatch (see the runtime-mount\n * `flowPost` wrap), not per step, and the Workflow World runs as a FLAT tree\n * whose events carry `writer: null` / `executionContext: null`, so the\n * per-step World id is not visible at the point a `\"use step\"` runs. The seam\n * is threaded end-to-end (context → ambient approval client → INSERT) so the\n * column is stamped the moment a step id becomes available, without another\n * surface change. Until then it stays `undefined` and the column stays NULL.\n */\n readonly requestedByStepId?: string;\n}\n\nconst storage = new AsyncLocalStorage<InvocationContext>();\n\n/**\n * Runs `fn` with `context` bound as the active invocation. The context stays\n * available to every synchronous and asynchronous continuation rooted in this\n * call (i.e. across `await`s inside `fn`). Returns whatever `fn` returns.\n */\nexport function runWithInvocationContext<T>(context: InvocationContext, fn: () => T): T {\n return storage.run(context, fn);\n}\n\n/**\n * Returns the active invocation context, or `undefined` when called outside any\n * invoke (process boot, lifecycle events, tests that don't set one up).\n */\nexport function getInvocationContext(): InvocationContext | undefined {\n return storage.getStore();\n}\n\n/**\n * Ergonomic wrapper for callers that already hold a single correlation id and\n * want to bind it as the active run/trace for `fn` — the durable workflow step\n * call-site is the first such caller (F5): it knows the projected `run_id` and\n * the World run id, and wraps a step's execution so the step's logs and SDK\n * operations correlate to its run.\n *\n * It does NOT generate ids — that stays a caller concern, exactly like\n * `runWithInvocationContext`. `runId` and `invocationId` default to the single\n * `id` you pass, so `runWithCallerId(runId, fn)` binds a context where the run\n * and trace share that id; pass distinct values (e.g. the World run id as the\n * trace) via the options form.\n */\nexport function runWithCallerId<T>(\n id: string,\n fn: () => T,\n options?: { readonly invocationId?: string; readonly handler?: string },\n): T {\n const context: InvocationContext = {\n runId: id,\n invocationId: options?.invocationId ?? id,\n // Only attach `handler` when supplied: `exactOptionalPropertyTypes` forbids\n // an explicit `undefined` on an optional property.\n ...(options?.handler !== undefined ? { handler: options.handler } : {}),\n };\n return runWithInvocationContext(context, fn);\n}\n","import { appendFile, mkdir } from 'node:fs/promises';\nimport { homedir } from 'node:os';\nimport { dirname, resolve } from 'node:path';\n\nimport { version as SDK_VERSION } from '../../package.json';\nimport { getInvocationContext } from '../runtime/invocation-context';\n\n// Numeric levels match Pino so JSONL files produced in local mode work with\n// `pino-pretty` and other Pino-aware tooling without translation.\nexport const LOG_LEVELS = {\n trace: 10,\n debug: 20,\n info: 30,\n warn: 40,\n error: 50,\n fatal: 60,\n} as const;\n\nexport type LogLevelName = keyof typeof LOG_LEVELS;\nexport type LogLevelNumber = (typeof LOG_LEVELS)[LogLevelName];\n\nexport interface LogRecord {\n /** Pino-style numeric level. */\n level: LogLevelNumber;\n /** Epoch milliseconds. Pino uses `time` as a number. */\n time: number;\n msg: string;\n run_id: string;\n trace_id?: string;\n installation_id?: string;\n agent_id?: string;\n [key: string]: unknown;\n}\n\nexport interface PlatformLoggerOptions {\n runId: string;\n installationId?: string | undefined;\n agentId?: string | undefined;\n /**\n * When set (cloud), logs are batched and POSTed to `<endpoint>/v1/logs` as\n * OTLP/HTTP/JSON. When unset (local), logs are appended to\n * `<runsDir>/<runId>.jsonl`. Falls back to `OTEL_EXPORTER_OTLP_ENDPOINT`.\n */\n otelEndpoint?: string | undefined;\n /** Local-only: directory where JSONL files live. Defaults to `~/.stackbone/dev/runs`. */\n runsDir?: string | undefined;\n /** Cloud-only: extra OTel resource attributes to send with every batch. */\n resourceAttributes?: Record<string, string> | undefined;\n /** Cloud-only: HTTP timeout per OTLP POST in ms. Defaults to 5_000. */\n httpTimeoutMs?: number | undefined;\n /** Flush trigger by buffer size. Defaults to 50. */\n flushBatchSize?: number | undefined;\n /** Flush trigger by elapsed time (ms). Defaults to 1_000. */\n flushIntervalMs?: number | undefined;\n /** Test seam — fetch implementation. Defaults to global `fetch`. */\n fetchImpl?: typeof fetch | undefined;\n /** Test seam — `fs.appendFile`-shaped sink the local destination uses. */\n appendFileImpl?: ((path: string, data: string) => Promise<void>) | undefined;\n /** Test seam — `fs.mkdir`-shaped helper the local destination uses. */\n mkdirImpl?: ((path: string) => Promise<void>) | undefined;\n /** Test seam — clock for `time` field. Defaults to `Date.now`. */\n now?: (() => number) | undefined;\n /** Override mode resolution (skips the env detection). */\n mode?: PlatformLoggerMode | undefined;\n}\n\nexport type PlatformLoggerMode = 'local' | 'cloud';\n\nexport interface PinoLike {\n trace(msgOrObj: unknown, msg?: string): void;\n debug(msgOrObj: unknown, msg?: string): void;\n info(msgOrObj: unknown, msg?: string): void;\n warn(msgOrObj: unknown, msg?: string): void;\n error(msgOrObj: unknown, msg?: string): void;\n fatal(msgOrObj: unknown, msg?: string): void;\n}\n\nexport interface PlatformLogger extends PinoLike {\n readonly mode: PlatformLoggerMode;\n /** Bind extra fields and return a child logger sharing the same destination. */\n child(bindings: Record<string, unknown>): PlatformLogger;\n /** Force-flush pending writes (close file handle or POST OTLP batch). */\n flush(): Promise<void>;\n /** Stop accepting writes and release resources. */\n close(): Promise<void>;\n}\n\ninterface Destination {\n write(record: LogRecord): void;\n flush(): Promise<void>;\n close(): Promise<void>;\n}\n\nconst DEFAULT_BATCH_SIZE = 50;\nconst DEFAULT_INTERVAL_MS = 1_000;\nconst DEFAULT_HTTP_TIMEOUT_MS = 5_000;\n\n/**\n * Creates a Pino-aligned logger that writes JSONL to disk in local mode and\n * batches OTLP/HTTP/JSON log records to an OTel collector in cloud mode. Mode\n * is resolved from `OTEL_EXPORTER_OTLP_ENDPOINT` or the explicit override.\n */\nexport function createPlatformLogger(options: PlatformLoggerOptions): PlatformLogger {\n // The resolver is the single seam that reads `OTEL_EXPORTER_OTLP_ENDPOINT`.\n // Runtime code building a logger on the `@stackbone/sdk/observability`\n // subpath supplies `otelEndpoint` explicitly (typically plumbed from\n // `ResolvedConfig`). The `undefined` here means \"no `otelEndpoint` ⇒ local\n // JSONL mode\" (matches the docstring).\n const otelEndpoint = options.otelEndpoint ?? undefined;\n const mode: PlatformLoggerMode = options.mode ?? (otelEndpoint ? 'cloud' : 'local');\n\n const baseBindings: Record<string, unknown> = { run_id: options.runId };\n if (options.installationId !== undefined)\n baseBindings['installation_id'] = options.installationId;\n if (options.agentId !== undefined) baseBindings['agent_id'] = options.agentId;\n\n const destination: Destination =\n mode === 'cloud'\n ? new OtlpHttpDestination({\n endpoint: otelEndpoint ?? '',\n resourceAttributes: options.resourceAttributes ?? {},\n httpTimeoutMs: options.httpTimeoutMs ?? DEFAULT_HTTP_TIMEOUT_MS,\n flushBatchSize: options.flushBatchSize ?? DEFAULT_BATCH_SIZE,\n flushIntervalMs: options.flushIntervalMs ?? DEFAULT_INTERVAL_MS,\n ...(options.fetchImpl !== undefined ? { fetchImpl: options.fetchImpl } : {}),\n })\n : new JsonlFileDestination({\n runId: options.runId,\n runsDir: options.runsDir ?? defaultRunsDir(),\n ...(options.appendFileImpl !== undefined\n ? { appendFileImpl: options.appendFileImpl }\n : {}),\n ...(options.mkdirImpl !== undefined ? { mkdirImpl: options.mkdirImpl } : {}),\n });\n\n const now = options.now ?? Date.now;\n return buildLogger({ destination, baseBindings, mode, now });\n}\n\ninterface LoggerBuildOptions {\n destination: Destination;\n baseBindings: Record<string, unknown>;\n mode: PlatformLoggerMode;\n now: () => number;\n}\n\nfunction buildLogger(opts: LoggerBuildOptions): PlatformLogger {\n const writeAt = (level: LogLevelName, msgOrObj: unknown, msg?: string): void => {\n const time = opts.now();\n const levelNumber = LOG_LEVELS[level];\n const record: LogRecord = {\n level: levelNumber,\n time,\n msg: '',\n run_id: String(opts.baseBindings['run_id'] ?? ''),\n ...opts.baseBindings,\n };\n if (typeof msgOrObj === 'string') {\n record.msg = msgOrObj;\n } else if (msgOrObj && typeof msgOrObj === 'object') {\n Object.assign(record, msgOrObj);\n if (typeof msg === 'string') record.msg = msg;\n else if (typeof record.msg !== 'string') record.msg = '';\n }\n // Ambient invocation correlation: when used inside an invoke (the request\n // handler wraps `capability.run` in an AsyncLocalStorage context), stamp\n // `trace_id` / `run_id` from that context unless the caller already set them\n // explicitly via bindings or per-call meta. Outside an invoke there is no\n // context, so the records keep their previous shape.\n const ctx = getInvocationContext();\n if (ctx) {\n if (record.trace_id === undefined) record.trace_id = ctx.invocationId;\n if (!record.run_id) record.run_id = ctx.runId;\n if (record['handler'] === undefined && ctx.handler !== undefined) {\n record['handler'] = ctx.handler;\n }\n }\n opts.destination.write(record);\n };\n\n const child = (bindings: Record<string, unknown>): PlatformLogger =>\n buildLogger({ ...opts, baseBindings: { ...opts.baseBindings, ...bindings } });\n\n return {\n mode: opts.mode,\n trace: (msgOrObj, msg) => writeAt('trace', msgOrObj, msg),\n debug: (msgOrObj, msg) => writeAt('debug', msgOrObj, msg),\n info: (msgOrObj, msg) => writeAt('info', msgOrObj, msg),\n warn: (msgOrObj, msg) => writeAt('warn', msgOrObj, msg),\n error: (msgOrObj, msg) => writeAt('error', msgOrObj, msg),\n fatal: (msgOrObj, msg) => writeAt('fatal', msgOrObj, msg),\n child,\n flush: () => opts.destination.flush(),\n close: () => opts.destination.close(),\n };\n}\n\ninterface JsonlFileDestinationOptions {\n runId: string;\n runsDir: string;\n appendFileImpl?: (path: string, data: string) => Promise<void>;\n mkdirImpl?: (path: string) => Promise<void>;\n}\n\nclass JsonlFileDestination implements Destination {\n private readonly path: string;\n private readonly appendFile: (path: string, data: string) => Promise<void>;\n private readonly mkdir: (path: string) => Promise<void>;\n private inFlight: Promise<void> = Promise.resolve();\n private dirReady = false;\n\n constructor(opts: JsonlFileDestinationOptions) {\n this.path = resolve(opts.runsDir, `${opts.runId}.jsonl`);\n this.appendFile = opts.appendFileImpl ?? ((p, d) => appendFile(p, d, 'utf8'));\n this.mkdir =\n opts.mkdirImpl ??\n (async (p) => {\n await mkdir(p, { recursive: true });\n });\n }\n\n write(record: LogRecord): void {\n const line = `${JSON.stringify(record)}\\n`;\n this.inFlight = this.inFlight.then(async () => {\n if (!this.dirReady) {\n await this.mkdir(dirname(this.path));\n this.dirReady = true;\n }\n try {\n await this.appendFile(this.path, line);\n } catch (error) {\n process.stderr.write(\n `[stackbone/sdk] PlatformLogger JSONL write failed: ${error instanceof Error ? error.message : String(error)}\\n`,\n );\n }\n });\n }\n\n async flush(): Promise<void> {\n await this.inFlight;\n }\n\n async close(): Promise<void> {\n await this.flush();\n }\n}\n\ninterface OtlpHttpDestinationOptions {\n endpoint: string;\n resourceAttributes: Record<string, string>;\n httpTimeoutMs: number;\n flushBatchSize: number;\n flushIntervalMs: number;\n fetchImpl?: typeof fetch;\n}\n\n// OTLP/HTTP/JSON spec: OpenTelemetry Logs Data Model §B.1. Failures log to\n// stderr — telemetry must never block agent execution.\nclass OtlpHttpDestination implements Destination {\n private readonly url: string;\n private readonly resourceAttributes: Record<string, string>;\n private readonly httpTimeoutMs: number;\n private readonly flushBatchSize: number;\n private readonly flushIntervalMs: number;\n private readonly fetchImpl: typeof fetch;\n private buffer: LogRecord[] = [];\n private timer: NodeJS.Timeout | null = null;\n private inFlight: Promise<void> = Promise.resolve();\n private closed = false;\n\n constructor(opts: OtlpHttpDestinationOptions) {\n this.url = `${opts.endpoint.replace(/\\/+$/, '')}/v1/logs`;\n this.resourceAttributes = opts.resourceAttributes;\n this.httpTimeoutMs = opts.httpTimeoutMs;\n this.flushBatchSize = opts.flushBatchSize;\n this.flushIntervalMs = opts.flushIntervalMs;\n this.fetchImpl = opts.fetchImpl ?? fetch;\n }\n\n write(record: LogRecord): void {\n if (this.closed) return;\n this.buffer.push(record);\n if (this.buffer.length >= this.flushBatchSize) {\n void this.flush();\n } else {\n this.armTimer();\n }\n }\n\n async flush(): Promise<void> {\n await this.inFlight;\n if (this.buffer.length === 0) return;\n const drained = this.buffer.splice(0, this.buffer.length);\n this.disarmTimer();\n this.inFlight = this.post(drained).catch((error) => {\n process.stderr.write(\n `[stackbone/sdk] PlatformLogger OTLP POST failed: ${error instanceof Error ? error.message : String(error)}\\n`,\n );\n });\n await this.inFlight;\n }\n\n async close(): Promise<void> {\n this.closed = true;\n await this.flush();\n }\n\n private armTimer(): void {\n if (this.timer) return;\n this.timer = setTimeout(() => {\n this.timer = null;\n void this.flush();\n }, this.flushIntervalMs);\n this.timer.unref?.();\n }\n\n private disarmTimer(): void {\n if (this.timer) {\n clearTimeout(this.timer);\n this.timer = null;\n }\n }\n\n private async post(records: LogRecord[]): Promise<void> {\n const body = JSON.stringify(buildOtlpLogsBody(records, this.resourceAttributes));\n const controller = new AbortController();\n const timeout = setTimeout(() => controller.abort(), this.httpTimeoutMs);\n try {\n const resp = await this.fetchImpl(this.url, {\n method: 'POST',\n headers: { 'content-type': 'application/json' },\n body,\n signal: controller.signal,\n });\n if (!resp.ok) {\n const text = await resp.text().catch(() => '');\n throw new Error(`HTTP ${resp.status}${text ? `: ${text.slice(0, 200)}` : ''}`);\n }\n } finally {\n clearTimeout(timeout);\n }\n }\n}\n\ninterface OtlpKeyValue {\n key: string;\n value:\n | { stringValue: string }\n | { intValue: string }\n | { doubleValue: number }\n | { boolValue: boolean };\n}\n\ninterface OtlpResource {\n attributes: OtlpKeyValue[];\n}\n\ninterface OtlpLogRecord {\n timeUnixNano: string;\n severityNumber: number;\n severityText: string;\n body: { stringValue: string };\n attributes: OtlpKeyValue[];\n}\n\ninterface OtlpLogsBody {\n resourceLogs: Array<{\n resource: OtlpResource;\n scopeLogs: Array<{\n scope: { name: string; version: string };\n logRecords: OtlpLogRecord[];\n }>;\n }>;\n}\n\nconst SDK_SCOPE = { name: '@stackbone/sdk', version: SDK_VERSION };\n\nfunction buildOtlpLogsBody(\n records: LogRecord[],\n resourceAttributes: Record<string, string>,\n): OtlpLogsBody {\n return {\n resourceLogs: [\n {\n resource: { attributes: toOtlpAttributes(resourceAttributes) },\n scopeLogs: [\n {\n scope: SDK_SCOPE,\n logRecords: records.map(toOtlpLogRecord),\n },\n ],\n },\n ],\n };\n}\n\nfunction toOtlpLogRecord(record: LogRecord): OtlpLogRecord {\n const { level, time, msg, ...rest } = record;\n return {\n timeUnixNano: `${time * 1_000_000}`,\n severityNumber: level,\n severityText: severityText(level),\n body: { stringValue: msg },\n attributes: toOtlpAttributesFromUnknown(rest),\n };\n}\n\nconst SEVERITY_TEXT_BY_LEVEL: Record<number, string> = Object.fromEntries(\n Object.entries(LOG_LEVELS).map(([name, value]) => [value, name.toUpperCase()]),\n);\n\nfunction severityText(level: number): string {\n return SEVERITY_TEXT_BY_LEVEL[level] ?? 'INFO';\n}\n\nfunction toOtlpAttributes(attrs: Record<string, string>): OtlpKeyValue[] {\n return Object.entries(attrs).map(([key, value]) => ({\n key,\n value: { stringValue: value },\n }));\n}\n\nfunction toOtlpAttributesFromUnknown(attrs: Record<string, unknown>): OtlpKeyValue[] {\n const out: OtlpKeyValue[] = [];\n for (const [key, value] of Object.entries(attrs)) {\n if (value === null || value === undefined) continue;\n if (typeof value === 'string') {\n out.push({ key, value: { stringValue: value } });\n } else if (typeof value === 'number') {\n if (Number.isInteger(value)) out.push({ key, value: { intValue: String(value) } });\n else out.push({ key, value: { doubleValue: value } });\n } else if (typeof value === 'boolean') {\n out.push({ key, value: { boolValue: value } });\n } else {\n out.push({ key, value: { stringValue: JSON.stringify(value) } });\n }\n }\n return out;\n}\n\nexport function defaultRunsDir(): string {\n return resolve(homedir(), '.stackbone', 'dev', 'runs');\n}\n"]}
|
package/observability/index.js
CHANGED
|
@@ -7,7 +7,7 @@ var __defProp = Object.defineProperty;
|
|
|
7
7
|
var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
|
|
8
8
|
|
|
9
9
|
// package.json
|
|
10
|
-
var version = "0.1.0
|
|
10
|
+
var version = "0.1.0";
|
|
11
11
|
var storage = new AsyncLocalStorage();
|
|
12
12
|
function getInvocationContext() {
|
|
13
13
|
return storage.getStore();
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../libs/sdk/package.json","../../../../libs/sdk/src/runtime/invocation-context.ts","../../../../libs/sdk/src/observability/logger.ts"],"names":["storage","AsyncLocalStorage","getInvocationContext","getStore","LOG_LEVELS","trace","debug","info","warn","error","fatal","DEFAULT_BATCH_SIZE","DEFAULT_INTERVAL_MS","DEFAULT_HTTP_TIMEOUT_MS","createPlatformLogger","options","otelEndpoint","undefined","mode","baseBindings","run_id","runId","installationId","agentId","destination","OtlpHttpDestination","endpoint","resourceAttributes","httpTimeoutMs","flushBatchSize","flushIntervalMs","fetchImpl","JsonlFileDestination","runsDir","defaultRunsDir","appendFileImpl","mkdirImpl","now","Date","buildLogger","opts","writeAt","level","msgOrObj","msg","time","levelNumber","record","String","Object","assign","ctx","trace_id","invocationId","handler","write","child","bindings","flush","close","path","appendFile","mkdir","inFlight","Promise","resolve","dirReady","p","d","recursive","line","JSON","stringify","then","dirname","process","stderr","Error","message","url","buffer","timer","closed","replace","fetch","push","length","armTimer","drained","splice","disarmTimer","post","catch","setTimeout","unref","clearTimeout","records","body","buildOtlpLogsBody","controller","AbortController","timeout","abort","resp","method","headers","signal","ok","text","status","slice","SDK_SCOPE","name","version","resourceLogs","resource","attributes","toOtlpAttributes","scopeLogs","scope","logRecords","map","toOtlpLogRecord","rest","timeUnixNano","severityNumber","severityText","stringValue","toOtlpAttributesFromUnknown","SEVERITY_TEXT_BY_LEVEL","fromEntries","entries","value","toUpperCase","attrs","key","out","Number","isInteger","intValue","doubleValue","boolValue","homedir"],"mappings":";;;;;;;;;AAEE,IAAA,OAAA,GAAW,eAAA;ACiDb,IAAMA,OAAAA,GAAU,IAAIC,iBAAAA,EAAAA;AAeb,SAASC,oBAAAA,GAAAA;AACd,EAAA,OAAOF,QAAQG,QAAAA,EAAQ;AACzB;AAFgBD,MAAAA,CAAAA,oBAAAA,EAAAA,sBAAAA,CAAAA;;;ACzDT,IAAME,UAAAA,GAAa;EACxBC,KAAAA,EAAO,EAAA;EACPC,KAAAA,EAAO,EAAA;EACPC,IAAAA,EAAM,EAAA;EACNC,IAAAA,EAAM,EAAA;EACNC,KAAAA,EAAO,EAAA;EACPC,KAAAA,EAAO;AACT;AA6EA,IAAMC,kBAAAA,GAAqB,EAAA;AAC3B,IAAMC,mBAAAA,GAAsB,GAAA;AAC5B,IAAMC,uBAAAA,GAA0B,GAAA;AAOzB,SAASC,qBAAqBC,OAAAA,EAA8B;AAMjE,EAAA,MAAMC,YAAAA,GAAeD,QAAQC,YAAAA,IAAgBC,MAAAA;AAC7C,EAAA,MAAMC,IAAAA,GAA2BH,OAAAA,CAAQG,IAAAA,KAASF,YAAAA,GAAe,OAAA,GAAU,OAAA,CAAA;AAE3E,EAAA,MAAMG,YAAAA,GAAwC;AAAEC,IAAAA,MAAAA,EAAQL,OAAAA,CAAQM;AAAM,GAAA;AACtE,EAAA,IAAIN,QAAQO,cAAAA,KAAmBL,MAAAA,EAC7BE,YAAAA,CAAa,iBAAA,IAAqBJ,OAAAA,CAAQO,cAAAA;AAC5C,EAAA,IAAIP,QAAQQ,OAAAA,KAAYN,MAAAA,EAAWE,YAAAA,CAA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AA","file":"index.js","sourcesContent":["{\n \"name\": \"@stackbone/sdk\",\n \"version\": \"0.1.0-alpha.8\",\n \"license\": \"UNLICENSED\",\n \"description\": \"Official TypeScript SDK for Stackbone — the marketplace and managed runtime for containerized AI agents.\",\n \"type\": \"module\",\n \"sideEffects\": false,\n \"main\": \"./dist/index.cjs\",\n \"module\": \"./dist/index.js\",\n \"types\": \"./dist/index.d.ts\",\n \"exports\": {\n \".\": {\n \"import\": {\n \"types\": \"./dist/index.d.ts\",\n \"default\": \"./dist/index.js\"\n },\n \"require\": {\n \"types\": \"./dist/index.d.cts\",\n \"default\": \"./dist/index.cjs\"\n }\n },\n \"./db\": {\n \"import\": {\n \"types\": \"./dist/db/index.d.ts\",\n \"default\": \"./dist/db/index.js\"\n },\n \"require\": {\n \"types\": \"./dist/db/index.d.cts\",\n \"default\": \"./dist/db/index.cjs\"\n }\n },\n \"./workflow\": {\n \"import\": {\n \"types\": \"./dist/workflow.d.ts\",\n \"default\": \"./dist/workflow.js\"\n },\n \"require\": {\n \"types\": \"./dist/workflow.d.cts\",\n \"default\": \"./dist/workflow.cjs\"\n }\n },\n \"./connect\": {\n \"import\": {\n \"types\": \"./dist/connect.d.ts\",\n \"default\": \"./dist/connect.js\"\n },\n \"require\": {\n \"types\": \"./dist/connect.d.cts\",\n \"default\": \"./dist/connect.cjs\"\n }\n },\n \"./eve\": {\n \"import\": {\n \"types\": \"./dist/eve.d.ts\",\n \"default\": \"./dist/eve.js\"\n },\n \"require\": {\n \"types\": \"./dist/eve.d.cts\",\n \"default\": \"./dist/eve.cjs\"\n }\n },\n \"./db/testing\": {\n \"import\": {\n \"types\": \"./dist/db/testing/index.d.ts\",\n \"default\": \"./dist/db/testing/index.js\"\n },\n \"require\": {\n \"types\": \"./dist/db/testing/index.d.cts\",\n \"default\": \"./dist/db/testing/index.cjs\"\n }\n },\n \"./observability\": {\n \"import\": {\n \"types\": \"./dist/observability/index.d.ts\",\n \"default\": \"./dist/observability/index.js\"\n },\n \"require\": {\n \"types\": \"./dist/observability/index.d.cts\",\n \"default\": \"./dist/observability/index.cjs\"\n }\n },\n \"./queues/types\": {\n \"import\": {\n \"types\": \"./dist/queues/types.d.ts\",\n \"default\": \"./dist/queues/types.js\"\n },\n \"require\": {\n \"types\": \"./dist/queues/types.d.cts\",\n \"default\": \"./dist/queues/types.cjs\"\n }\n },\n \"./rag/schema\": {\n \"import\": {\n \"types\": \"./dist/rag/schema.d.ts\",\n \"default\": \"./dist/rag/schema.js\"\n },\n \"require\": {\n \"types\": \"./dist/rag/schema.d.cts\",\n \"default\": \"./dist/rag/schema.cjs\"\n }\n },\n \"./package.json\": \"./package.json\"\n },\n \"files\": [\n \"dist\",\n \"README.md\",\n \"CHANGELOG.md\"\n ],\n \"publishConfig\": {\n \"access\": \"public\"\n },\n \"engines\": {\n \"node\": \">=24\"\n },\n \"repository\": {\n \"type\": \"git\",\n \"url\": \"git+https://github.com/stackbone/stackbone.git\",\n \"directory\": \"libs/sdk\"\n },\n \"homepage\": \"https://stackbone.ai\",\n \"bugs\": {\n \"url\": \"https://github.com/stackbone/stackbone/issues\"\n },\n \"keywords\": [\n \"stackbone\",\n \"ai-agents\",\n \"agent-sdk\",\n \"containerized-agents\",\n \"openrouter\",\n \"rag\",\n \"pgvector\",\n \"drizzle\",\n \"openai\",\n \"postgres\"\n ],\n \"peerDependencies\": {\n \"@ai-sdk/openai-compatible\": \"*\",\n \"eve\": \"*\",\n \"workflow\": \"*\"\n },\n \"peerDependenciesMeta\": {\n \"@ai-sdk/openai-compatible\": {\n \"optional\": true\n },\n \"eve\": {\n \"optional\": true\n },\n \"workflow\": {\n \"optional\": true\n }\n },\n \"dependencies\": {\n \"@aws-sdk/client-s3\": \"^3.1038.0\",\n \"@aws-sdk/s3-request-presigner\": \"^3.1038.0\",\n \"@stackbone/crypto\": \"workspace:*\",\n \"@stackbone/prompt-compiler\": \"workspace:*\",\n \"@stackbone/rag-core\": \"workspace:*\",\n \"@stackbone/s3-client\": \"workspace:*\",\n \"@stackbone/validators\": \"workspace:*\",\n \"@testcontainers/postgresql\": \"^11.14.0\",\n \"drizzle-orm\": \"0.45.2\",\n \"openai\": \"^6.42.0\",\n \"postgres\": \"3.4.9\",\n \"unpdf\": \"^0.12.1\",\n \"zod\": \"^4.3.6\"\n }\n}\n","// Process-wide invocation context, propagated with `AsyncLocalStorage`.\n//\n// The runtime request handler wraps each `capability.run(...)` in this context\n// (see `@stackbone/agent-server`'s `request-handler`), so any code running\n// inside an invoke — the creator's handler, the SDK's own loggers, a stray\n// `console.log` — can recover the active `invocationId` / `runId` without the\n// handler having to thread them through every call.\n//\n// Why an ALS and not a plain module variable: the agent process serves invokes\n// concurrently (the node:http adapter does not serialise requests). A single\n// mutable \"current invocation\" would be clobbered the moment two invokes\n// overlap. `AsyncLocalStorage` keeps a separate store per async call tree, so\n// each invoke's logs stay correlated to the right run even under concurrency.\n//\n// `invocationId` is the value the canonical logs call `trace_id` (the control\n// plane mints it once per invoke and threads it through the envelope); `runId`\n// is the run the invoke belongs to.\n\nimport { AsyncLocalStorage } from 'node:async_hooks';\n\nexport interface InvocationContext {\n /** The envelope's `invocationId` — surfaced on log lines as `trace_id`. */\n readonly invocationId: string;\n /** The run this invoke belongs to — surfaced on log lines as `run_id`. */\n readonly runId: string;\n /**\n * The handler this invoke routed to — `invoke` for a direct entry or the\n * named job handler (e.g. `demo-log-job`) the dispatcher delivered to.\n * Surfaced on log lines as `handler` so the Studio logs trail can tell which\n * entrypoint emitted each line. Optional so a caller that binds a context\n * without routing info (older tests, lifecycle hooks) still type-checks.\n */\n readonly handler?: string;\n /**\n * The projected `run_steps.id` of the workflow step currently executing, when\n * the runtime can attribute the active async tree to one step. The\n * workflow-HITL helper reads it so an approval row can be anchored to the\n * exact step that requested it (`approvals.requested_by_step_id`, A6).\n *\n * GAP (2026-06-20): no caller populates this yet. The emulator binds the\n * invocation context once per WHOLE flow dispatch (see the runtime-mount\n * `flowPost` wrap), not per step, and the Workflow World runs as a FLAT tree\n * whose events carry `writer: null` / `executionContext: null`, so the\n * per-step World id is not visible at the point a `\"use step\"` runs. The seam\n * is threaded end-to-end (context → ambient approval client → INSERT) so the\n * column is stamped the moment a step id becomes available, without another\n * surface change. Until then it stays `undefined` and the column stays NULL.\n */\n readonly requestedByStepId?: string;\n}\n\nconst storage = new AsyncLocalStorage<InvocationContext>();\n\n/**\n * Runs `fn` with `context` bound as the active invocation. The context stays\n * available to every synchronous and asynchronous continuation rooted in this\n * call (i.e. across `await`s inside `fn`). Returns whatever `fn` returns.\n */\nexport function runWithInvocationContext<T>(context: InvocationContext, fn: () => T): T {\n return storage.run(context, fn);\n}\n\n/**\n * Returns the active invocation context, or `undefined` when called outside any\n * invoke (process boot, lifecycle events, tests that don't set one up).\n */\nexport function getInvocationContext(): InvocationContext | undefined {\n return storage.getStore();\n}\n\n/**\n * Ergonomic wrapper for callers that already hold a single correlation id and\n * want to bind it as the active run/trace for `fn` — the durable workflow step\n * call-site is the first such caller (F5): it knows the projected `run_id` and\n * the World run id, and wraps a step's execution so the step's logs and SDK\n * operations correlate to its run.\n *\n * It does NOT generate ids — that stays a caller concern, exactly like\n * `runWithInvocationContext`. `runId` and `invocationId` default to the single\n * `id` you pass, so `runWithCallerId(runId, fn)` binds a context where the run\n * and trace share that id; pass distinct values (e.g. the World run id as the\n * trace) via the options form.\n */\nexport function runWithCallerId<T>(\n id: string,\n fn: () => T,\n options?: { readonly invocationId?: string; readonly handler?: string },\n): T {\n const context: InvocationContext = {\n runId: id,\n invocationId: options?.invocationId ?? id,\n // Only attach `handler` when supplied: `exactOptionalPropertyTypes` forbids\n // an explicit `undefined` on an optional property.\n ...(options?.handler !== undefined ? { handler: options.handler } : {}),\n };\n return runWithInvocationContext(context, fn);\n}\n","import { appendFile, mkdir } from 'node:fs/promises';\nimport { homedir } from 'node:os';\nimport { dirname, resolve } from 'node:path';\n\nimport { version as SDK_VERSION } from '../../package.json';\nimport { getInvocationContext } from '../runtime/invocation-context';\n\n// Numeric levels match Pino so JSONL files produced in local mode work with\n// `pino-pretty` and other Pino-aware tooling without translation.\nexport const LOG_LEVELS = {\n trace: 10,\n debug: 20,\n info: 30,\n warn: 40,\n error: 50,\n fatal: 60,\n} as const;\n\nexport type LogLevelName = keyof typeof LOG_LEVELS;\nexport type LogLevelNumber = (typeof LOG_LEVELS)[LogLevelName];\n\nexport interface LogRecord {\n /** Pino-style numeric level. */\n level: LogLevelNumber;\n /** Epoch milliseconds. Pino uses `time` as a number. */\n time: number;\n msg: string;\n run_id: string;\n trace_id?: string;\n installation_id?: string;\n agent_id?: string;\n [key: string]: unknown;\n}\n\nexport interface PlatformLoggerOptions {\n runId: string;\n installationId?: string | undefined;\n agentId?: string | undefined;\n /**\n * When set (cloud), logs are batched and POSTed to `<endpoint>/v1/logs` as\n * OTLP/HTTP/JSON. When unset (local), logs are appended to\n * `<runsDir>/<runId>.jsonl`. Falls back to `OTEL_EXPORTER_OTLP_ENDPOINT`.\n */\n otelEndpoint?: string | undefined;\n /** Local-only: directory where JSONL files live. Defaults to `~/.stackbone/dev/runs`. */\n runsDir?: string | undefined;\n /** Cloud-only: extra OTel resource attributes to send with every batch. */\n resourceAttributes?: Record<string, string> | undefined;\n /** Cloud-only: HTTP timeout per OTLP POST in ms. Defaults to 5_000. */\n httpTimeoutMs?: number | undefined;\n /** Flush trigger by buffer size. Defaults to 50. */\n flushBatchSize?: number | undefined;\n /** Flush trigger by elapsed time (ms). Defaults to 1_000. */\n flushIntervalMs?: number | undefined;\n /** Test seam — fetch implementation. Defaults to global `fetch`. */\n fetchImpl?: typeof fetch | undefined;\n /** Test seam — `fs.appendFile`-shaped sink the local destination uses. */\n appendFileImpl?: ((path: string, data: string) => Promise<void>) | undefined;\n /** Test seam — `fs.mkdir`-shaped helper the local destination uses. */\n mkdirImpl?: ((path: string) => Promise<void>) | undefined;\n /** Test seam — clock for `time` field. Defaults to `Date.now`. */\n now?: (() => number) | undefined;\n /** Override mode resolution (skips the env detection). */\n mode?: PlatformLoggerMode | undefined;\n}\n\nexport type PlatformLoggerMode = 'local' | 'cloud';\n\nexport interface PinoLike {\n trace(msgOrObj: unknown, msg?: string): void;\n debug(msgOrObj: unknown, msg?: string): void;\n info(msgOrObj: unknown, msg?: string): void;\n warn(msgOrObj: unknown, msg?: string): void;\n error(msgOrObj: unknown, msg?: string): void;\n fatal(msgOrObj: unknown, msg?: string): void;\n}\n\nexport interface PlatformLogger extends PinoLike {\n readonly mode: PlatformLoggerMode;\n /** Bind extra fields and return a child logger sharing the same destination. */\n child(bindings: Record<string, unknown>): PlatformLogger;\n /** Force-flush pending writes (close file handle or POST OTLP batch). */\n flush(): Promise<void>;\n /** Stop accepting writes and release resources. */\n close(): Promise<void>;\n}\n\ninterface Destination {\n write(record: LogRecord): void;\n flush(): Promise<void>;\n close(): Promise<void>;\n}\n\nconst DEFAULT_BATCH_SIZE = 50;\nconst DEFAULT_INTERVAL_MS = 1_000;\nconst DEFAULT_HTTP_TIMEOUT_MS = 5_000;\n\n/**\n * Creates a Pino-aligned logger that writes JSONL to disk in local mode and\n * batches OTLP/HTTP/JSON log records to an OTel collector in cloud mode. Mode\n * is resolved from `OTEL_EXPORTER_OTLP_ENDPOINT` or the explicit override.\n */\nexport function createPlatformLogger(options: PlatformLoggerOptions): PlatformLogger {\n // The resolver is the single seam that reads `OTEL_EXPORTER_OTLP_ENDPOINT`.\n // Runtime code building a logger on the `@stackbone/sdk/observability`\n // subpath supplies `otelEndpoint` explicitly (typically plumbed from\n // `ResolvedConfig`). The `undefined` here means \"no `otelEndpoint` ⇒ local\n // JSONL mode\" (matches the docstring).\n const otelEndpoint = options.otelEndpoint ?? undefined;\n const mode: PlatformLoggerMode = options.mode ?? (otelEndpoint ? 'cloud' : 'local');\n\n const baseBindings: Record<string, unknown> = { run_id: options.runId };\n if (options.installationId !== undefined)\n baseBindings['installation_id'] = options.installationId;\n if (options.agentId !== undefined) baseBindings['agent_id'] = options.agentId;\n\n const destination: Destination =\n mode === 'cloud'\n ? new OtlpHttpDestination({\n endpoint: otelEndpoint ?? '',\n resourceAttributes: options.resourceAttributes ?? {},\n httpTimeoutMs: options.httpTimeoutMs ?? DEFAULT_HTTP_TIMEOUT_MS,\n flushBatchSize: options.flushBatchSize ?? DEFAULT_BATCH_SIZE,\n flushIntervalMs: options.flushIntervalMs ?? DEFAULT_INTERVAL_MS,\n ...(options.fetchImpl !== undefined ? { fetchImpl: options.fetchImpl } : {}),\n })\n : new JsonlFileDestination({\n runId: options.runId,\n runsDir: options.runsDir ?? defaultRunsDir(),\n ...(options.appendFileImpl !== undefined\n ? { appendFileImpl: options.appendFileImpl }\n : {}),\n ...(options.mkdirImpl !== undefined ? { mkdirImpl: options.mkdirImpl } : {}),\n });\n\n const now = options.now ?? Date.now;\n return buildLogger({ destination, baseBindings, mode, now });\n}\n\ninterface LoggerBuildOptions {\n destination: Destination;\n baseBindings: Record<string, unknown>;\n mode: PlatformLoggerMode;\n now: () => number;\n}\n\nfunction buildLogger(opts: LoggerBuildOptions): PlatformLogger {\n const writeAt = (level: LogLevelName, msgOrObj: unknown, msg?: string): void => {\n const time = opts.now();\n const levelNumber = LOG_LEVELS[level];\n const record: LogRecord = {\n level: levelNumber,\n time,\n msg: '',\n run_id: String(opts.baseBindings['run_id'] ?? ''),\n ...opts.baseBindings,\n };\n if (typeof msgOrObj === 'string') {\n record.msg = msgOrObj;\n } else if (msgOrObj && typeof msgOrObj === 'object') {\n Object.assign(record, msgOrObj);\n if (typeof msg === 'string') record.msg = msg;\n else if (typeof record.msg !== 'string') record.msg = '';\n }\n // Ambient invocation correlation: when used inside an invoke (the request\n // handler wraps `capability.run` in an AsyncLocalStorage context), stamp\n // `trace_id` / `run_id` from that context unless the caller already set them\n // explicitly via bindings or per-call meta. Outside an invoke there is no\n // context, so the records keep their previous shape.\n const ctx = getInvocationContext();\n if (ctx) {\n if (record.trace_id === undefined) record.trace_id = ctx.invocationId;\n if (!record.run_id) record.run_id = ctx.runId;\n if (record['handler'] === undefined && ctx.handler !== undefined) {\n record['handler'] = ctx.handler;\n }\n }\n opts.destination.write(record);\n };\n\n const child = (bindings: Record<string, unknown>): PlatformLogger =>\n buildLogger({ ...opts, baseBindings: { ...opts.baseBindings, ...bindings } });\n\n return {\n mode: opts.mode,\n trace: (msgOrObj, msg) => writeAt('trace', msgOrObj, msg),\n debug: (msgOrObj, msg) => writeAt('debug', msgOrObj, msg),\n info: (msgOrObj, msg) => writeAt('info', msgOrObj, msg),\n warn: (msgOrObj, msg) => writeAt('warn', msgOrObj, msg),\n error: (msgOrObj, msg) => writeAt('error', msgOrObj, msg),\n fatal: (msgOrObj, msg) => writeAt('fatal', msgOrObj, msg),\n child,\n flush: () => opts.destination.flush(),\n close: () => opts.destination.close(),\n };\n}\n\ninterface JsonlFileDestinationOptions {\n runId: string;\n runsDir: string;\n appendFileImpl?: (path: string, data: string) => Promise<void>;\n mkdirImpl?: (path: string) => Promise<void>;\n}\n\nclass JsonlFileDestination implements Destination {\n private readonly path: string;\n private readonly appendFile: (path: string, data: string) => Promise<void>;\n private readonly mkdir: (path: string) => Promise<void>;\n private inFlight: Promise<void> = Promise.resolve();\n private dirReady = false;\n\n constructor(opts: JsonlFileDestinationOptions) {\n this.path = resolve(opts.runsDir, `${opts.runId}.jsonl`);\n this.appendFile = opts.appendFileImpl ?? ((p, d) => appendFile(p, d, 'utf8'));\n this.mkdir =\n opts.mkdirImpl ??\n (async (p) => {\n await mkdir(p, { recursive: true });\n });\n }\n\n write(record: LogRecord): void {\n const line = `${JSON.stringify(record)}\\n`;\n this.inFlight = this.inFlight.then(async () => {\n if (!this.dirReady) {\n await this.mkdir(dirname(this.path));\n this.dirReady = true;\n }\n try {\n await this.appendFile(this.path, line);\n } catch (error) {\n process.stderr.write(\n `[stackbone/sdk] PlatformLogger JSONL write failed: ${error instanceof Error ? error.message : String(error)}\\n`,\n );\n }\n });\n }\n\n async flush(): Promise<void> {\n await this.inFlight;\n }\n\n async close(): Promise<void> {\n await this.flush();\n }\n}\n\ninterface OtlpHttpDestinationOptions {\n endpoint: string;\n resourceAttributes: Record<string, string>;\n httpTimeoutMs: number;\n flushBatchSize: number;\n flushIntervalMs: number;\n fetchImpl?: typeof fetch;\n}\n\n// OTLP/HTTP/JSON spec: OpenTelemetry Logs Data Model §B.1. Failures log to\n// stderr — telemetry must never block agent execution.\nclass OtlpHttpDestination implements Destination {\n private readonly url: string;\n private readonly resourceAttributes: Record<string, string>;\n private readonly httpTimeoutMs: number;\n private readonly flushBatchSize: number;\n private readonly flushIntervalMs: number;\n private readonly fetchImpl: typeof fetch;\n private buffer: LogRecord[] = [];\n private timer: NodeJS.Timeout | null = null;\n private inFlight: Promise<void> = Promise.resolve();\n private closed = false;\n\n constructor(opts: OtlpHttpDestinationOptions) {\n this.url = `${opts.endpoint.replace(/\\/+$/, '')}/v1/logs`;\n this.resourceAttributes = opts.resourceAttributes;\n this.httpTimeoutMs = opts.httpTimeoutMs;\n this.flushBatchSize = opts.flushBatchSize;\n this.flushIntervalMs = opts.flushIntervalMs;\n this.fetchImpl = opts.fetchImpl ?? fetch;\n }\n\n write(record: LogRecord): void {\n if (this.closed) return;\n this.buffer.push(record);\n if (this.buffer.length >= this.flushBatchSize) {\n void this.flush();\n } else {\n this.armTimer();\n }\n }\n\n async flush(): Promise<void> {\n await this.inFlight;\n if (this.buffer.length === 0) return;\n const drained = this.buffer.splice(0, this.buffer.length);\n this.disarmTimer();\n this.inFlight = this.post(drained).catch((error) => {\n process.stderr.write(\n `[stackbone/sdk] PlatformLogger OTLP POST failed: ${error instanceof Error ? error.message : String(error)}\\n`,\n );\n });\n await this.inFlight;\n }\n\n async close(): Promise<void> {\n this.closed = true;\n await this.flush();\n }\n\n private armTimer(): void {\n if (this.timer) return;\n this.timer = setTimeout(() => {\n this.timer = null;\n void this.flush();\n }, this.flushIntervalMs);\n this.timer.unref?.();\n }\n\n private disarmTimer(): void {\n if (this.timer) {\n clearTimeout(this.timer);\n this.timer = null;\n }\n }\n\n private async post(records: LogRecord[]): Promise<void> {\n const body = JSON.stringify(buildOtlpLogsBody(records, this.resourceAttributes));\n const controller = new AbortController();\n const timeout = setTimeout(() => controller.abort(), this.httpTimeoutMs);\n try {\n const resp = await this.fetchImpl(this.url, {\n method: 'POST',\n headers: { 'content-type': 'application/json' },\n body,\n signal: controller.signal,\n });\n if (!resp.ok) {\n const text = await resp.text().catch(() => '');\n throw new Error(`HTTP ${resp.status}${text ? `: ${text.slice(0, 200)}` : ''}`);\n }\n } finally {\n clearTimeout(timeout);\n }\n }\n}\n\ninterface OtlpKeyValue {\n key: string;\n value:\n | { stringValue: string }\n | { intValue: string }\n | { doubleValue: number }\n | { boolValue: boolean };\n}\n\ninterface OtlpResource {\n attributes: OtlpKeyValue[];\n}\n\ninterface OtlpLogRecord {\n timeUnixNano: string;\n severityNumber: number;\n severityText: string;\n body: { stringValue: string };\n attributes: OtlpKeyValue[];\n}\n\ninterface OtlpLogsBody {\n resourceLogs: Array<{\n resource: OtlpResource;\n scopeLogs: Array<{\n scope: { name: string; version: string };\n logRecords: OtlpLogRecord[];\n }>;\n }>;\n}\n\nconst SDK_SCOPE = { name: '@stackbone/sdk', version: SDK_VERSION };\n\nfunction buildOtlpLogsBody(\n records: LogRecord[],\n resourceAttributes: Record<string, string>,\n): OtlpLogsBody {\n return {\n resourceLogs: [\n {\n resource: { attributes: toOtlpAttributes(resourceAttributes) },\n scopeLogs: [\n {\n scope: SDK_SCOPE,\n logRecords: records.map(toOtlpLogRecord),\n },\n ],\n },\n ],\n };\n}\n\nfunction toOtlpLogRecord(record: LogRecord): OtlpLogRecord {\n const { level, time, msg, ...rest } = record;\n return {\n timeUnixNano: `${time * 1_000_000}`,\n severityNumber: level,\n severityText: severityText(level),\n body: { stringValue: msg },\n attributes: toOtlpAttributesFromUnknown(rest),\n };\n}\n\nconst SEVERITY_TEXT_BY_LEVEL: Record<number, string> = Object.fromEntries(\n Object.entries(LOG_LEVELS).map(([name, value]) => [value, name.toUpperCase()]),\n);\n\nfunction severityText(level: number): string {\n return SEVERITY_TEXT_BY_LEVEL[level] ?? 'INFO';\n}\n\nfunction toOtlpAttributes(attrs: Record<string, string>): OtlpKeyValue[] {\n return Object.entries(attrs).map(([key, value]) => ({\n key,\n value: { stringValue: value },\n }));\n}\n\nfunction toOtlpAttributesFromUnknown(attrs: Record<string, unknown>): OtlpKeyValue[] {\n const out: OtlpKeyValue[] = [];\n for (const [key, value] of Object.entries(attrs)) {\n if (value === null || value === undefined) continue;\n if (typeof value === 'string') {\n out.push({ key, value: { stringValue: value } });\n } else if (typeof value === 'number') {\n if (Number.isInteger(value)) out.push({ key, value: { intValue: String(value) } });\n else out.push({ key, value: { doubleValue: value } });\n } else if (typeof value === 'boolean') {\n out.push({ key, value: { boolValue: value } });\n } else {\n out.push({ key, value: { stringValue: JSON.stringify(value) } });\n }\n }\n return out;\n}\n\nexport function defaultRunsDir(): string {\n return resolve(homedir(), '.stackbone', 'dev', 'runs');\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../../../../libs/sdk/package.json","../../../../libs/sdk/src/runtime/invocation-context.ts","../../../../libs/sdk/src/observability/logger.ts"],"names":["storage","AsyncLocalStorage","getInvocationContext","getStore","LOG_LEVELS","trace","debug","info","warn","error","fatal","DEFAULT_BATCH_SIZE","DEFAULT_INTERVAL_MS","DEFAULT_HTTP_TIMEOUT_MS","createPlatformLogger","options","otelEndpoint","undefined","mode","baseBindings","run_id","runId","installationId","agentId","destination","OtlpHttpDestination","endpoint","resourceAttributes","httpTimeoutMs","flushBatchSize","flushIntervalMs","fetchImpl","JsonlFileDestination","runsDir","defaultRunsDir","appendFileImpl","mkdirImpl","now","Date","buildLogger","opts","writeAt","level","msgOrObj","msg","time","levelNumber","record","String","Object","assign","ctx","trace_id","invocationId","handler","write","child","bindings","flush","close","path","appendFile","mkdir","inFlight","Promise","resolve","dirReady","p","d","recursive","line","JSON","stringify","then","dirname","process","stderr","Error","message","url","buffer","timer","closed","replace","fetch","push","length","armTimer","drained","splice","disarmTimer","post","catch","setTimeout","unref","clearTimeout","records","body","buildOtlpLogsBody","controller","AbortController","timeout","abort","resp","method","headers","signal","ok","text","status","slice","SDK_SCOPE","name","version","resourceLogs","resource","attributes","toOtlpAttributes","scopeLogs","scope","logRecords","map","toOtlpLogRecord","rest","timeUnixNano","severityNumber","severityText","stringValue","toOtlpAttributesFromUnknown","SEVERITY_TEXT_BY_LEVEL","fromEntries","entries","value","toUpperCase","attrs","key","out","Number","isInteger","intValue","doubleValue","boolValue","homedir"],"mappings":";;;;;;;;;AAEE,IAAA,OAAA,GAAW,OAAA;ACiDb,IAAMA,OAAAA,GAAU,IAAIC,iBAAAA,EAAAA;AAeb,SAASC,oBAAAA,GAAAA;AACd,EAAA,OAAOF,QAAQG,QAAAA,EAAQ;AACzB;AAFgBD,MAAAA,CAAAA,oBAAAA,EAAAA,sBAAAA,CAAAA;;;ACzDT,IAAME,UAAAA,GAAa;EACxBC,KAAAA,EAAO,EAAA;EACPC,KAAAA,EAAO,EAAA;EACPC,IAAAA,EAAM,EAAA;EACNC,IAAAA,EAAM,EAAA;EACNC,KAAAA,EAAO,EAAA;EACPC,KAAAA,EAAO;AACT;AA6EA,IAAMC,kBAAAA,GAAqB,EAAA;AAC3B,IAAMC,mBAAAA,GAAsB,GAAA;AAC5B,IAAMC,uBAAAA,GAA0B,GAAA;AAOzB,SAASC,qBAAqBC,OAAAA,EAA8B;AAMjE,EAAA,MAAMC,YAAAA,GAAeD,QAAQC,YAAAA,IAAgBC,MAAAA;AAC7C,EAAA,MAAMC,IAAAA,GAA2BH,OAAAA,CAAQG,IAAAA,KAASF,YAAAA,GAAe,OAAA,GAAU,OAAA,CAAA;AAE3E,EAAA,MAAMG,YAAAA,GAAwC;AAAEC,IAAAA,MAAAA,EAAQL,OAAAA,CAAQM;AAAM,GAAA;AACtE,EAAA,IAAIN,QAAQO,cAAAA,KAAmBL,MAAAA,EAC7BE,YAAAA,CAAa,iBAAA,IAAqBJ,OAAAA,CAAQO,cAAAA;AAC5C,EAAA,IAAIP,QAAQQ,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AAAA,CAAAA,cAAAA,EAAAA,gBAAAA,CAAAA","file":"index.js","sourcesContent":["{\n \"name\": \"@stackbone/sdk\",\n \"version\": \"0.1.0\",\n \"license\": \"UNLICENSED\",\n \"description\": \"Official TypeScript SDK for Stackbone — the marketplace and managed runtime for containerized AI agents.\",\n \"type\": \"module\",\n \"sideEffects\": false,\n \"main\": \"./dist/index.cjs\",\n \"module\": \"./dist/index.js\",\n \"types\": \"./dist/index.d.ts\",\n \"exports\": {\n \".\": {\n \"import\": {\n \"types\": \"./dist/index.d.ts\",\n \"default\": \"./dist/index.js\"\n },\n \"require\": {\n \"types\": \"./dist/index.d.cts\",\n \"default\": \"./dist/index.cjs\"\n }\n },\n \"./db\": {\n \"import\": {\n \"types\": \"./dist/db/index.d.ts\",\n \"default\": \"./dist/db/index.js\"\n },\n \"require\": {\n \"types\": \"./dist/db/index.d.cts\",\n \"default\": \"./dist/db/index.cjs\"\n }\n },\n \"./workflow\": {\n \"import\": {\n \"types\": \"./dist/workflow.d.ts\",\n \"default\": \"./dist/workflow.js\"\n },\n \"require\": {\n \"types\": \"./dist/workflow.d.cts\",\n \"default\": \"./dist/workflow.cjs\"\n }\n },\n \"./connect\": {\n \"import\": {\n \"types\": \"./dist/connect.d.ts\",\n \"default\": \"./dist/connect.js\"\n },\n \"require\": {\n \"types\": \"./dist/connect.d.cts\",\n \"default\": \"./dist/connect.cjs\"\n }\n },\n \"./eve\": {\n \"import\": {\n \"types\": \"./dist/eve.d.ts\",\n \"default\": \"./dist/eve.js\"\n },\n \"require\": {\n \"types\": \"./dist/eve.d.cts\",\n \"default\": \"./dist/eve.cjs\"\n }\n },\n \"./db/testing\": {\n \"import\": {\n \"types\": \"./dist/db/testing/index.d.ts\",\n \"default\": \"./dist/db/testing/index.js\"\n },\n \"require\": {\n \"types\": \"./dist/db/testing/index.d.cts\",\n \"default\": \"./dist/db/testing/index.cjs\"\n }\n },\n \"./observability\": {\n \"import\": {\n \"types\": \"./dist/observability/index.d.ts\",\n \"default\": \"./dist/observability/index.js\"\n },\n \"require\": {\n \"types\": \"./dist/observability/index.d.cts\",\n \"default\": \"./dist/observability/index.cjs\"\n }\n },\n \"./queues/types\": {\n \"import\": {\n \"types\": \"./dist/queues/types.d.ts\",\n \"default\": \"./dist/queues/types.js\"\n },\n \"require\": {\n \"types\": \"./dist/queues/types.d.cts\",\n \"default\": \"./dist/queues/types.cjs\"\n }\n },\n \"./rag/schema\": {\n \"import\": {\n \"types\": \"./dist/rag/schema.d.ts\",\n \"default\": \"./dist/rag/schema.js\"\n },\n \"require\": {\n \"types\": \"./dist/rag/schema.d.cts\",\n \"default\": \"./dist/rag/schema.cjs\"\n }\n },\n \"./package.json\": \"./package.json\"\n },\n \"files\": [\n \"dist\",\n \"README.md\",\n \"CHANGELOG.md\"\n ],\n \"publishConfig\": {\n \"access\": \"public\"\n },\n \"engines\": {\n \"node\": \">=24\"\n },\n \"repository\": {\n \"type\": \"git\",\n \"url\": \"git+https://github.com/stackbone/stackbone.git\",\n \"directory\": \"libs/sdk\"\n },\n \"homepage\": \"https://stackbone.ai\",\n \"bugs\": {\n \"url\": \"https://github.com/stackbone/stackbone/issues\"\n },\n \"keywords\": [\n \"stackbone\",\n \"ai-agents\",\n \"agent-sdk\",\n \"containerized-agents\",\n \"openrouter\",\n \"rag\",\n \"pgvector\",\n \"drizzle\",\n \"openai\",\n \"postgres\"\n ],\n \"peerDependencies\": {\n \"@ai-sdk/openai-compatible\": \"*\",\n \"eve\": \"*\",\n \"workflow\": \"*\"\n },\n \"peerDependenciesMeta\": {\n \"@ai-sdk/openai-compatible\": {\n \"optional\": true\n },\n \"eve\": {\n \"optional\": true\n },\n \"workflow\": {\n \"optional\": true\n }\n },\n \"dependencies\": {\n \"@aws-sdk/client-s3\": \"^3.1038.0\",\n \"@aws-sdk/s3-request-presigner\": \"^3.1038.0\",\n \"@stackbone/crypto\": \"workspace:*\",\n \"@stackbone/prompt-compiler\": \"workspace:*\",\n \"@stackbone/rag-core\": \"workspace:*\",\n \"@stackbone/s3-client\": \"workspace:*\",\n \"@stackbone/validators\": \"workspace:*\",\n \"@testcontainers/postgresql\": \"^11.14.0\",\n \"drizzle-orm\": \"0.45.2\",\n \"openai\": \"^6.42.0\",\n \"postgres\": \"3.4.9\",\n \"unpdf\": \"^0.12.1\",\n \"zod\": \"^4.3.6\"\n }\n}\n","// Process-wide invocation context, propagated with `AsyncLocalStorage`.\n//\n// The runtime request handler wraps each `capability.run(...)` in this context\n// (see `@stackbone/agent-server`'s `request-handler`), so any code running\n// inside an invoke — the creator's handler, the SDK's own loggers, a stray\n// `console.log` — can recover the active `invocationId` / `runId` without the\n// handler having to thread them through every call.\n//\n// Why an ALS and not a plain module variable: the agent process serves invokes\n// concurrently (the node:http adapter does not serialise requests). A single\n// mutable \"current invocation\" would be clobbered the moment two invokes\n// overlap. `AsyncLocalStorage` keeps a separate store per async call tree, so\n// each invoke's logs stay correlated to the right run even under concurrency.\n//\n// `invocationId` is the value the canonical logs call `trace_id` (the control\n// plane mints it once per invoke and threads it through the envelope); `runId`\n// is the run the invoke belongs to.\n\nimport { AsyncLocalStorage } from 'node:async_hooks';\n\nexport interface InvocationContext {\n /** The envelope's `invocationId` — surfaced on log lines as `trace_id`. */\n readonly invocationId: string;\n /** The run this invoke belongs to — surfaced on log lines as `run_id`. */\n readonly runId: string;\n /**\n * The handler this invoke routed to — `invoke` for a direct entry or the\n * named job handler (e.g. `demo-log-job`) the dispatcher delivered to.\n * Surfaced on log lines as `handler` so the Studio logs trail can tell which\n * entrypoint emitted each line. Optional so a caller that binds a context\n * without routing info (older tests, lifecycle hooks) still type-checks.\n */\n readonly handler?: string;\n /**\n * The projected `run_steps.id` of the workflow step currently executing, when\n * the runtime can attribute the active async tree to one step. The\n * workflow-HITL helper reads it so an approval row can be anchored to the\n * exact step that requested it (`approvals.requested_by_step_id`, A6).\n *\n * GAP (2026-06-20): no caller populates this yet. The emulator binds the\n * invocation context once per WHOLE flow dispatch (see the runtime-mount\n * `flowPost` wrap), not per step, and the Workflow World runs as a FLAT tree\n * whose events carry `writer: null` / `executionContext: null`, so the\n * per-step World id is not visible at the point a `\"use step\"` runs. The seam\n * is threaded end-to-end (context → ambient approval client → INSERT) so the\n * column is stamped the moment a step id becomes available, without another\n * surface change. Until then it stays `undefined` and the column stays NULL.\n */\n readonly requestedByStepId?: string;\n}\n\nconst storage = new AsyncLocalStorage<InvocationContext>();\n\n/**\n * Runs `fn` with `context` bound as the active invocation. The context stays\n * available to every synchronous and asynchronous continuation rooted in this\n * call (i.e. across `await`s inside `fn`). Returns whatever `fn` returns.\n */\nexport function runWithInvocationContext<T>(context: InvocationContext, fn: () => T): T {\n return storage.run(context, fn);\n}\n\n/**\n * Returns the active invocation context, or `undefined` when called outside any\n * invoke (process boot, lifecycle events, tests that don't set one up).\n */\nexport function getInvocationContext(): InvocationContext | undefined {\n return storage.getStore();\n}\n\n/**\n * Ergonomic wrapper for callers that already hold a single correlation id and\n * want to bind it as the active run/trace for `fn` — the durable workflow step\n * call-site is the first such caller (F5): it knows the projected `run_id` and\n * the World run id, and wraps a step's execution so the step's logs and SDK\n * operations correlate to its run.\n *\n * It does NOT generate ids — that stays a caller concern, exactly like\n * `runWithInvocationContext`. `runId` and `invocationId` default to the single\n * `id` you pass, so `runWithCallerId(runId, fn)` binds a context where the run\n * and trace share that id; pass distinct values (e.g. the World run id as the\n * trace) via the options form.\n */\nexport function runWithCallerId<T>(\n id: string,\n fn: () => T,\n options?: { readonly invocationId?: string; readonly handler?: string },\n): T {\n const context: InvocationContext = {\n runId: id,\n invocationId: options?.invocationId ?? id,\n // Only attach `handler` when supplied: `exactOptionalPropertyTypes` forbids\n // an explicit `undefined` on an optional property.\n ...(options?.handler !== undefined ? { handler: options.handler } : {}),\n };\n return runWithInvocationContext(context, fn);\n}\n","import { appendFile, mkdir } from 'node:fs/promises';\nimport { homedir } from 'node:os';\nimport { dirname, resolve } from 'node:path';\n\nimport { version as SDK_VERSION } from '../../package.json';\nimport { getInvocationContext } from '../runtime/invocation-context';\n\n// Numeric levels match Pino so JSONL files produced in local mode work with\n// `pino-pretty` and other Pino-aware tooling without translation.\nexport const LOG_LEVELS = {\n trace: 10,\n debug: 20,\n info: 30,\n warn: 40,\n error: 50,\n fatal: 60,\n} as const;\n\nexport type LogLevelName = keyof typeof LOG_LEVELS;\nexport type LogLevelNumber = (typeof LOG_LEVELS)[LogLevelName];\n\nexport interface LogRecord {\n /** Pino-style numeric level. */\n level: LogLevelNumber;\n /** Epoch milliseconds. Pino uses `time` as a number. */\n time: number;\n msg: string;\n run_id: string;\n trace_id?: string;\n installation_id?: string;\n agent_id?: string;\n [key: string]: unknown;\n}\n\nexport interface PlatformLoggerOptions {\n runId: string;\n installationId?: string | undefined;\n agentId?: string | undefined;\n /**\n * When set (cloud), logs are batched and POSTed to `<endpoint>/v1/logs` as\n * OTLP/HTTP/JSON. When unset (local), logs are appended to\n * `<runsDir>/<runId>.jsonl`. Falls back to `OTEL_EXPORTER_OTLP_ENDPOINT`.\n */\n otelEndpoint?: string | undefined;\n /** Local-only: directory where JSONL files live. Defaults to `~/.stackbone/dev/runs`. */\n runsDir?: string | undefined;\n /** Cloud-only: extra OTel resource attributes to send with every batch. */\n resourceAttributes?: Record<string, string> | undefined;\n /** Cloud-only: HTTP timeout per OTLP POST in ms. Defaults to 5_000. */\n httpTimeoutMs?: number | undefined;\n /** Flush trigger by buffer size. Defaults to 50. */\n flushBatchSize?: number | undefined;\n /** Flush trigger by elapsed time (ms). Defaults to 1_000. */\n flushIntervalMs?: number | undefined;\n /** Test seam — fetch implementation. Defaults to global `fetch`. */\n fetchImpl?: typeof fetch | undefined;\n /** Test seam — `fs.appendFile`-shaped sink the local destination uses. */\n appendFileImpl?: ((path: string, data: string) => Promise<void>) | undefined;\n /** Test seam — `fs.mkdir`-shaped helper the local destination uses. */\n mkdirImpl?: ((path: string) => Promise<void>) | undefined;\n /** Test seam — clock for `time` field. Defaults to `Date.now`. */\n now?: (() => number) | undefined;\n /** Override mode resolution (skips the env detection). */\n mode?: PlatformLoggerMode | undefined;\n}\n\nexport type PlatformLoggerMode = 'local' | 'cloud';\n\nexport interface PinoLike {\n trace(msgOrObj: unknown, msg?: string): void;\n debug(msgOrObj: unknown, msg?: string): void;\n info(msgOrObj: unknown, msg?: string): void;\n warn(msgOrObj: unknown, msg?: string): void;\n error(msgOrObj: unknown, msg?: string): void;\n fatal(msgOrObj: unknown, msg?: string): void;\n}\n\nexport interface PlatformLogger extends PinoLike {\n readonly mode: PlatformLoggerMode;\n /** Bind extra fields and return a child logger sharing the same destination. */\n child(bindings: Record<string, unknown>): PlatformLogger;\n /** Force-flush pending writes (close file handle or POST OTLP batch). */\n flush(): Promise<void>;\n /** Stop accepting writes and release resources. */\n close(): Promise<void>;\n}\n\ninterface Destination {\n write(record: LogRecord): void;\n flush(): Promise<void>;\n close(): Promise<void>;\n}\n\nconst DEFAULT_BATCH_SIZE = 50;\nconst DEFAULT_INTERVAL_MS = 1_000;\nconst DEFAULT_HTTP_TIMEOUT_MS = 5_000;\n\n/**\n * Creates a Pino-aligned logger that writes JSONL to disk in local mode and\n * batches OTLP/HTTP/JSON log records to an OTel collector in cloud mode. Mode\n * is resolved from `OTEL_EXPORTER_OTLP_ENDPOINT` or the explicit override.\n */\nexport function createPlatformLogger(options: PlatformLoggerOptions): PlatformLogger {\n // The resolver is the single seam that reads `OTEL_EXPORTER_OTLP_ENDPOINT`.\n // Runtime code building a logger on the `@stackbone/sdk/observability`\n // subpath supplies `otelEndpoint` explicitly (typically plumbed from\n // `ResolvedConfig`). The `undefined` here means \"no `otelEndpoint` ⇒ local\n // JSONL mode\" (matches the docstring).\n const otelEndpoint = options.otelEndpoint ?? undefined;\n const mode: PlatformLoggerMode = options.mode ?? (otelEndpoint ? 'cloud' : 'local');\n\n const baseBindings: Record<string, unknown> = { run_id: options.runId };\n if (options.installationId !== undefined)\n baseBindings['installation_id'] = options.installationId;\n if (options.agentId !== undefined) baseBindings['agent_id'] = options.agentId;\n\n const destination: Destination =\n mode === 'cloud'\n ? new OtlpHttpDestination({\n endpoint: otelEndpoint ?? '',\n resourceAttributes: options.resourceAttributes ?? {},\n httpTimeoutMs: options.httpTimeoutMs ?? DEFAULT_HTTP_TIMEOUT_MS,\n flushBatchSize: options.flushBatchSize ?? DEFAULT_BATCH_SIZE,\n flushIntervalMs: options.flushIntervalMs ?? DEFAULT_INTERVAL_MS,\n ...(options.fetchImpl !== undefined ? { fetchImpl: options.fetchImpl } : {}),\n })\n : new JsonlFileDestination({\n runId: options.runId,\n runsDir: options.runsDir ?? defaultRunsDir(),\n ...(options.appendFileImpl !== undefined\n ? { appendFileImpl: options.appendFileImpl }\n : {}),\n ...(options.mkdirImpl !== undefined ? { mkdirImpl: options.mkdirImpl } : {}),\n });\n\n const now = options.now ?? Date.now;\n return buildLogger({ destination, baseBindings, mode, now });\n}\n\ninterface LoggerBuildOptions {\n destination: Destination;\n baseBindings: Record<string, unknown>;\n mode: PlatformLoggerMode;\n now: () => number;\n}\n\nfunction buildLogger(opts: LoggerBuildOptions): PlatformLogger {\n const writeAt = (level: LogLevelName, msgOrObj: unknown, msg?: string): void => {\n const time = opts.now();\n const levelNumber = LOG_LEVELS[level];\n const record: LogRecord = {\n level: levelNumber,\n time,\n msg: '',\n run_id: String(opts.baseBindings['run_id'] ?? ''),\n ...opts.baseBindings,\n };\n if (typeof msgOrObj === 'string') {\n record.msg = msgOrObj;\n } else if (msgOrObj && typeof msgOrObj === 'object') {\n Object.assign(record, msgOrObj);\n if (typeof msg === 'string') record.msg = msg;\n else if (typeof record.msg !== 'string') record.msg = '';\n }\n // Ambient invocation correlation: when used inside an invoke (the request\n // handler wraps `capability.run` in an AsyncLocalStorage context), stamp\n // `trace_id` / `run_id` from that context unless the caller already set them\n // explicitly via bindings or per-call meta. Outside an invoke there is no\n // context, so the records keep their previous shape.\n const ctx = getInvocationContext();\n if (ctx) {\n if (record.trace_id === undefined) record.trace_id = ctx.invocationId;\n if (!record.run_id) record.run_id = ctx.runId;\n if (record['handler'] === undefined && ctx.handler !== undefined) {\n record['handler'] = ctx.handler;\n }\n }\n opts.destination.write(record);\n };\n\n const child = (bindings: Record<string, unknown>): PlatformLogger =>\n buildLogger({ ...opts, baseBindings: { ...opts.baseBindings, ...bindings } });\n\n return {\n mode: opts.mode,\n trace: (msgOrObj, msg) => writeAt('trace', msgOrObj, msg),\n debug: (msgOrObj, msg) => writeAt('debug', msgOrObj, msg),\n info: (msgOrObj, msg) => writeAt('info', msgOrObj, msg),\n warn: (msgOrObj, msg) => writeAt('warn', msgOrObj, msg),\n error: (msgOrObj, msg) => writeAt('error', msgOrObj, msg),\n fatal: (msgOrObj, msg) => writeAt('fatal', msgOrObj, msg),\n child,\n flush: () => opts.destination.flush(),\n close: () => opts.destination.close(),\n };\n}\n\ninterface JsonlFileDestinationOptions {\n runId: string;\n runsDir: string;\n appendFileImpl?: (path: string, data: string) => Promise<void>;\n mkdirImpl?: (path: string) => Promise<void>;\n}\n\nclass JsonlFileDestination implements Destination {\n private readonly path: string;\n private readonly appendFile: (path: string, data: string) => Promise<void>;\n private readonly mkdir: (path: string) => Promise<void>;\n private inFlight: Promise<void> = Promise.resolve();\n private dirReady = false;\n\n constructor(opts: JsonlFileDestinationOptions) {\n this.path = resolve(opts.runsDir, `${opts.runId}.jsonl`);\n this.appendFile = opts.appendFileImpl ?? ((p, d) => appendFile(p, d, 'utf8'));\n this.mkdir =\n opts.mkdirImpl ??\n (async (p) => {\n await mkdir(p, { recursive: true });\n });\n }\n\n write(record: LogRecord): void {\n const line = `${JSON.stringify(record)}\\n`;\n this.inFlight = this.inFlight.then(async () => {\n if (!this.dirReady) {\n await this.mkdir(dirname(this.path));\n this.dirReady = true;\n }\n try {\n await this.appendFile(this.path, line);\n } catch (error) {\n process.stderr.write(\n `[stackbone/sdk] PlatformLogger JSONL write failed: ${error instanceof Error ? error.message : String(error)}\\n`,\n );\n }\n });\n }\n\n async flush(): Promise<void> {\n await this.inFlight;\n }\n\n async close(): Promise<void> {\n await this.flush();\n }\n}\n\ninterface OtlpHttpDestinationOptions {\n endpoint: string;\n resourceAttributes: Record<string, string>;\n httpTimeoutMs: number;\n flushBatchSize: number;\n flushIntervalMs: number;\n fetchImpl?: typeof fetch;\n}\n\n// OTLP/HTTP/JSON spec: OpenTelemetry Logs Data Model §B.1. Failures log to\n// stderr — telemetry must never block agent execution.\nclass OtlpHttpDestination implements Destination {\n private readonly url: string;\n private readonly resourceAttributes: Record<string, string>;\n private readonly httpTimeoutMs: number;\n private readonly flushBatchSize: number;\n private readonly flushIntervalMs: number;\n private readonly fetchImpl: typeof fetch;\n private buffer: LogRecord[] = [];\n private timer: NodeJS.Timeout | null = null;\n private inFlight: Promise<void> = Promise.resolve();\n private closed = false;\n\n constructor(opts: OtlpHttpDestinationOptions) {\n this.url = `${opts.endpoint.replace(/\\/+$/, '')}/v1/logs`;\n this.resourceAttributes = opts.resourceAttributes;\n this.httpTimeoutMs = opts.httpTimeoutMs;\n this.flushBatchSize = opts.flushBatchSize;\n this.flushIntervalMs = opts.flushIntervalMs;\n this.fetchImpl = opts.fetchImpl ?? fetch;\n }\n\n write(record: LogRecord): void {\n if (this.closed) return;\n this.buffer.push(record);\n if (this.buffer.length >= this.flushBatchSize) {\n void this.flush();\n } else {\n this.armTimer();\n }\n }\n\n async flush(): Promise<void> {\n await this.inFlight;\n if (this.buffer.length === 0) return;\n const drained = this.buffer.splice(0, this.buffer.length);\n this.disarmTimer();\n this.inFlight = this.post(drained).catch((error) => {\n process.stderr.write(\n `[stackbone/sdk] PlatformLogger OTLP POST failed: ${error instanceof Error ? error.message : String(error)}\\n`,\n );\n });\n await this.inFlight;\n }\n\n async close(): Promise<void> {\n this.closed = true;\n await this.flush();\n }\n\n private armTimer(): void {\n if (this.timer) return;\n this.timer = setTimeout(() => {\n this.timer = null;\n void this.flush();\n }, this.flushIntervalMs);\n this.timer.unref?.();\n }\n\n private disarmTimer(): void {\n if (this.timer) {\n clearTimeout(this.timer);\n this.timer = null;\n }\n }\n\n private async post(records: LogRecord[]): Promise<void> {\n const body = JSON.stringify(buildOtlpLogsBody(records, this.resourceAttributes));\n const controller = new AbortController();\n const timeout = setTimeout(() => controller.abort(), this.httpTimeoutMs);\n try {\n const resp = await this.fetchImpl(this.url, {\n method: 'POST',\n headers: { 'content-type': 'application/json' },\n body,\n signal: controller.signal,\n });\n if (!resp.ok) {\n const text = await resp.text().catch(() => '');\n throw new Error(`HTTP ${resp.status}${text ? `: ${text.slice(0, 200)}` : ''}`);\n }\n } finally {\n clearTimeout(timeout);\n }\n }\n}\n\ninterface OtlpKeyValue {\n key: string;\n value:\n | { stringValue: string }\n | { intValue: string }\n | { doubleValue: number }\n | { boolValue: boolean };\n}\n\ninterface OtlpResource {\n attributes: OtlpKeyValue[];\n}\n\ninterface OtlpLogRecord {\n timeUnixNano: string;\n severityNumber: number;\n severityText: string;\n body: { stringValue: string };\n attributes: OtlpKeyValue[];\n}\n\ninterface OtlpLogsBody {\n resourceLogs: Array<{\n resource: OtlpResource;\n scopeLogs: Array<{\n scope: { name: string; version: string };\n logRecords: OtlpLogRecord[];\n }>;\n }>;\n}\n\nconst SDK_SCOPE = { name: '@stackbone/sdk', version: SDK_VERSION };\n\nfunction buildOtlpLogsBody(\n records: LogRecord[],\n resourceAttributes: Record<string, string>,\n): OtlpLogsBody {\n return {\n resourceLogs: [\n {\n resource: { attributes: toOtlpAttributes(resourceAttributes) },\n scopeLogs: [\n {\n scope: SDK_SCOPE,\n logRecords: records.map(toOtlpLogRecord),\n },\n ],\n },\n ],\n };\n}\n\nfunction toOtlpLogRecord(record: LogRecord): OtlpLogRecord {\n const { level, time, msg, ...rest } = record;\n return {\n timeUnixNano: `${time * 1_000_000}`,\n severityNumber: level,\n severityText: severityText(level),\n body: { stringValue: msg },\n attributes: toOtlpAttributesFromUnknown(rest),\n };\n}\n\nconst SEVERITY_TEXT_BY_LEVEL: Record<number, string> = Object.fromEntries(\n Object.entries(LOG_LEVELS).map(([name, value]) => [value, name.toUpperCase()]),\n);\n\nfunction severityText(level: number): string {\n return SEVERITY_TEXT_BY_LEVEL[level] ?? 'INFO';\n}\n\nfunction toOtlpAttributes(attrs: Record<string, string>): OtlpKeyValue[] {\n return Object.entries(attrs).map(([key, value]) => ({\n key,\n value: { stringValue: value },\n }));\n}\n\nfunction toOtlpAttributesFromUnknown(attrs: Record<string, unknown>): OtlpKeyValue[] {\n const out: OtlpKeyValue[] = [];\n for (const [key, value] of Object.entries(attrs)) {\n if (value === null || value === undefined) continue;\n if (typeof value === 'string') {\n out.push({ key, value: { stringValue: value } });\n } else if (typeof value === 'number') {\n if (Number.isInteger(value)) out.push({ key, value: { intValue: String(value) } });\n else out.push({ key, value: { doubleValue: value } });\n } else if (typeof value === 'boolean') {\n out.push({ key, value: { boolValue: value } });\n } else {\n out.push({ key, value: { stringValue: JSON.stringify(value) } });\n }\n }\n return out;\n}\n\nexport function defaultRunsDir(): string {\n return resolve(homedir(), '.stackbone', 'dev', 'runs');\n}\n"]}
|
package/package.json
CHANGED
|
Binary file
|
|
Binary file
|