@lunora/agent 1.0.0-alpha.9 → 1.0.0-alpha.91

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 (88) hide show
  1. package/dist/channels.d.mts +3 -11
  2. package/dist/channels.d.ts +3 -11
  3. package/dist/channels.mjs +1 -181
  4. package/dist/component.d.mts +2 -0
  5. package/dist/component.d.ts +2 -0
  6. package/dist/component.mjs +2 -418
  7. package/dist/inbound.d.mts +7 -5
  8. package/dist/inbound.d.ts +7 -5
  9. package/dist/inbound.mjs +1 -32
  10. package/dist/index.d.mts +49 -8
  11. package/dist/index.d.ts +49 -8
  12. package/dist/index.mjs +1 -18
  13. package/dist/naming.mjs +1 -8
  14. package/dist/packem_shared/AGENT_MODULE-M4D1EejI.mjs +1 -0
  15. package/dist/packem_shared/VoiceSessionDO-BdvnaLoO.mjs +1 -0
  16. package/dist/packem_shared/adaptMcpResult-CVlq-_TO.mjs +2 -0
  17. package/dist/packem_shared/agent-loop-B3KTMfqm.mjs +3 -0
  18. package/dist/packem_shared/agentAsTool-CgZb6ycK.mjs +1 -0
  19. package/dist/packem_shared/base64-5eyBfWO3.mjs +1 -0
  20. package/dist/packem_shared/braintrustTelemetry-Byne8uPK.mjs +1 -0
  21. package/dist/packem_shared/branch-marker-boZ00zmk.mjs +1 -0
  22. package/dist/packem_shared/buildModelMessages-Y4tGo1T9.mjs +5 -0
  23. package/dist/packem_shared/codeTool-BQb-K3my.mjs +1 -0
  24. package/dist/packem_shared/collectAgenticMemoryTools-BeMWT2qt.mjs +1 -0
  25. package/dist/packem_shared/combineTelemetry-DgE9W9G8.mjs +1 -0
  26. package/dist/packem_shared/common-CJSjtsfv.mjs +1 -0
  27. package/dist/packem_shared/compileAgentWorkflow-DRkaF9sV.mjs +1 -0
  28. package/dist/packem_shared/component-shared-G8ngerkU.mjs +1 -0
  29. package/dist/packem_shared/consoleTelemetry-BZY3Y-Ly.mjs +1 -0
  30. package/dist/packem_shared/createAgentContext-DPFZ88dr.mjs +1 -0
  31. package/dist/packem_shared/createAgentGenerate-BOILDUZj.mjs +3 -0
  32. package/dist/packem_shared/createDispatchRunner-BMgSkFiH-DjUQx8vg.mjs +1 -0
  33. package/dist/packem_shared/defineAgent-Q3MlQjYs.mjs +3 -0
  34. package/dist/packem_shared/defineSkill-DGGvDWNq.mjs +1 -0
  35. package/dist/packem_shared/fnv1a-BNN96GYb.mjs +1 -0
  36. package/dist/packem_shared/functionTool-D3CP4f8-.mjs +1 -0
  37. package/dist/packem_shared/in-flight-calls-GH1A_1P3.mjs +1 -0
  38. package/dist/packem_shared/normalizeEntityName-k3fjicAG.mjs +2 -0
  39. package/dist/packem_shared/otlpTelemetry-ByqrB-72.mjs +1 -0
  40. package/dist/packem_shared/positive-integer-ztHqqpBk.mjs +1 -0
  41. package/dist/packem_shared/runAgentLoop-DJvzWDgh.mjs +1 -0
  42. package/dist/packem_shared/runVoiceTurn-D1WCjVPw.mjs +1 -0
  43. package/dist/packem_shared/sandboxComponent-BtOkUYpY.mjs +5 -0
  44. package/dist/packem_shared/sentryTelemetry-BHeydiAB.mjs +1 -0
  45. package/dist/packem_shared/tool-output-Cmk3JWMG.mjs +1 -0
  46. package/dist/packem_shared/{types.d-boAM2Yi1.d.mts → types.d-B8WZl1rU.d.mts} +255 -22
  47. package/dist/packem_shared/{types.d-boAM2Yi1.d.ts → types.d-B8WZl1rU.d.ts} +255 -22
  48. package/dist/packem_shared/voice-turn-D1ZzTzcE.mjs +1 -0
  49. package/dist/reply.d.mts +40 -0
  50. package/dist/reply.d.ts +40 -0
  51. package/dist/reply.mjs +1 -0
  52. package/dist/sandbox.d.mts +14 -13
  53. package/dist/sandbox.d.ts +14 -13
  54. package/dist/sandbox.mjs +1 -113
  55. package/dist/skill-markdown.d.mts +36 -0
  56. package/dist/skill-markdown.d.ts +36 -0
  57. package/dist/skill-markdown.mjs +1 -0
  58. package/dist/telemetry/index.d.mts +152 -33
  59. package/dist/telemetry/index.d.ts +152 -33
  60. package/dist/telemetry/index.mjs +1 -5
  61. package/package.json +18 -9
  62. package/dist/packem_shared/AGENT_MODULE-Dnt_-AAT.mjs +0 -24
  63. package/dist/packem_shared/VoiceSessionDO-BdwlLaXC.mjs +0 -297
  64. package/dist/packem_shared/adaptMcpResult-wtNMvLoP.mjs +0 -65
  65. package/dist/packem_shared/agentAsTool-CUHlWsmt.mjs +0 -98
  66. package/dist/packem_shared/base64-BVwtgRJV.mjs +0 -18
  67. package/dist/packem_shared/braintrustTelemetry-TP7Kwuuj.mjs +0 -47
  68. package/dist/packem_shared/buildModelMessages-BWFigaoo.mjs +0 -69
  69. package/dist/packem_shared/codeTool-CjgJOC9t.mjs +0 -122
  70. package/dist/packem_shared/collectAgenticMemoryTools-QrzpV-WX.mjs +0 -97
  71. package/dist/packem_shared/combineTelemetry-DCyaaWAI.mjs +0 -43
  72. package/dist/packem_shared/common-DQXayow6.mjs +0 -89
  73. package/dist/packem_shared/compileAgentWorkflow-DAfyUuI5.mjs +0 -78
  74. package/dist/packem_shared/consoleTelemetry--3sWfu1R.mjs +0 -93
  75. package/dist/packem_shared/createAgentContext-4xJGXNR4.mjs +0 -50
  76. package/dist/packem_shared/createAgentGenerate-DO7Z96zX.mjs +0 -192
  77. package/dist/packem_shared/createDispatchRunner-DSbp_dph-ZHTtxy3f.mjs +0 -69
  78. package/dist/packem_shared/defineAgent-DAwAZC9P.mjs +0 -148
  79. package/dist/packem_shared/defineSkill-Ctf_S-rz.mjs +0 -22
  80. package/dist/packem_shared/functionTool-D6lCa2jB.mjs +0 -20
  81. package/dist/packem_shared/graph-component-Bbaxxymp.mjs +0 -217
  82. package/dist/packem_shared/memory-D4FPcBsX.mjs +0 -12
  83. package/dist/packem_shared/normalizeEntityName-BouctxLC.mjs +0 -3
  84. package/dist/packem_shared/otlpTelemetry-CKgmWVLg.mjs +0 -170
  85. package/dist/packem_shared/runAgentLoop-M8PKbtWT.mjs +0 -493
  86. package/dist/packem_shared/runVoiceTurn-LnqLvCRR.mjs +0 -211
  87. package/dist/packem_shared/sandboxComponent-DR3pTwBL.mjs +0 -194
  88. package/dist/packem_shared/sentryTelemetry-A4F5ndh9.mjs +0 -36
@@ -1,217 +0,0 @@
1
- import { defineTable, initLunora } from '@lunora/server';
2
- import { v } from '@lunora/values';
3
-
4
- const AGENT_EXTENSION_KEY = "agent";
5
- const asInternal = (function_) => {
6
- return { ...function_, visibility: "internal" };
7
- };
8
- const definedColumns = (columns) => {
9
- const result = {};
10
- for (const [key, value] of Object.entries(columns)) {
11
- if (value !== void 0) {
12
- result[key] = value;
13
- }
14
- }
15
- return result;
16
- };
17
-
18
- const ENTITIES_BARE_TABLE = "entities";
19
- const EDGES_BARE_TABLE = "edges";
20
- const ENTITIES_TABLE = `${AGENT_EXTENSION_KEY}_${ENTITIES_BARE_TABLE}`;
21
- const EDGES_TABLE = `${AGENT_EXTENSION_KEY}_${EDGES_BARE_TABLE}`;
22
- const graphTables = {
23
- /**
24
- * Graph-memory nodes — one per normalized entity name per owner. `weight` is
25
- * salience (last-write-wins, absolute set → replay-idempotent),
26
- * `firstMessageKey` is provenance.
27
- */
28
- [ENTITIES_BARE_TABLE]: defineTable({
29
- createdAt: v.number(),
30
- firstMessageKey: v.optional(v.string()),
31
- /** Normalized (trim/collapse/lowercase) — the per-owner dedup key. */
32
- name: v.string(),
33
- owner: v.string(),
34
- type: v.optional(v.string()),
35
- updatedAt: v.number(),
36
- weight: v.optional(v.number())
37
- }).index("byOwnerName", ["owner", "name"], { unique: true }).index("byOwnerUpdatedAt", ["owner", "updatedAt"]).public(),
38
- /**
39
- * Graph-memory edges — directed triples storing the normalized endpoint
40
- * NAMES (no join on write), owner-scoped like the nodes. `weight` is
41
- * confidence (last-write-wins), `messageKey` is provenance. Traversal is
42
- * bidirectional, so both endpoints are indexed.
43
- */
44
- [EDGES_BARE_TABLE]: defineTable({
45
- createdAt: v.number(),
46
- dstName: v.string(),
47
- label: v.string(),
48
- messageKey: v.string(),
49
- owner: v.string(),
50
- srcName: v.string(),
51
- updatedAt: v.number(),
52
- weight: v.optional(v.number())
53
- }).index("byOwnerSrc", ["owner", "srcName"]).index("byOwnerDst", ["owner", "dstName"]).index("byTriple", ["owner", "srcName", "label", "dstName"], { unique: true }).public()
54
- };
55
- const GRAPH_ARRAY_CAP = 64;
56
- const DEFAULT_GRAPH_DEPTH = 2;
57
- const DEFAULT_GRAPH_MAX_SEEDS = 4;
58
- const DEFAULT_GRAPH_FAN_OUT = 8;
59
- const DEFAULT_GRAPH_MAX_NODES = 32;
60
- const GRAPH_SEED_SCAN_CAP = 500;
61
- const WHITESPACE_RUN = /\s+/gu;
62
- const NON_WORD = /[^\p{L}\p{N}]+/u;
63
- const normalizeEntityName = (name) => name.trim().replaceAll(WHITESPACE_RUN, " ").toLowerCase();
64
- const tokenizeQuery = (text) => text.toLowerCase().split(NON_WORD).filter((token) => token.length >= 2);
65
- const toGraphEdge = (row) => {
66
- return {
67
- dstName: row["dstName"],
68
- label: row["label"],
69
- srcName: row["srcName"],
70
- weight: row["weight"] ?? 1
71
- };
72
- };
73
- const compareEdgesByWeight = (a, b) => b.weight - a.weight || a.label.localeCompare(b.label) || a.srcName.localeCompare(b.srcName) || a.dstName.localeCompare(b.dstName);
74
- const matchesSeed = (entityName, tokens) => tokens.some((token) => entityName.includes(token) || token.includes(entityName));
75
- const renderTriples = (edges) => edges.map((edge) => `- ${edge.srcName} —[${edge.label}]→ ${edge.dstName}`).toSorted((a, b) => a.localeCompare(b)).join("\n");
76
- const edgeKey = (edge) => `${edge.srcName}\0${edge.label}\0${edge.dstName}`;
77
- const addEdge = (edge, from, bounds, accumulator) => {
78
- const key = edgeKey(edge);
79
- if (!accumulator.collectedKeys.has(key)) {
80
- accumulator.collectedKeys.add(key);
81
- accumulator.collected.push(edge);
82
- }
83
- const neighbor = edge.srcName === from ? edge.dstName : edge.srcName;
84
- if (!accumulator.seen.has(neighbor) && accumulator.seen.size < bounds.maxNodes) {
85
- accumulator.seen.add(neighbor);
86
- accumulator.next.push(neighbor);
87
- }
88
- };
89
- const traverseGraph = async (edgesFrom, seeds, bounds) => {
90
- const accumulator = { collected: [], collectedKeys: /* @__PURE__ */ new Set(), next: [], seen: new Set(seeds) };
91
- let frontier = seeds.slice(0, bounds.maxNodes);
92
- for (let depth = 0; depth < bounds.depth && frontier.length > 0; depth += 1) {
93
- accumulator.next = [];
94
- for (const node of frontier) {
95
- const nodeEdges = await edgesFrom(node);
96
- const incident = nodeEdges.toSorted(compareEdgesByWeight).slice(0, bounds.fanOut);
97
- for (const edge of incident) {
98
- addEdge(edge, node, bounds, accumulator);
99
- }
100
- }
101
- frontier = accumulator.next;
102
- }
103
- return accumulator.collected;
104
- };
105
- const { mutation, query } = initLunora.dataModel().create();
106
- const graphComponent = () => {
107
- const agentGraphUpsert = mutation.input({
108
- entities: v.array(v.object({ name: v.string(), type: v.optional(v.string()) })),
109
- messageKey: v.string(),
110
- owner: v.string(),
111
- relations: v.array(v.object({ confidence: v.optional(v.number()), dst: v.string(), label: v.string(), src: v.string() }))
112
- }).mutation(async ({ args, ctx: context }) => {
113
- const now = Date.now();
114
- const upsertEntity = async (rawName, type) => {
115
- const name = normalizeEntityName(rawName);
116
- if (name.length === 0) {
117
- return void 0;
118
- }
119
- const existing = await context.db.query(ENTITIES_TABLE).withIndex("byOwnerName", (q) => q.eq("owner", args.owner).eq("name", name)).first();
120
- if (existing) {
121
- if (type !== void 0 && existing["type"] === void 0) {
122
- await context.db.patch(existing["_id"], { type, updatedAt: now });
123
- }
124
- return name;
125
- }
126
- await context.db.insert(ENTITIES_TABLE, {
127
- createdAt: now,
128
- name,
129
- owner: args.owner,
130
- updatedAt: now,
131
- weight: 1,
132
- ...definedColumns({ firstMessageKey: args.messageKey, type })
133
- });
134
- return name;
135
- };
136
- const upsertRelation = async (relation) => {
137
- const sourceName = normalizeEntityName(relation.src);
138
- const destinationName = normalizeEntityName(relation.dst);
139
- const label = normalizeEntityName(relation.label);
140
- if (sourceName.length === 0 || destinationName.length === 0 || label.length === 0 || sourceName === destinationName) {
141
- return false;
142
- }
143
- await upsertEntity(sourceName);
144
- await upsertEntity(destinationName);
145
- const confidence = relation.confidence ?? 1;
146
- const existing = await context.db.query(EDGES_TABLE).withIndex("byTriple", (q) => q.eq("owner", args.owner).eq("srcName", sourceName).eq("label", label).eq("dstName", destinationName)).first();
147
- if (existing) {
148
- const priorWeight = existing["weight"] ?? 1;
149
- await context.db.patch(existing["_id"], { updatedAt: now, weight: Math.max(priorWeight, confidence) });
150
- } else {
151
- await context.db.insert(EDGES_TABLE, {
152
- createdAt: now,
153
- dstName: destinationName,
154
- label,
155
- messageKey: args.messageKey,
156
- owner: args.owner,
157
- srcName: sourceName,
158
- updatedAt: now,
159
- weight: confidence
160
- });
161
- }
162
- return true;
163
- };
164
- let entities = 0;
165
- for (const entity of args.entities.slice(0, GRAPH_ARRAY_CAP)) {
166
- if (await upsertEntity(entity.name, entity.type) !== void 0) {
167
- entities += 1;
168
- }
169
- }
170
- let relations = 0;
171
- for (const relation of args.relations.slice(0, GRAPH_ARRAY_CAP)) {
172
- if (await upsertRelation(relation)) {
173
- relations += 1;
174
- }
175
- }
176
- return { entities, relations };
177
- });
178
- const agentGraphTraverse = query.input({
179
- depth: v.optional(v.number()),
180
- fanOut: v.optional(v.number()),
181
- maxNodes: v.optional(v.number()),
182
- maxSeeds: v.optional(v.number()),
183
- owner: v.string(),
184
- query: v.string()
185
- }).query(async ({ args, ctx: context }) => {
186
- const tokens = tokenizeQuery(args.query);
187
- if (tokens.length === 0) {
188
- return { context: "" };
189
- }
190
- const ownerEntities = await context.db.query(ENTITIES_TABLE).withIndex("byOwnerUpdatedAt", (q) => q.eq("owner", args.owner)).order("desc").take(GRAPH_SEED_SCAN_CAP);
191
- const seeds = ownerEntities.filter((row) => matchesSeed(row["name"], tokens)).toSorted(
192
- (a, b) => (b["weight"] ?? 1) - (a["weight"] ?? 1) || a["name"].localeCompare(b["name"])
193
- ).slice(0, args.maxSeeds ?? DEFAULT_GRAPH_MAX_SEEDS).map((row) => row["name"]);
194
- if (seeds.length === 0) {
195
- return { context: "" };
196
- }
197
- const edgesFrom = async (node) => {
198
- const [outgoing, incoming] = await Promise.all([
199
- context.db.query(EDGES_TABLE).withIndex("byOwnerSrc", (q) => q.eq("owner", args.owner).eq("srcName", node)).collect(),
200
- context.db.query(EDGES_TABLE).withIndex("byOwnerDst", (q) => q.eq("owner", args.owner).eq("dstName", node)).collect()
201
- ]);
202
- return [...outgoing, ...incoming].map((row) => toGraphEdge(row));
203
- };
204
- const edges = await traverseGraph(edgesFrom, seeds, {
205
- depth: args.depth ?? DEFAULT_GRAPH_DEPTH,
206
- fanOut: args.fanOut ?? DEFAULT_GRAPH_FAN_OUT,
207
- maxNodes: args.maxNodes ?? DEFAULT_GRAPH_MAX_NODES
208
- });
209
- return { context: renderTriples(edges) };
210
- });
211
- return {
212
- agentGraphTraverse: asInternal(agentGraphTraverse),
213
- agentGraphUpsert: asInternal(agentGraphUpsert)
214
- };
215
- };
216
-
217
- export { AGENT_EXTENSION_KEY as A, asInternal as a, graphComponent as b, definedColumns as d, graphTables as g, normalizeEntityName as n };
@@ -1,12 +0,0 @@
1
- const isInjectedMemorySource = (memory) => memory.kind === "graph" || memory.kind === "episodic" || memory.mode !== "agentic";
2
- const resolveInjectedSources = (agent) => {
3
- if (agent.memorySources) {
4
- return agent.memorySources;
5
- }
6
- return agent.memory && isInjectedMemorySource(agent.memory) ? [{ key: "default", ...agent.memory }] : [];
7
- };
8
- const firstGraphSource = (agent) => resolveInjectedSources(agent).find((source) => source.kind === "graph");
9
- const firstEpisodicSource = (agent) => resolveInjectedSources(agent).find((source) => source.kind === "episodic");
10
- const memoryStepName = (base, key) => key === "default" ? base : `${base}:${key}`;
11
-
12
- export { firstEpisodicSource as a, firstGraphSource as f, isInjectedMemorySource as i, memoryStepName as m, resolveInjectedSources as r };
@@ -1,3 +0,0 @@
1
- import '@lunora/server';
2
- import '@lunora/values';
3
- export { b as graphComponent, g as graphTables, n as normalizeEntityName } from './graph-component-Bbaxxymp.mjs';
@@ -1,170 +0,0 @@
1
- import { s as summarizeUsage, r as readField, e as summarizeGatewayTelemetry, c as contentText, t as toolInputOf, a as toolNameOf } from './common-DQXayow6.mjs';
2
-
3
- const otlpUnixNano = (ms) => `${String(Math.round(ms))}000000`;
4
- const otlpRandomHex = (bytes) => {
5
- const buffer = new Uint8Array(bytes);
6
- crypto.getRandomValues(buffer);
7
- let hex = "";
8
- for (const byte of buffer) {
9
- hex += byte.toString(16).padStart(2, "0");
10
- }
11
- return hex;
12
- };
13
- const encodeAttribute = (key, value) => {
14
- if (typeof value === "boolean") {
15
- return { key, value: { boolValue: value } };
16
- }
17
- if (typeof value === "number") {
18
- if (!Number.isFinite(value)) {
19
- return { key, value: { stringValue: String(value) } };
20
- }
21
- return Number.isSafeInteger(value) ? { key, value: { intValue: String(value) } } : { key, value: { doubleValue: value } };
22
- }
23
- return { key, value: { stringValue: value } };
24
- };
25
- const mergeHeaders = (defaults, overrides, token) => {
26
- const merged = {};
27
- const seen = /* @__PURE__ */ new Map();
28
- const put = (name, value) => {
29
- const lower = name.toLowerCase();
30
- const existing = seen.get(lower);
31
- if (existing === void 0) {
32
- seen.set(lower, name);
33
- merged[name] = value;
34
- } else {
35
- merged[existing] = value;
36
- }
37
- };
38
- for (const [name, value] of Object.entries(defaults)) {
39
- put(name, value);
40
- }
41
- for (const [name, value] of Object.entries(overrides ?? {})) {
42
- put(name, value);
43
- }
44
- if (token !== void 0 && token.length > 0) {
45
- put("authorization", `Bearer ${token}`);
46
- }
47
- return merged;
48
- };
49
- const wrapResourceSpans = (span, scopeName, serviceName) => {
50
- return {
51
- resourceSpans: [
52
- {
53
- resource: { attributes: [encodeAttribute("service.name", serviceName)] },
54
- scopeSpans: [{ scope: { name: scopeName }, spans: [span] }]
55
- }
56
- ]
57
- };
58
- };
59
-
60
- const pushAttribute = (attributes, key, value) => {
61
- if (value === void 0 || value === null) {
62
- return;
63
- }
64
- if (typeof value === "boolean" || typeof value === "number" || typeof value === "string") {
65
- attributes.push(encodeAttribute(key, value));
66
- return;
67
- }
68
- attributes.push(encodeAttribute(key, JSON.stringify(value)));
69
- };
70
- const observeSettled = (promise, onSettle) => {
71
- const run = async () => {
72
- let result;
73
- try {
74
- result = await promise;
75
- } catch (error) {
76
- onSettle(false, error instanceof Error ? error.message : String(error), void 0);
77
- return;
78
- }
79
- onSettle(true, void 0, result);
80
- };
81
- run().catch(() => void 0);
82
- };
83
- const otlpTelemetry = (options) => {
84
- const { conversationId, endpoint, headers, recordInputs = false, recordOutputs = false, token, traceId: fixedTraceId, waitUntil } = options;
85
- const serviceName = options.serviceName ?? "lunora";
86
- let base = endpoint;
87
- while (base.endsWith("/")) {
88
- base = base.slice(0, -1);
89
- }
90
- const tracesUrl = `${base}/v1/traces`;
91
- const mergedHeaders = mergeHeaders({ "content-type": "application/json" }, headers, token);
92
- const emitSpan = (name, startTs, ok, message, attributes) => {
93
- const span = {
94
- attributes,
95
- endTimeUnixNano: otlpUnixNano(Date.now()),
96
- // SPAN_KIND_INTERNAL — matches the runtime's `ctx.trace` spans.
97
- kind: 1,
98
- name,
99
- spanId: otlpRandomHex(8),
100
- startTimeUnixNano: otlpUnixNano(startTs),
101
- // STATUS_CODE_OK (1) / STATUS_CODE_ERROR (2).
102
- status: ok ? { code: 1 } : { code: 2, message: message ?? "" },
103
- traceId: fixedTraceId ?? otlpRandomHex(16)
104
- };
105
- try {
106
- const sent = fetch(tracesUrl, {
107
- body: JSON.stringify(wrapResourceSpans(span, "@lunora/agent", serviceName)),
108
- headers: mergedHeaders,
109
- method: "POST"
110
- }).catch(() => {
111
- });
112
- waitUntil?.(sent);
113
- } catch {
114
- }
115
- };
116
- return {
117
- executeLanguageModelCall: (options_) => {
118
- const startTs = Date.now();
119
- const modelId = readField(options_, "modelId");
120
- const promise = options_.execute();
121
- const emit = (ok, message, result) => {
122
- const attributes = [];
123
- pushAttribute(attributes, "gen_ai.operation.name", "chat");
124
- pushAttribute(attributes, "gen_ai.request.model", modelId);
125
- pushAttribute(attributes, "gen_ai.system", readField(options_, "provider"));
126
- pushAttribute(attributes, "gen_ai.conversation.id", conversationId);
127
- const usage = summarizeUsage(readField(result, "usage"));
128
- if (usage) {
129
- pushAttribute(attributes, "gen_ai.usage.input_tokens", usage.inputTokens);
130
- pushAttribute(attributes, "gen_ai.usage.output_tokens", usage.outputTokens);
131
- pushAttribute(attributes, "gen_ai.usage.total_tokens", usage.totalTokens);
132
- }
133
- const gateway = summarizeGatewayTelemetry(result);
134
- if (gateway) {
135
- pushAttribute(attributes, "gen_ai.usage.cost", gateway.cost);
136
- pushAttribute(attributes, "gen_ai.response.cached", gateway.cached);
137
- pushAttribute(attributes, "cf.aig.log_id", gateway.logId);
138
- }
139
- if (recordInputs) {
140
- pushAttribute(attributes, "gen_ai.prompt", readField(options_, "messages"));
141
- }
142
- if (recordOutputs) {
143
- pushAttribute(attributes, "gen_ai.completion", contentText(readField(result, "content")));
144
- }
145
- emitSpan(typeof modelId === "string" ? `chat ${modelId}` : "language_model_call", startTs, ok, message, attributes);
146
- };
147
- observeSettled(promise, emit);
148
- return promise;
149
- },
150
- executeTool: (options_) => {
151
- const startTs = Date.now();
152
- const toolName = toolNameOf(options_);
153
- const promise = options_.execute();
154
- const emit = (ok, message) => {
155
- const attributes = [];
156
- pushAttribute(attributes, "gen_ai.operation.name", "execute_tool");
157
- pushAttribute(attributes, "gen_ai.tool.name", toolName);
158
- pushAttribute(attributes, "gen_ai.tool.call.id", readField(options_, "toolCallId"));
159
- if (recordInputs) {
160
- pushAttribute(attributes, "gen_ai.tool.input", toolInputOf(options_));
161
- }
162
- emitSpan(typeof toolName === "string" ? `execute_tool ${toolName}` : "execute_tool", startTs, ok, message, attributes);
163
- };
164
- observeSettled(promise, emit);
165
- return promise;
166
- }
167
- };
168
- };
169
-
170
- export { otlpTelemetry };