@jini-ai/agent-runtime 0.6.12 → 0.6.15-rc.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (41) hide show
  1. package/CHANGELOG.md +33 -0
  2. package/dist/agent-protocol/acp/json.d.ts +1 -1
  3. package/dist/agent-protocol/acp/json.js +6 -3
  4. package/dist/agent-protocol/acp/models.js +53 -15
  5. package/dist/agent-protocol/acp/rpc.js +1 -1
  6. package/dist/agent-protocol/acp/session.d.ts +1 -1
  7. package/dist/agent-protocol/acp/session.js +25 -8
  8. package/dist/agent-protocol/acp/text-suppression.js +2 -1
  9. package/dist/ai-trace/capture.d.ts +17 -0
  10. package/dist/ai-trace/capture.js +43 -0
  11. package/dist/ai-trace/classify.d.ts +12 -0
  12. package/dist/ai-trace/classify.js +13 -0
  13. package/dist/ai-trace/index.d.ts +13 -0
  14. package/dist/ai-trace/index.js +6 -0
  15. package/dist/ai-trace/recorder.d.ts +65 -0
  16. package/dist/ai-trace/recorder.js +259 -0
  17. package/dist/ai-trace/sinks.d.ts +51 -0
  18. package/dist/ai-trace/sinks.js +137 -0
  19. package/dist/ai-trace/types.d.ts +123 -0
  20. package/dist/ai-trace/types.js +17 -0
  21. package/dist/ai-trace/usage.d.ts +13 -0
  22. package/dist/ai-trace/usage.js +43 -0
  23. package/dist/claude-filesystem-policy.d.ts +25 -3
  24. package/dist/claude-filesystem-policy.js +104 -14
  25. package/dist/core/model-discovery-shared.d.ts +28 -0
  26. package/dist/core/model-discovery-shared.js +88 -0
  27. package/dist/defs/antigravity.js +10 -2
  28. package/dist/defs/claude.js +2 -1
  29. package/dist/defs/codex.js +13 -2
  30. package/dist/index.d.ts +1 -0
  31. package/dist/index.js +1 -0
  32. package/dist/model-discovery-adapters.js +1 -1
  33. package/dist/model-discovery-shared.d.ts +2 -27
  34. package/dist/model-discovery-shared.js +2 -87
  35. package/dist/model-discovery.d.ts +1 -1
  36. package/dist/model-discovery.js +2 -2
  37. package/dist/models.js +1 -1
  38. package/dist/providers/anthropic-messages.d.ts +1 -1
  39. package/dist/providers/anthropic-messages.js +10 -4
  40. package/dist/types.d.ts +4 -0
  41. package/package.json +16 -10
package/CHANGELOG.md CHANGED
@@ -1,3 +1,36 @@
1
+ ## 0.6.13
2
+
3
+ ### Patch Changes
4
+
5
+ - aef0152: Folder-limited Claude runs get a private per-run CLAUDE_CODE_TMPDIR (a 0700 /tmp/jini-\* directory, removed on exit, crash, cancellation or startup failure). The sandbox grants only that run's scratch subtree; the shared per-user /tmp/claude-<uid> grant is gone, and overlong bases are refused instead of falling back to shared scratch.
6
+ - 0728914: Engine guard clean-up (`pnpm guard` 106 -> 0): layer, subpath-isolation and module-state findings fixed by moving
7
+ shared contracts to their owners instead of reaching across domains. Additive public API: `@jini-ai/core/filesystem`
8
+ (guarded-reader contracts), `useFetchQueryScope` from `@jini-ai/ui` fetch-query (per-provider query scope),
9
+ `@jini-ai/chat/react` re-exports of the accepted-input, run-state and agent-plugin chat-state helpers. The Claude
10
+ filesystem probe cache in `@jini-ai/agent-runtime` is instance-owned. No behaviour change intended; host-facing
11
+ breaks are listed in `owner-store-to-server` and `guard-host-ports`.
12
+ - cbce255: Apply AI-trace capture policy to errors, contain tracing and sink failures, preserve canonical
13
+ usage and stop reasons, accumulate request usage snapshots, scope tool identities per request,
14
+ and finalize traces from committed terminal events including inactivity watchdog completion.
15
+ Provider/session trace mappers now receive object arguments.
16
+ A trace whose stream subscription is refused or rejects after `run_started` is now finished from
17
+ the run's real terminal state (`waitForTerminal`, in the background) instead of being dropped.
18
+ `RunLifecycle.waitForTerminal` takes an optional `{ signal }`: aborting it rejects with the reason and
19
+ unregisters the waiter. The traced lifecycle gains `dispose()`, which releases open traces without
20
+ finishing them and cancels those background waits; the server kernel's `close()` calls it after the
21
+ agent runtime stops, so a retained kernel keeps no recorder or waiter.
22
+ - e46b6ec: The Langfuse AI-trace sink moved out of `@jini-ai/agent-runtime` into the `ai-trace-langfuse` provider plugin (contract `ai_trace`), which bundles the `langfuse` SDK. Removed: the `@jini-ai/agent-runtime/ai-trace/langfuse` subpath (`createLangfuseAiTraceSink`, `loadLangfuseAiTraceSink`, `toLangfuseCall`). The runtime core has no Langfuse reference; a core-wide boundary test refuses vendor SDK imports or dependencies in any other package.
23
+ - 63bacc5: OpenTelemetry and Sentry observability adapters moved out of `@jini-ai/diagnostics` into the `observability-opentelemetry` and `observability-sentry` provider plugins of `@jini-ai/provider-plugins`. Removed: the `@jini-ai/diagnostics/observability/opentelemetry` and `/observability/sentry` subpaths and every `@opentelemetry/*` / `@sentry/node` dev and optional peer dependency. The OTel plugin accepts any OTLP/HTTP endpoint plus generic request headers. Packages bundled into plugin artifacts now ship their LICENSE file.
24
+ - Updated dependencies [7479159]
25
+ - Updated dependencies [c31264d]
26
+ - Updated dependencies [0728914]
27
+ - Updated dependencies [cbce255]
28
+ - Updated dependencies [6ecbdb2]
29
+ - Updated dependencies [63bacc5]
30
+ - @jini-ai/core@0.6.13
31
+ - @jini-ai/protocol@0.6.13
32
+ - @jini-ai/oauth@0.6.13
33
+
1
34
  ## 0.6.12
2
35
 
3
36
  ### Patch Changes
@@ -19,7 +19,7 @@ export declare const DEFAULT_ACP_TIMEOUT_ENV_VAR = "AGENT_RUNTIME_ACP_TIMEOUT_MS
19
19
  export declare function errorMessage(err: unknown): string;
20
20
  /**
21
21
  * Resolves the effective ACP timeout from an environment variable, falling
22
- * back to `fallbackMs` when the variable is absent or non-finite. Clamps the
22
+ * back to `fallbackMs` when the variable is absent, blank, or non-finite. Clamps the
23
23
  * result to `[0, MAX_TIMEOUT_MS]`.
24
24
  *
25
25
  * @param env - The process environment object to read the timeout var from.
@@ -15,7 +15,7 @@ export function errorMessage(err) {
15
15
  }
16
16
  /**
17
17
  * Resolves the effective ACP timeout from an environment variable, falling
18
- * back to `fallbackMs` when the variable is absent or non-finite. Clamps the
18
+ * back to `fallbackMs` when the variable is absent, blank, or non-finite. Clamps the
19
19
  * result to `[0, MAX_TIMEOUT_MS]`.
20
20
  *
21
21
  * @param env - The process environment object to read the timeout var from.
@@ -27,7 +27,10 @@ export function errorMessage(err) {
27
27
  * @returns The resolved timeout in milliseconds.
28
28
  */
29
29
  export function resolveAcpTimeoutMs(env, fallbackMs, envVarName = DEFAULT_ACP_TIMEOUT_ENV_VAR) {
30
- const raw = Number(env[envVarName]);
30
+ const value = env[envVarName];
31
+ if (!value?.trim())
32
+ return fallbackMs;
33
+ const raw = Number(value);
31
34
  if (!Number.isFinite(raw))
32
35
  return fallbackMs;
33
36
  return Math.min(MAX_TIMEOUT_MS, Math.max(0, Math.floor(raw)));
@@ -41,7 +44,7 @@ export function resolveAcpTimeoutMs(env, fallbackMs, envVarName = DEFAULT_ACP_TI
41
44
  * @returns The value cast as `UnknownRecord`, or `null` when the cast is unsafe.
42
45
  */
43
46
  export function asObject(value) {
44
- return value && typeof value === 'object' ? value : null;
47
+ return value && typeof value === 'object' && !Array.isArray(value) ? value : null;
45
48
  }
46
49
  /**
47
50
  * Returns a short diagnostic string describing the JSON kind of `value`:
@@ -214,6 +214,8 @@ export async function detectAcpModels(requiredArgs, optionalArgs = {}) {
214
214
  const { bin, args, cwd = process.cwd(), env = process.env, timeoutMs = DEFAULT_TIMEOUT_MS, clientName = 'agent-runtime-detect', clientVersion = 'runtime-adapter', defaultModelOption = { id: 'default', label: 'Default (CLI config)' }, signal, onSessionResult, spawnProcess = spawn, } = { ...optionalArgs, ...requiredArgs };
215
215
  const effectiveTimeoutMs = resolveAcpTimeoutMs(env, timeoutMs);
216
216
  return await new Promise((resolve, reject) => {
217
+ if (signal?.aborted)
218
+ throw new Error('ACP model detection aborted');
217
219
  const child = spawnProcess(bin, args, {
218
220
  cwd,
219
221
  stdio: ['pipe', 'pipe', 'pipe'],
@@ -234,23 +236,10 @@ export async function detectAcpModels(requiredArgs, optionalArgs = {}) {
234
236
  if (timer)
235
237
  clearTimeout(timer);
236
238
  signal?.removeEventListener('abort', abort);
237
- try {
238
- child.stdin.end();
239
- }
240
- catch { }
241
- if (!child.killed)
242
- child.kill('SIGTERM');
243
- const killTimer = setTimeout(() => { if (child.exitCode === null)
244
- child.kill('SIGKILL'); }, 250);
245
- killTimer.unref();
246
- // The process scheduler must retain its slot until exit, including the SIGKILL grace
247
- // period. Returning at metadata receipt would overlap this child with the next probe.
248
- if (closed) {
249
- clearTimeout(killTimer);
239
+ if (closed)
250
240
  fn(value);
251
- }
252
241
  else
253
- child.once('close', () => { clearTimeout(killTimer); fn(value); });
242
+ finishAcpProbeProcess({ child, complete: () => fn(value) });
254
243
  };
255
244
  const fail = (message) => {
256
245
  finish(reject, new Error(message));
@@ -335,6 +324,55 @@ export async function detectAcpModels(requiredArgs, optionalArgs = {}) {
335
324
  });
336
325
  });
337
326
  }
327
+ /**
328
+ * Ends a finished probe and completes after close, or after exit plus a pipe-drain grace.
329
+ * Descendants may inherit stdout, so waiting indefinitely for close can hold the scheduler slot.
330
+ * The process scheduler must retain its slot until exit, including the SIGKILL grace
331
+ * period. Returning at metadata receipt would overlap this child with the next probe.
332
+ * @param requiredArgs - The owned child and the callback that settles its probe result.
333
+ * @param _optionalArgs - Reserved optional controls.
334
+ * @returns Nothing; completes once and removes its timers and lifecycle listeners.
335
+ * @complexity O(1) time and space, excluding stream teardown.
336
+ */
337
+ function finishAcpProbeProcess({ child, complete }, _optionalArgs = {}) {
338
+ let completed = false;
339
+ let exitTimer = null;
340
+ const settle = () => {
341
+ if (completed)
342
+ return;
343
+ completed = true;
344
+ clearTimeout(killTimer);
345
+ if (exitTimer)
346
+ clearTimeout(exitTimer);
347
+ child.removeListener('exit', afterExit);
348
+ child.removeListener('close', settle);
349
+ complete();
350
+ };
351
+ const afterExit = () => {
352
+ clearTimeout(killTimer);
353
+ child.removeListener('exit', afterExit);
354
+ exitTimer = setTimeout(() => {
355
+ child.stdin.destroy();
356
+ child.stdout.destroy();
357
+ child.stderr.destroy();
358
+ settle();
359
+ }, 250);
360
+ exitTimer.unref();
361
+ };
362
+ const killTimer = setTimeout(() => { if (child.exitCode === null)
363
+ child.kill('SIGKILL'); }, 250);
364
+ killTimer.unref();
365
+ child.once('close', settle);
366
+ child.once('exit', afterExit);
367
+ if (child.exitCode !== null || child.signalCode)
368
+ afterExit();
369
+ try {
370
+ child.stdin.end();
371
+ }
372
+ catch { }
373
+ if (!child.killed)
374
+ child.kill('SIGTERM');
375
+ }
338
376
  /** Retains native current selection. Session creation can write CLI state/start services;
339
377
  * this metadata probe never sends session/prompt. The old array API remains compatible. */
340
378
  export async function detectAcpModelMetadata(requiredArgs, optionalArgs = {}) {
@@ -44,7 +44,7 @@ export function rpcErrorMessage(raw) {
44
44
  if (!obj || !error) {
45
45
  return '';
46
46
  }
47
- const message = typeof error.message === 'string'
47
+ const message = typeof error.message === 'string' && error.message.trim()
48
48
  ? error.message
49
49
  : typeof error.code === 'number'
50
50
  ? String(error.code)
@@ -206,7 +206,7 @@ export declare function isPlainIncrementalDelta(args: {
206
206
  hasOpenArtifactCandidate: boolean;
207
207
  }): boolean;
208
208
  /** Runs a tool-call-stripped delta through the DSML artifact suppressor, emits whatever should stay visible, and arms/disarms the "saw incremental prose" and suppressor-cleared state. */
209
- export declare function applyDsmlArtifactSuppression({ state, effects, suppressor, toolCallStrippedDelta, delta, isCumulativeSnapshot, }: {
209
+ export declare function applyDsmlArtifactSuppression({ state, effects, suppressor, toolCallStrippedDelta, isCumulativeSnapshot, }: {
210
210
  state: AcpSessionState;
211
211
  effects: AcpSessionEffects;
212
212
  suppressor: ArtifactTextSuppressor;
@@ -183,13 +183,13 @@ export function isPlainIncrementalDelta(args) {
183
183
  !hasOpenArtifactCandidate);
184
184
  }
185
185
  /** Runs a tool-call-stripped delta through the DSML artifact suppressor, emits whatever should stay visible, and arms/disarms the "saw incremental prose" and suppressor-cleared state. */
186
- export function applyDsmlArtifactSuppression({ state, effects, suppressor, toolCallStrippedDelta, delta, isCumulativeSnapshot, }) {
186
+ export function applyDsmlArtifactSuppression({ state, effects, suppressor, toolCallStrippedDelta, isCumulativeSnapshot, }) {
187
187
  const wasSuppressingArtifact = suppressor.isSuppressing();
188
188
  const hadPendingArtifactCandidate = suppressor.hasPendingCandidate();
189
189
  const strippedDelta = suppressor.strip(toolCallStrippedDelta);
190
190
  effects.noteArtifactTextSuppression(wasSuppressingArtifact || strippedDelta !== toolCallStrippedDelta ? 'artifact_echo' : 'artifact_candidate');
191
191
  const hasOpenArtifactCandidate = suppressor.isSuppressing() || suppressor.hasPendingCandidate();
192
- const consumedArtifactText = wasSuppressingArtifact || strippedDelta !== delta;
192
+ const consumedArtifactText = wasSuppressingArtifact || strippedDelta !== toolCallStrippedDelta;
193
193
  const preserveIncrementalProse = shouldPreserveIncrementalProse({
194
194
  isCumulativeSnapshot,
195
195
  wasSuppressingArtifact,
@@ -226,7 +226,8 @@ export function handleMessageChunkUpdate({ state, effects, update, }) {
226
226
  const text = extractAcpUpdateText(update);
227
227
  if (!text)
228
228
  return;
229
- const isCumulativeSnapshot = text.startsWith(state.emittedTextBuffer);
229
+ const isCumulativeSnapshot = state.emittedTextBuffer.length > 0 &&
230
+ text.length > state.emittedTextBuffer.length && text.startsWith(state.emittedTextBuffer);
230
231
  const delta = isCumulativeSnapshot ? text.slice(state.emittedTextBuffer.length) : text;
231
232
  if (delta.length === 0)
232
233
  return;
@@ -383,7 +384,12 @@ export function handleInitializeAck({ state, effects }) {
383
384
  state.expectedId = state.nextId;
384
385
  if (effects.resumeSessionId) {
385
386
  // Resume the prior upstream session instead of creating a fresh one.
386
- effects.writeRpc(state.nextId, 'session/load', { sessionId: effects.resumeSessionId, cwd: effects.effectiveCwd }, 'session/load');
387
+ effects.writeRpc(state.nextId, 'session/load', {
388
+ ...buildAcpSessionNewParams({ cwd: effects.effectiveCwd }, effects.mcpServers
389
+ ? { mcpServers: effects.mcpServers, envFormat: effects.envFormat }
390
+ : { envFormat: effects.envFormat }),
391
+ sessionId: effects.resumeSessionId,
392
+ }, 'session/load');
387
393
  }
388
394
  else {
389
395
  effects.writeRpc(state.nextId, 'session/new', buildAcpSessionNewParams({ cwd: effects.effectiveCwd }, effects.mcpServers ? { mcpServers: effects.mcpServers, envFormat: effects.envFormat } : { envFormat: effects.envFormat }), 'session/new');
@@ -409,11 +415,19 @@ export function triggerSetModelIfNeeded({ state, effects, }) {
409
415
  state.nextId += 1;
410
416
  return true;
411
417
  }
418
+ /** Records handshake identity, retaining the requested handle on an ID-free load ack.
419
+ * Mutates only the two session handles; performs no I/O.
420
+ * @complexity O(1) time and space.
421
+ */
422
+ function recordSessionIdentity({ state, result }, { resumeSessionId = null } = {}) {
423
+ // ACP load responses need not repeat the handle supplied in the request.
424
+ state.sessionId = asOptionalString(result.sessionId) ?? resumeSessionId;
425
+ // The durable handle for resuming this session on the next turn.
426
+ state.durableSessionId = asOptionalString(result.openCodeSessionId) ?? resumeSessionId;
427
+ }
412
428
  /** Handles the `session/new` (or `session/load`) ack: records the session id, model config, and either triggers a model switch or sends the prompt. */
413
429
  export function handleSessionNewAck({ state, effects, result, rawLine, }) {
414
- state.sessionId = asOptionalString(result.sessionId);
415
- // The durable handle for resuming this session on the next turn.
416
- state.durableSessionId = asOptionalString(result.openCodeSessionId);
430
+ recordSessionIdentity({ state, result }, { resumeSessionId: effects.resumeSessionId });
417
431
  // session/new acknowledged with a session id = handshake done.
418
432
  if (state.sessionId)
419
433
  notifySessionInit(effects);
@@ -572,7 +586,7 @@ export function attachAcpSession(requiredArgs, optionalArgs = {}) {
572
586
  // run-level inactivity watchdog's escape hatch. Without this, a caller
573
587
  // passing a zero stage timeout would schedule a 0ms timeout that fires on
574
588
  // the next tick and kills the session immediately.
575
- if (stageWatchdogDisabled)
589
+ if (stageWatchdogDisabled || pendingPermissionRequests.size > 0)
576
590
  return;
577
591
  stageTimer = setTimeout(() => {
578
592
  fail(`ACP ${label} timed out after ${stageTimeoutMs}ms`);
@@ -915,6 +929,9 @@ export function attachAcpSession(requiredArgs, optionalArgs = {}) {
915
929
  return;
916
930
  }
917
931
  pendingPermissionRequests.set(requestId, () => logDecision());
932
+ // Human decision time is outside the agent's inactivity budget. All timer
933
+ // resets stay paused until the last pending permission response is sent.
934
+ clearStageTimer();
918
935
  try {
919
936
  if (!onPermissionRequest) {
920
937
  respond(defaultPermissionDecision({ optionRecords }, { permissionMode, cliParity: options.cliParity }));
@@ -21,7 +21,8 @@ const DSML_ARTIFACT_CLOSE_RE = /(?:<\/artifact>|<\/\s*\|?\s*DSML\s*>|<\s*\|?\s*\
21
21
  const DSML_OPEN_CANONICAL = 'dsmlartifact';
22
22
  const ARTIFACT_OPEN_CANONICAL = 'artifact';
23
23
  const ARTIFACT_CLOSE_CANONICALS = ['artifact', 'dsml'];
24
- const TOOL_CALL_OPEN_RE = /(?:<\s*tool_call\b[^>]*>|<\s*edit\s*>)/i;
24
+ // Require tag syntax so comparison prose such as `x < tool_call.count && y > 0` stays visible.
25
+ const TOOL_CALL_OPEN_RE = /(?:<tool_call(?=[\s/>])[^>&\r\n]*>|<edit[ \t]*>)/i;
25
26
  const TOOL_CALL_CLOSE_RE = /(?:<\/\s*tool_call\s*>|<\/\s*edit\s*>)/i;
26
27
  const TOOL_CALL_OPEN_CANONICALS = ['toolcall', 'edit'];
27
28
  const TOOL_CALL_CLOSE_CANONICALS = ['toolcall', 'edit'];
@@ -0,0 +1,17 @@
1
+ import type { AiCapturedText, AiContentCapture } from './types.js';
2
+ export declare const DEFAULT_MAX_CAPTURED_CHARS = 16000;
3
+ export interface CaptureTextOptions {
4
+ readonly mode?: AiContentCapture | undefined;
5
+ readonly maxChars?: number | undefined;
6
+ /** Host-known secrets (API keys in env, tokens) masked exactly before the lexical rules run. */
7
+ readonly exactSecrets?: ReadonlyArray<string | undefined | null> | undefined;
8
+ }
9
+ /** `off` → `null`; `metadata` → `{ chars }`; `full` → redacted (then truncated) text plus counts. */
10
+ export declare function captureText({ text }: {
11
+ text: string | null | undefined;
12
+ }, { mode, maxChars, exactSecrets }?: CaptureTextOptions): AiCapturedText | null;
13
+ /** Tool inputs arrive as objects; stringify once so capture/redaction sees the same text a backend would. */
14
+ export declare function stringifyForCapture({ value }: {
15
+ value: unknown;
16
+ }): string | null;
17
+ //# sourceMappingURL=capture.d.ts.map
@@ -0,0 +1,43 @@
1
+ /**
2
+ * @module ai-trace/capture
3
+ * Applies the capture mode and redaction before any text reaches a sink. Redaction reuses the
4
+ * engine's lexical scrubber (`@jini-ai/core` `redactSecretsWithCounts`): credential shapes,
5
+ * emails, phones, Luhn-valid cards. It does NOT detect names, addresses or business secrets —
6
+ * that is why `metadata` (char counts only) exists and is the recommended default for prompts
7
+ * that may hold customer data.
8
+ */
9
+ import { redactSecretsWithCounts } from '@jini-ai/core';
10
+ export const DEFAULT_MAX_CAPTURED_CHARS = 16_000;
11
+ /** `off` → `null`; `metadata` → `{ chars }`; `full` → redacted (then truncated) text plus counts. */
12
+ export function captureText({ text }, { mode = 'metadata', maxChars = DEFAULT_MAX_CAPTURED_CHARS, exactSecrets = [] } = {}) {
13
+ if (mode === 'off' || text === null || text === undefined)
14
+ return null;
15
+ if (mode === 'metadata')
16
+ return { chars: text.length };
17
+ return captureFullText({ text, maxChars, exactSecrets });
18
+ }
19
+ // Redact before truncating: a cut through a secret would leave a prefix no rule matches.
20
+ function captureFullText({ text, maxChars, exactSecrets }) {
21
+ const { redacted, counts } = redactSecretsWithCounts({ input: text }, { exactSecrets });
22
+ const truncated = redacted.length > maxChars;
23
+ return {
24
+ chars: text.length,
25
+ text: truncated ? redacted.slice(0, maxChars) : redacted,
26
+ ...(truncated ? { truncated } : {}),
27
+ ...(Object.keys(counts).length ? { redactions: counts } : {}),
28
+ };
29
+ }
30
+ /** Tool inputs arrive as objects; stringify once so capture/redaction sees the same text a backend would. */
31
+ export function stringifyForCapture({ value }) {
32
+ if (value === undefined || value === null)
33
+ return null;
34
+ if (typeof value === 'string')
35
+ return value;
36
+ try {
37
+ return JSON.stringify(value);
38
+ }
39
+ catch {
40
+ return String(value);
41
+ }
42
+ }
43
+ //# sourceMappingURL=capture.js.map
@@ -0,0 +1,12 @@
1
+ /**
2
+ * @module ai-trace/classify
3
+ * Lexical tool-failure classifier. Order matters: "permission denied … timed out" is a denial,
4
+ * and a schema rejection is checked before the generic execution bucket. It reads only the
5
+ * result text the provider surfaced, so a tool that fails with an unhelpful message lands in
6
+ * `execution` — the safe default, since that bucket means "look at the tool".
7
+ */
8
+ import type { AiToolErrorClass } from './types.js';
9
+ export declare function classifyToolError({ content }: {
10
+ content: string;
11
+ }): AiToolErrorClass;
12
+ //# sourceMappingURL=classify.d.ts.map
@@ -0,0 +1,13 @@
1
+ const CLASS_PATTERNS = [
2
+ ['denied', /\b(permission denied|denied|not allowed|not permitted|forbidden|unauthori[sz]ed|requires approval|user rejected|rejected by user)\b/i],
3
+ ['timeout', /\b(timed? ?out|timeout|deadline exceeded|ETIMEDOUT)\b/i],
4
+ ['input_validation', /\b(unknown (input|argument|parameter|property|field)|invalid (input|argument|arguments|parameter|params)|missing required|is required|required (property|parameter|field)|validation (error|failed)|schema|must be (a|an|of)|expected .+ (got|received)|InputValidationError|unrecognized key)\b/i],
5
+ ];
6
+ export function classifyToolError({ content }) {
7
+ for (const [errorClass, pattern] of CLASS_PATTERNS) {
8
+ if (pattern.test(content))
9
+ return errorClass;
10
+ }
11
+ return 'execution';
12
+ }
13
+ //# sourceMappingURL=classify.js.map
@@ -0,0 +1,13 @@
1
+ /**
2
+ * @module ai-trace
3
+ * Vendor-neutral AI-run tracing: contract, recorder over the normalized agent-event stream, and
4
+ * backend-free sinks. Vendor adapters are provider plugins (`ai-trace-langfuse` in
5
+ * `@jini-ai/provider-plugins`), so neither this entry nor this package ever pulls an SDK.
6
+ */
7
+ export type * from './types.js';
8
+ export { createAiTraceRecorder, type AiTraceRecorder, type AiTraceRecorderOptions } from './recorder.js';
9
+ export { noopAiTraceSink, createRecordingAiTraceSink, createFanOutAiTraceSink, createLazyAiTraceSink, DEFAULT_LAZY_SINK_QUEUE, type RecordingAiTraceSink } from './sinks.js';
10
+ export { captureText, DEFAULT_MAX_CAPTURED_CHARS, type CaptureTextOptions } from './capture.js';
11
+ export { classifyToolError } from './classify.js';
12
+ export { normalizeAiUsage } from './usage.js';
13
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1,6 @@
1
+ export { createAiTraceRecorder } from './recorder.js';
2
+ export { noopAiTraceSink, createRecordingAiTraceSink, createFanOutAiTraceSink, createLazyAiTraceSink, DEFAULT_LAZY_SINK_QUEUE } from './sinks.js';
3
+ export { captureText, DEFAULT_MAX_CAPTURED_CHARS } from './capture.js';
4
+ export { classifyToolError } from './classify.js';
5
+ export { normalizeAiUsage } from './usage.js';
6
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1,65 @@
1
+ /**
2
+ * @module ai-trace/recorder
3
+ *
4
+ * Turns the normalized agent-event stream into {@link AiTraceEvent}s. Every provider path in the
5
+ * runtime already converges on one vocabulary before the daemon sees it — `status` (model),
6
+ * `text_delta`, `thinking_delta`, `tool_use`, `tool_result`, `usage`, `turn_end`, `error`, `end`
7
+ * — emitted by `claude-stream`, `copilot-stream`, `qoder-stream`, `json-event-stream` (Codex,
8
+ * OpenCode, Cursor, Kimi), the ACP session (Gemini/Codex/Hermes over ACP) and
9
+ * `runProviderToolTurn` (OpenAI/Anthropic/Azure/Google HTTP). Tapping that one vocabulary is
10
+ * what makes tracing provider-agnostic: no per-vendor code lives here.
11
+ *
12
+ * A model turn follows explicit request boundaries (`status: requesting`, `end`) when the stream has them;
13
+ * otherwise each usage report closes one turn (CLI per-step or per-run usage).
14
+ * Within a request, usage reports are snapshots, not boundaries: a final frame can contain usage AND more text.
15
+ * HTTP tool-turn produces one turn per call; CLIs that report once per run (Claude Code `result`,
16
+ * Copilot) produce one turn per run with all its tool calls — the granularity the provider gave,
17
+ * not a guess.
18
+ */
19
+ import { type CaptureTextOptions } from './capture.js';
20
+ import type { AiContentCapture, AiRunOutcome, AiTokenUsage, AiTraceSink } from './types.js';
21
+ type AgentEvent = Record<string, unknown>;
22
+ export interface AiTraceRecorderOptions {
23
+ readonly provider?: string | null;
24
+ readonly model?: string | null;
25
+ readonly sessionId?: string | null;
26
+ readonly traceId?: string;
27
+ readonly tags?: readonly string[];
28
+ readonly capture?: AiContentCapture;
29
+ readonly exactSecrets?: CaptureTextOptions['exactSecrets'];
30
+ readonly maxCapturedChars?: number;
31
+ readonly now?: () => number;
32
+ /** Optional host price table; only consulted when the provider reported no cost. */
33
+ readonly priceUsage?: (args: {
34
+ model: string | null;
35
+ usage: AiTokenUsage;
36
+ }) => number | null;
37
+ /** A failing backend must never fail the run; the host decides whether to log it. */
38
+ readonly onSinkError?: (error: unknown) => void;
39
+ }
40
+ export interface AiTraceRecorder {
41
+ readonly traceId: string;
42
+ start(args: {
43
+ input?: string | null;
44
+ }): void;
45
+ /** Supplies the prompt after `start` (hosts that learn it late); it rides the first model turn. */
46
+ noteInput(args: {
47
+ input: string;
48
+ }): void;
49
+ observe(event: AgentEvent): void;
50
+ finish(required: {
51
+ outcome: AiRunOutcome;
52
+ }, optional?: {
53
+ error?: {
54
+ message: string;
55
+ code?: string | null;
56
+ } | null;
57
+ }): void;
58
+ }
59
+ export declare function createAiTraceRecorder({ sink, runId, agentId }: {
60
+ sink: AiTraceSink;
61
+ runId: string;
62
+ agentId: string;
63
+ }, options?: AiTraceRecorderOptions): AiTraceRecorder;
64
+ export {};
65
+ //# sourceMappingURL=recorder.d.ts.map