orchajs 0.27.3 → 0.28.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (37) hide show
  1. package/README.md +31 -0
  2. package/dist/amarsia/analytics.d.ts +37 -3
  3. package/dist/amarsia/analytics.js +57 -5
  4. package/dist/cli-agents-template.d.ts +1 -1
  5. package/dist/cli-agents-template.js +9 -0
  6. package/dist/errors.d.ts +1 -0
  7. package/dist/errors.js +7 -0
  8. package/dist/index.d.ts +1 -1
  9. package/dist/index.js +1 -1
  10. package/dist/orcha.js +14 -8
  11. package/dist/providers/index.js +7 -1
  12. package/dist/runtime/agent.js +22 -9
  13. package/dist/runtime/create-orcha.js +15 -5
  14. package/dist/runtime/node-module-loader.d.ts +11 -0
  15. package/dist/runtime/node-module-loader.js +18 -0
  16. package/dist/runtime/structured-output.d.ts +1 -0
  17. package/dist/runtime/structured-output.js +10 -1
  18. package/dist/storage/create-store.js +1 -1
  19. package/dist/storage/node-sqlite-facade.d.ts +20 -0
  20. package/dist/storage/node-sqlite-facade.js +48 -0
  21. package/dist/telemetry/open-telemetry.d.ts +19 -0
  22. package/dist/telemetry/open-telemetry.js +630 -0
  23. package/dist/types.d.ts +13 -0
  24. package/dist-cjs/amarsia/analytics.js +60 -5
  25. package/dist-cjs/cli-agents-template.js +9 -0
  26. package/dist-cjs/errors.js +7 -0
  27. package/dist-cjs/index.js +2 -2
  28. package/dist-cjs/orcha.js +19 -8
  29. package/dist-cjs/providers/index.js +7 -1
  30. package/dist-cjs/runtime/agent.js +16 -9
  31. package/dist-cjs/runtime/create-orcha.js +12 -2
  32. package/dist-cjs/runtime/node-module-loader.js +42 -0
  33. package/dist-cjs/runtime/structured-output.js +12 -1
  34. package/dist-cjs/storage/create-store.js +2 -2
  35. package/dist-cjs/storage/node-sqlite-facade.js +72 -0
  36. package/dist-cjs/telemetry/open-telemetry.js +635 -0
  37. package/package.json +36 -4
@@ -1,8 +1,8 @@
1
- import { describeProviderError, isRetryableProviderConnectionError, OrchaError, } from "../errors.js";
1
+ import { describeProviderError, isOrchaError, isRetryableProviderConnectionError, OrchaError, } from "../errors.js";
2
2
  import { sanitizeErrorMessage } from "../amarsia/analytics.js";
3
3
  import { normalizeLocalFile, normalizeUrlContent, } from "../file-content.js";
4
4
  import { messagesFromEvents, normalizePersistedToolResults, SessionEventWriter, } from "./session-events.js";
5
- import { StructuredOutputError, validateStructuredValue, } from "./structured-output.js";
5
+ import { isStructuredOutputError, validateStructuredValue, } from "./structured-output.js";
6
6
  import { executeLocalAction } from "./actions/execute.js";
7
7
  import { createExecution, } from "./execution.js";
8
8
  import { McpClientPool, } from "./mcp/client.js";
@@ -751,7 +751,7 @@ export class RuntimeAgent {
751
751
  output: streamedOutput,
752
752
  };
753
753
  }
754
- if (error instanceof StructuredOutputError && error.response) {
754
+ if (isStructuredOutputError(error) && error.response) {
755
755
  const modelDurationMs = Math.round(performance.now() - modelStartedAt);
756
756
  const usage = aggregateUsage(previousEvents, writer.run, error.response.usage);
757
757
  const assistantEvent = writer.create("message.created", {
@@ -803,7 +803,7 @@ export class RuntimeAgent {
803
803
  details,
804
804
  });
805
805
  }
806
- if (error instanceof OrchaError) {
806
+ if (isOrchaError(error)) {
807
807
  throw error;
808
808
  }
809
809
  const providerError = describeProviderError(error);
@@ -992,9 +992,9 @@ export class RuntimeAgent {
992
992
  }
993
993
  catch (error) {
994
994
  const message = error instanceof Error ? error.message : String(error);
995
- const code = error instanceof OrchaError ? error.code : "execution_failed";
996
- const details = error instanceof OrchaError ? error.details : undefined;
997
- const retryable = error instanceof OrchaError ? error.retryable : false;
995
+ const code = isOrchaError(error) ? error.code : "execution_failed";
996
+ const details = isOrchaError(error) ? error.details : undefined;
997
+ const retryable = isOrchaError(error) ? error.retryable : false;
998
998
  const usage = usageForRun(previousEvents, writer.run);
999
999
  await this.#store.append(sessionId, [
1000
1000
  writer.create("run.failed", {
@@ -1492,11 +1492,15 @@ export class RuntimeAgent {
1492
1492
  return subagentToolOutput(existing);
1493
1493
  }
1494
1494
  const input = normalizeDelegatedInput(call.arguments.input, this.#projectRoot);
1495
+ const parentLineage = sessionLineage(parentEvents);
1495
1496
  const lineage = {
1496
1497
  origin: "delegated",
1497
1498
  parentAgent: this.#manifest.key,
1498
1499
  parentSessionId,
1499
1500
  parentCallId: call.callId,
1501
+ parentRunNumber: writer.run,
1502
+ rootSessionId: parentLineage?.rootSessionId ?? parentSessionId,
1503
+ rootRunNumber: parentLineage?.rootRunNumber ?? writer.run,
1500
1504
  };
1501
1505
  const childSessionId = child.createDelegatedSessionId();
1502
1506
  const initiated = writer.create("subagent.initiated", {
@@ -1680,7 +1684,7 @@ export class RuntimeAgent {
1680
1684
  return await operation();
1681
1685
  }
1682
1686
  catch (error) {
1683
- const normalized = error instanceof OrchaError
1687
+ const normalized = isOrchaError(error)
1684
1688
  ? error
1685
1689
  : new OrchaError("storage_error", error instanceof Error ? error.message : String(error), { retryable: true, cause: error });
1686
1690
  return failure(sessionId, normalized.code, normalized.message, {
@@ -1702,7 +1706,7 @@ export class RuntimeAgent {
1702
1706
  return await operation();
1703
1707
  }
1704
1708
  catch (error) {
1705
- if (error instanceof OrchaError) {
1709
+ if (isOrchaError(error)) {
1706
1710
  throw error;
1707
1711
  }
1708
1712
  throw new OrchaError("storage_error", error instanceof Error ? error.message : String(error), { retryable: true, cause: error });
@@ -2999,6 +3003,15 @@ function sessionLineage(events) {
2999
3003
  parentAgent: value.parentAgent,
3000
3004
  parentSessionId: value.parentSessionId,
3001
3005
  parentCallId: value.parentCallId,
3006
+ ...(typeof value.parentRunNumber === "number"
3007
+ ? { parentRunNumber: value.parentRunNumber }
3008
+ : {}),
3009
+ ...(typeof value.rootSessionId === "string"
3010
+ ? { rootSessionId: value.rootSessionId }
3011
+ : {}),
3012
+ ...(typeof value.rootRunNumber === "number"
3013
+ ? { rootRunNumber: value.rootRunNumber }
3014
+ : {}),
3002
3015
  };
3003
3016
  }
3004
3017
  function requiredToolString(value, name) {
@@ -1,8 +1,9 @@
1
1
  import { RuntimeAgent } from "./agent.js";
2
- import { AmarsiaTelemetryClient, withAmarsiaTelemetry, } from "../amarsia/analytics.js";
2
+ import { AmarsiaTelemetryClient, withRunTelemetry, } from "../amarsia/analytics.js";
3
3
  import { isRegistryCompilationActive } from "./compiler-hook.js";
4
4
  import { setOrchaRuntimeContext } from "./context.js";
5
5
  import { createInferenceGenerator } from "./optional-features.js";
6
+ import { CompositeRunTelemetryClient, createOpenTelemetryClient, } from "../telemetry/open-telemetry.js";
6
7
  class OrchaRuntimeCore {
7
8
  #agents = new Map();
8
9
  #bundle;
@@ -80,14 +81,23 @@ class OrchaRuntimeCore {
80
81
  projectRoot,
81
82
  manifest,
82
83
  });
83
- const telemetry = configuration.amarsia?.key
84
- ? new AmarsiaTelemetryClient(configuration.amarsia)
85
- : undefined;
84
+ const telemetryClients = [];
85
+ if (configuration.amarsia?.key) {
86
+ telemetryClients.push(new AmarsiaTelemetryClient(configuration.amarsia));
87
+ }
88
+ if (configuration.telemetry?.otel) {
89
+ telemetryClients.push(createOpenTelemetryClient(configuration.telemetry.otel));
90
+ }
91
+ const telemetry = telemetryClients.length === 0
92
+ ? undefined
93
+ : telemetryClients.length === 1
94
+ ? telemetryClients[0]
95
+ : new CompositeRunTelemetryClient(telemetryClients);
86
96
  this.#telemetry = telemetry;
87
97
  const createRuntimeStore = (manifest) => {
88
98
  const store = createStore(manifest);
89
99
  const runtimeStore = telemetry
90
- ? withAmarsiaTelemetry({ store, manifest, client: telemetry })
100
+ ? withRunTelemetry({ store, manifest, client: telemetry })
91
101
  : store;
92
102
  this.#stores.add(runtimeStore);
93
103
  return runtimeStore;
@@ -0,0 +1,11 @@
1
+ /**
2
+ * Loads a Node-only package subpath without exposing it to consumer bundlers.
3
+ * Callers pass path segments so no optional module specifier is statically
4
+ * discoverable from the default package graph.
5
+ */
6
+ export declare function requireRuntimeModule<T>(specifierSegments: string[]): T;
7
+ /**
8
+ * Loads an ESM package subpath without exposing the optional module specifier
9
+ * to consumer bundlers.
10
+ */
11
+ export declare function importRuntimeModule<T>(specifierSegments: string[]): Promise<T>;
@@ -0,0 +1,18 @@
1
+ import { createRequire } from "node:module";
2
+ const runtimeRequire = createRequire(import.meta.url);
3
+ const runtimeImport = new Function("specifier", "return import(specifier)");
4
+ /**
5
+ * Loads a Node-only package subpath without exposing it to consumer bundlers.
6
+ * Callers pass path segments so no optional module specifier is statically
7
+ * discoverable from the default package graph.
8
+ */
9
+ export function requireRuntimeModule(specifierSegments) {
10
+ return runtimeRequire(specifierSegments.join("/"));
11
+ }
12
+ /**
13
+ * Loads an ESM package subpath without exposing the optional module specifier
14
+ * to consumer bundlers.
15
+ */
16
+ export async function importRuntimeModule(specifierSegments) {
17
+ return await runtimeImport(specifierSegments.join("/"));
18
+ }
@@ -14,6 +14,7 @@ export declare class StructuredOutputError extends Error {
14
14
  cause?: unknown;
15
15
  });
16
16
  }
17
+ export declare function isStructuredOutputError(value: unknown): value is StructuredOutputError;
17
18
  export declare function resolveProviderStructuredOutput(request: ProviderRequest, baseResponse: ProviderResponse, textOutput: string): ProviderResponse;
18
19
  export declare function parseStructuredOutput(text: string, schema: Record<string, unknown>): unknown;
19
20
  export declare function validateStructuredValue(value: unknown, schema: Record<string, unknown>, label?: string): void;
@@ -1,3 +1,4 @@
1
+ const STRUCTURED_OUTPUT_ERROR_BRAND = Symbol.for("orchajs.StructuredOutputError");
1
2
  export class StructuredOutputError extends Error {
2
3
  kind;
3
4
  rawText;
@@ -7,12 +8,20 @@ export class StructuredOutputError extends Error {
7
8
  constructor(message, options) {
8
9
  super(message, { cause: options.cause });
9
10
  this.name = "StructuredOutputError";
11
+ Object.defineProperty(this, STRUCTURED_OUTPUT_ERROR_BRAND, {
12
+ value: true,
13
+ });
10
14
  this.kind = options.kind;
11
15
  this.rawText = options.rawText;
12
16
  this.responsePreview = options.responsePreview;
13
17
  this.schemaErrors = options.schemaErrors;
14
18
  }
15
19
  }
20
+ export function isStructuredOutputError(value) {
21
+ return (typeof value === "object" &&
22
+ value !== null &&
23
+ value[STRUCTURED_OUTPUT_ERROR_BRAND] === true);
24
+ }
16
25
  export function resolveProviderStructuredOutput(request, baseResponse, textOutput) {
17
26
  if (request.outputType !== "json" ||
18
27
  baseResponse.toolCalls.length > 0 ||
@@ -27,7 +36,7 @@ export function resolveProviderStructuredOutput(request, baseResponse, textOutpu
27
36
  };
28
37
  }
29
38
  catch (error) {
30
- if (error instanceof StructuredOutputError) {
39
+ if (isStructuredOutputError(error)) {
31
40
  error.response = baseResponse;
32
41
  }
33
42
  throw error;
@@ -1,5 +1,5 @@
1
1
  import { NodeJsonlSessionStore } from "./node-jsonl.js";
2
- import { NodeSqliteSessionStore } from "./node-sqlite.js";
2
+ import { NodeSqliteSessionStore } from "./node-sqlite-facade.js";
3
3
  export function createSessionStore(options) {
4
4
  const strategy = options.strategy ?? "node-jsonl";
5
5
  const directory = options.directory ?? ".orcha/sessions";
@@ -0,0 +1,20 @@
1
+ import type { SessionEvent, SessionStore } from "../types.js";
2
+ /**
3
+ * Backwards-compatible lazy facade for SQLite storage. The native-backed
4
+ * implementation is resolved only when this class is instantiated.
5
+ */
6
+ export declare class NodeSqliteSessionStore implements SessionStore {
7
+ #private;
8
+ readonly databasePath: string;
9
+ readonly agentName: string;
10
+ constructor(directory?: string, projectRoot?: string, agentName?: string);
11
+ read(sessionId: string): Promise<SessionEvent[]>;
12
+ readAfterSequence(sessionId: string, afterSequence: number, limit: number): Promise<SessionEvent[]>;
13
+ append(sessionId: string, events: SessionEvent[]): Promise<void>;
14
+ listSessionIds(): Promise<string[]>;
15
+ getCloudAcknowledgement(sessionId: string): Promise<number>;
16
+ setCloudAcknowledgement(sessionId: string, sequence: number): Promise<void>;
17
+ subscribe(sessionId: string, listener: (events: SessionEvent[]) => void): () => void;
18
+ subscribeAll(listener: (sessionId: string, events: SessionEvent[]) => void): () => void;
19
+ describeLocation(sessionId: string): Promise<string>;
20
+ }
@@ -0,0 +1,48 @@
1
+ import { requireRuntimeModule } from "../runtime/node-module-loader.js";
2
+ /**
3
+ * Backwards-compatible lazy facade for SQLite storage. The native-backed
4
+ * implementation is resolved only when this class is instantiated.
5
+ */
6
+ export class NodeSqliteSessionStore {
7
+ #store;
8
+ databasePath;
9
+ agentName;
10
+ constructor(directory = ".orcha/sessions", projectRoot = process.cwd(), agentName) {
11
+ const { NodeSqliteSessionStore: SqliteStore } = requireRuntimeModule(["orchajs", "storage", "sqlite"]);
12
+ const store = new SqliteStore(directory, projectRoot, agentName);
13
+ this.#store = store;
14
+ this.databasePath = store.databasePath;
15
+ this.agentName = store.agentName;
16
+ }
17
+ read(sessionId) {
18
+ return this.#store.read(sessionId);
19
+ }
20
+ readAfterSequence(sessionId, afterSequence, limit) {
21
+ return this.#store.readAfterSequence?.(sessionId, afterSequence, limit) ?? Promise.resolve([]);
22
+ }
23
+ append(sessionId, events) {
24
+ return this.#store.append(sessionId, events);
25
+ }
26
+ listSessionIds() {
27
+ return this.#store.listSessionIds();
28
+ }
29
+ getCloudAcknowledgement(sessionId) {
30
+ return this.#store.getCloudAcknowledgement?.(sessionId) ??
31
+ Promise.resolve(0);
32
+ }
33
+ setCloudAcknowledgement(sessionId, sequence) {
34
+ return this.#store.setCloudAcknowledgement?.(sessionId, sequence) ??
35
+ Promise.resolve();
36
+ }
37
+ subscribe(sessionId, listener) {
38
+ return this.#store.subscribe?.(sessionId, listener) ??
39
+ (() => undefined);
40
+ }
41
+ subscribeAll(listener) {
42
+ return this.#store.subscribeAll?.(listener) ?? (() => undefined);
43
+ }
44
+ describeLocation(sessionId) {
45
+ return this.#store.describeLocation?.(sessionId) ??
46
+ Promise.resolve(this.databasePath);
47
+ }
48
+ }
@@ -0,0 +1,19 @@
1
+ import type { AmarsiaRunFact, RunTelemetryClient, RunTelemetryDetails } from "../amarsia/analytics.js";
2
+ export type OpenTelemetryConfiguration = true | {
3
+ endpoint: string;
4
+ headers?: Record<string, string>;
5
+ };
6
+ export declare class CompositeRunTelemetryClient implements RunTelemetryClient {
7
+ #private;
8
+ constructor(clients: RunTelemetryClient[]);
9
+ enqueue(fact: AmarsiaRunFact, details?: RunTelemetryDetails): void;
10
+ updateActiveRun(fact: AmarsiaRunFact): void;
11
+ trackProjection(projection: Promise<void>): void;
12
+ drain(options?: {
13
+ timeoutMs?: number;
14
+ }): Promise<void>;
15
+ close(options?: {
16
+ timeoutMs?: number;
17
+ }): Promise<void>;
18
+ }
19
+ export declare function createOpenTelemetryClient(configuration: OpenTelemetryConfiguration): RunTelemetryClient;