@agimon-ai/po-log 0.0.0-alpha.21 → 0.0.0-alpha.211

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 (67) hide show
  1. package/LICENSE +21 -149
  2. package/README.md +4 -10
  3. package/dist/apiContracts.cjs +81 -57
  4. package/dist/apiContracts.cjs.map +1 -1
  5. package/dist/apiContracts.d.mts +2 -2
  6. package/dist/apiContracts.mjs +82 -58
  7. package/dist/apiContracts.mjs.map +1 -1
  8. package/dist/extensions/native.mjs +403 -0
  9. package/dist/extensions/native.mjs.map +1 -0
  10. package/dist/extensions/server.cjs +835 -296
  11. package/dist/extensions/server.cjs.map +1 -1
  12. package/dist/extensions/server.d.mts.map +1 -1
  13. package/dist/extensions/server.mjs +837 -298
  14. package/dist/extensions/server.mjs.map +1 -1
  15. package/dist/extensions/web.mjs +735 -300
  16. package/dist/extensions/web.mjs.map +1 -1
  17. package/dist/findings-Bo4IHNpr.cjs +165 -0
  18. package/dist/findings-Bo4IHNpr.cjs.map +1 -0
  19. package/dist/findings-DAKeRG4O.mjs +160 -0
  20. package/dist/findings-DAKeRG4O.mjs.map +1 -0
  21. package/dist/http-D7IHAk6Y.mjs +29 -0
  22. package/dist/http-D7IHAk6Y.mjs.map +1 -0
  23. package/dist/http-Dhn2bpMh.cjs +40 -0
  24. package/dist/http-Dhn2bpMh.cjs.map +1 -0
  25. package/dist/index.cjs +3 -2
  26. package/dist/index.d.mts +8 -2
  27. package/dist/index.d.mts.map +1 -1
  28. package/dist/index.mjs +3 -1
  29. package/dist/{metrics-jCZe13Xg.cjs → metrics-Bml7TSZq.cjs} +9 -160
  30. package/dist/metrics-Bml7TSZq.cjs.map +1 -0
  31. package/dist/{metrics-DywCpDJ_.mjs → metrics-DwfV84Fy.mjs} +2 -159
  32. package/dist/metrics-DwfV84Fy.mjs.map +1 -0
  33. package/dist/metrics.cjs +3 -2
  34. package/dist/metrics.mjs +3 -1
  35. package/dist/{metricsSource-Cy8f47Q0.cjs → metricsSource-CF3cp-sf.cjs} +16 -43
  36. package/dist/metricsSource-CF3cp-sf.cjs.map +1 -0
  37. package/dist/{metricsSource-BaoBR_Ia.mjs → metricsSource-I5p5_t2L.mjs} +9 -42
  38. package/dist/metricsSource-I5p5_t2L.mjs.map +1 -0
  39. package/dist/{metricsSource-DNT8BrTF.d.mts → metricsSource-sO8OpIes.d.mts} +14 -3
  40. package/dist/metricsSource-sO8OpIes.d.mts.map +1 -0
  41. package/dist/metricsSource.cjs +1 -1
  42. package/dist/metricsSource.d.mts +1 -13
  43. package/dist/metricsSource.d.mts.map +1 -1
  44. package/dist/metricsSource.mjs +1 -1
  45. package/dist/metricsStore-BcjSOJGN.mjs +44 -0
  46. package/dist/metricsStore-BcjSOJGN.mjs.map +1 -0
  47. package/dist/metricsStore-nGI-c5NH.cjs +79 -0
  48. package/dist/metricsStore-nGI-c5NH.cjs.map +1 -0
  49. package/dist/metricsStore.cjs +476 -0
  50. package/dist/metricsStore.cjs.map +1 -0
  51. package/dist/metricsStore.d.mts +63 -0
  52. package/dist/metricsStore.d.mts.map +1 -0
  53. package/dist/metricsStore.mjs +471 -0
  54. package/dist/metricsStore.mjs.map +1 -0
  55. package/dist/po-runtime-identity.json +1 -0
  56. package/llms.txt +5 -1
  57. package/locales/vi.json +202 -0
  58. package/locales/zh-CN.json +202 -0
  59. package/package.json +81 -18
  60. package/src/prompts/codemode-how-to-logsink/SKILL.md +80 -0
  61. package/src/prompts/help-how-to-log/SKILL.md +28 -0
  62. package/dist/metrics-DywCpDJ_.mjs.map +0 -1
  63. package/dist/metrics-jCZe13Xg.cjs.map +0 -1
  64. package/dist/metricsSource-BaoBR_Ia.mjs.map +0 -1
  65. package/dist/metricsSource-Cy8f47Q0.cjs.map +0 -1
  66. package/dist/metricsSource-DNT8BrTF.d.mts.map +0 -1
  67. package/src/prompts/po-debug-agent/SKILL.md +0 -28
@@ -1,26 +1,394 @@
1
- import { t as createMetricsSource } from "../metricsSource-BaoBR_Ia.mjs";
1
+ import { n as resolveMetricsEndpoint, t as createMetricsSource } from "../metricsSource-I5p5_t2L.mjs";
2
+ import { a as PO_LOG_METRICS_CONTRACT, r as PO_LOG_HOST_USAGE_CONTRACT, t as METRICS_ATTRIBUTE } from "../metricsStore-BcjSOJGN.mjs";
2
3
  import { createRequire } from "node:module";
3
- import { resolveLogSinkInstance } from "@agimon-ai/po-logsink";
4
- import { composeServerProviderOverrides, defineServerPlugin, defineTool, packageResourcePath, readPackageResource } from "@agimon-ai/po-core/serverPlugin";
4
+ import { createAsyncLogQueryReader, resolveGlobalLogQueryDbPath, resolveLogSinkInstance } from "@agimon-ai/po-logsink";
5
+ import { composeServerProviderOverrides, defineServerPlugin, defineTool, packageResourcePath, readPackageResource, readPoServerScope } from "@agimon-ai/po-core/serverPlugin";
5
6
  import { composeRootHooks, composeRootInjects, defineHook, defineResource, defineRoot, defineRoute, defineServerCommand, defineTool as defineTool$1 } from "@agimon-ai/po-core/extensionFile";
7
+ import { readPoChildSessionHookRegistry } from "@agimon-ai/po-core/childSession";
8
+ import { PO_CODEMODE_SERVICE, readPoCodemode } from "@agimon-ai/po-core/codemode";
9
+ import { readPoWorkflowContextService } from "@agimon-ai/po-core/workflow";
10
+ import { createPoTelemetry, sanitizeTelemetryAttributes } from "@agimon-ai/po-core/telemetry";
11
+ import { LOG_QUERY_INPUT_SCHEMAS, parseLogQueryInput } from "@agimon-ai/po-logsink/queryContracts";
12
+ import { Type } from "typebox";
13
+ import { readPoLang, readPoPersonLocale, translateMessage } from "@agimon-ai/po-core/locale";
6
14
  import { isRecord } from "@agimon-ai/po-core/runtimeJson";
7
- import { createPoTelemetry } from "@agimon-ai/po-telemetry";
8
15
  import { Hono } from "hono";
9
16
  import { execFile } from "node:child_process";
10
17
  import path from "node:path";
11
18
  import { apiResponse, defineApiRoutes } from "@agimon-ai/po-core/web";
12
19
  import { PO_HELP_WHEN } from "@agimon-ai/po-core/help";
13
- import { Check } from "typebox/value";
14
- import { Type } from "typebox";
15
20
  //#region src/constants/telemetry.ts
16
21
  const PACKAGE_NAME$1 = "@agimon-ai/po-log";
17
22
  //#endregion
23
+ //#region src/schemas/logsink.ts
24
+ const LOGSINK_METHODS = [
25
+ "status",
26
+ "search",
27
+ "agentIssues",
28
+ "trace",
29
+ "stats",
30
+ "services",
31
+ "metrics"
32
+ ];
33
+ const LOGSINK_TOOL_NAMES = LOGSINK_METHODS.map((method) => `logsink_${method.replace(/[A-Z]/g, (letter) => `_${letter.toLowerCase()}`)}`);
34
+ /** The direct tools advertise the same schema the reader validates, plus Po's scope selector. */
35
+ function logsinkParameters(method) {
36
+ const schema = LOG_QUERY_INPUT_SCHEMAS[method];
37
+ return Type.Unsafe({
38
+ ...schema,
39
+ properties: {
40
+ ...schema.properties,
41
+ ...method === "status" ? {} : { scope: {
42
+ type: "string",
43
+ enum: ["session", "history"],
44
+ description: "Defaults to this session. History requires explicit startTime and endTime."
45
+ } }
46
+ }
47
+ });
48
+ }
49
+ function parseLogsinkInput(method, value, sessionId) {
50
+ if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error("Log query input must be an object.");
51
+ const { scope: requestedScope, ...query } = value;
52
+ const storedSessionId = sanitizeTelemetryAttributes({ "pi.session.id": sessionId })["pi.session.id"];
53
+ if (typeof storedSessionId !== "string") throw new Error("Log queries require a valid session identity.");
54
+ if (method === "status") {
55
+ if (requestedScope !== void 0) throw new Error("status does not accept a scope.");
56
+ return {
57
+ scope: {
58
+ kind: "session",
59
+ sessionId: storedSessionId
60
+ },
61
+ input: parseLogQueryInput(method, query)
62
+ };
63
+ }
64
+ const kind = requestedScope ?? "session";
65
+ if (kind !== "session" && kind !== "history") throw new Error("scope must be session or history.");
66
+ if (kind === "session") {
67
+ if (query.sessionId !== void 0 && query.sessionId !== sessionId && query.sessionId !== storedSessionId) throw new Error("Use explicit history scope to query another session.");
68
+ query.sessionId = storedSessionId;
69
+ } else if (typeof query.startTime !== "string" || typeof query.endTime !== "string") throw new Error("History queries require explicit ISO startTime and endTime.");
70
+ const input = parseLogQueryInput(method, query);
71
+ const filters = input;
72
+ return {
73
+ scope: {
74
+ kind,
75
+ ...typeof filters.sessionId === "string" ? { sessionId: filters.sessionId } : {},
76
+ ...typeof filters.startTime === "string" ? { startTime: filters.startTime } : {},
77
+ ...typeof filters.endTime === "string" ? { endTime: filters.endTime } : {}
78
+ },
79
+ input
80
+ };
81
+ }
82
+ //#endregion
83
+ //#region src/services/logQuerySource/index.ts
84
+ /** The host supplies its home; inspection must not run the sink's directory-creating resolver. */
85
+ function createLogQuerySource(homeDirectory) {
86
+ if (!homeDirectory) throw new Error("Log queries require the host home directory.");
87
+ return createAsyncLogQueryReader({ dbPath: resolveGlobalLogQueryDbPath(homeDirectory) });
88
+ }
89
+ //#endregion
90
+ //#region src/services/logsink/index.ts
91
+ const DESCRIPTIONS = {
92
+ status: "Check whether retained Log Sink data is available without starting a collector.",
93
+ search: "Search retained logs with structured filters and optional FTS text.",
94
+ agentIssues: "Aggregate captured agent failures, then inspect bounded issue samples and coverage.",
95
+ trace: "Read a bounded chronological trace within the selected session or history scope.",
96
+ stats: "Aggregate retained log statistics within the selected scope.",
97
+ services: "List services with retained records within the selected scope.",
98
+ metrics: "Inspect captured token usage, tool turn costs, and failure metrics."
99
+ };
100
+ function createLogsinkOperations(options) {
101
+ return {
102
+ sessionId: options.sessionId,
103
+ async read(method, value = {}, inputSignal) {
104
+ const active = options.authorize(inputSignal);
105
+ const signal = AbortSignal.any([active, AbortSignal.timeout(25e3)]);
106
+ const parsed = parseLogsinkInput(method, value, options.sessionId);
107
+ signal.throwIfAborted();
108
+ const reader = options.createReader?.() ?? createLogQuerySource(options.homeDirectory);
109
+ let report;
110
+ try {
111
+ const data = method === "status" ? await reader.status(signal) : await reader[method](parsed.input, signal);
112
+ report = JSON.parse(JSON.stringify({
113
+ scope: parsed.scope,
114
+ data
115
+ }));
116
+ } finally {
117
+ await reader.close();
118
+ }
119
+ signal.throwIfAborted();
120
+ options.authorize(inputSignal);
121
+ return report;
122
+ }
123
+ };
124
+ }
125
+ function createLogsinkTool(method, operations) {
126
+ if (!operations) throw new Error("Log Sink tools require a session host.");
127
+ return defineTool({
128
+ name: LOGSINK_TOOL_NAMES[LOGSINK_METHODS.indexOf(method)],
129
+ description: `${DESCRIPTIONS[method]} Defaults to this session. Cross-session workflow analysis requires scope: history and explicit startTime/endTime.`,
130
+ parameters: logsinkParameters(method),
131
+ async execute(input, execution) {
132
+ const report = await operations.read(method, input, execution.signal);
133
+ return {
134
+ content: [{
135
+ type: "text",
136
+ text: JSON.stringify(report)
137
+ }],
138
+ details: report
139
+ };
140
+ }
141
+ });
142
+ }
143
+ //#endregion
144
+ //#region src/services/logsinkNamespace/index.ts
145
+ const DECLARATIONS = `interface LogScope { kind: 'session' | 'history'; sessionId?: string; startTime?: string; endTime?: string }
146
+ interface LogResponse<T> { scope: LogScope; data: T }
147
+ interface LogPage { offset: number; limit: number; hasMore: boolean; nextOffset: number | null }
148
+ interface LogFilters {
149
+ scope?: 'session' | 'history'; sessionId?: string; startTime?: string; endTime?: string;
150
+ workflowRunId?: string; workflowName?: string; jobName?: string; jobId?: string;
151
+ agentName?: string; workflowRunKey?: string; workflowWorkspace?: string; stepName?: string; phase?: string;
152
+ service?: string | string[];
153
+ }
154
+ interface LogAvailability { available: boolean; reason?: 'missing-database' }
155
+ interface LogRecord {
156
+ id: string; timestamp: string; level: string; service: string; message: string;
157
+ sessionId: string | null; traceId: string | null; spanId: string | null;
158
+ metadata: Record<string, unknown> | null; errorType: string | null; errorMessage: string | null;
159
+ [field: string]: unknown;
160
+ }
161
+ interface LogSearch { mode: 'filter' | 'fts'; count: number; total: number; truncated: boolean; results: LogRecord[]; pagination: LogPage }
162
+ interface LogIssue {
163
+ category: string; timestamp: string; service: string; sessionId: string | null; tool: string | null;
164
+ errorType: string | null; message: string; detail: string | null; fingerprint: string; occurrenceCount: number;
165
+ traceId: string | null; spanId: string | null; [field: string]: unknown;
166
+ }
167
+ interface LogIssues {
168
+ scanned: number; matchingLogs: number; truncated: boolean; coveragePercent: number; oldestScannedTimestamp: string | null;
169
+ totalIssues: number; uniqueIncidents: number; byCategory: Record<string, number>; byTool: Record<string, number>;
170
+ byErrorType: Record<string, number>; bySession: Record<string, number>; issues: LogIssue[]; pagination: LogPage;
171
+ }
172
+ interface LogTraceEntry { timestamp: string; service: string; spanId: string | null; parentSpanId: string | null; level: string; message: string; [field: string]: unknown }
173
+ interface LogTrace { traceId: string; count: number; truncated: boolean; timeline: LogTraceEntry[]; pagination: LogPage }
174
+ interface LogStats { groupBy: string; signalType: 'log' | 'span' | 'all'; totalEntries: number; statistics: { service: string; level: string; count: number }[]; pagination: LogPage }
175
+ interface LogServices { count: number; truncated: boolean; services: string[]; pagination: LogPage }
176
+ interface LogTokens {
177
+ inputTokens: number; totalPromptTokens: number; outputTokens: number; totalTokens: number;
178
+ cachedInputTokens: number; reasoningOutputTokens: number; usageEventCount: number;
179
+ /** Completed requests with explicit cache-read usage. */
180
+ requestCache: { measuredRequests: number; hitRequests: number; totalPromptTokens: number; cachedInputTokens: number };
181
+ }
182
+ interface LogTokenDistribution { samples: number; avgInputTokens: number; p50InputTokens: number; p90InputTokens: number; avgOutputTokens: number; p50OutputTokens: number; p90OutputTokens: number; avgTotalTokens: number; p50TotalTokens: number; p90TotalTokens: number }
183
+ interface LogMetrics {
184
+ generatedAt: string; groupBy: string; sort: string; toolSort: string; period: string; bucket: string;
185
+ filters: Record<string, unknown>;
186
+ totals: LogTokens & { totalRecords: number; issueCount: number; groupCount: number; returnedGroups: number; tokenCoveragePercent: number; [field: string]: unknown };
187
+ groups: (LogTokens & { key: string; sessionId: string | null; issueCount: number; byCategory: Record<string, number>; [field: string]: unknown })[];
188
+ tools: { returnedTools: number; rows: { toolName: string; invocationCount: number; toolCallTurn: LogTokenDistribution; toolOutputImpact: LogTokenDistribution; [field: string]: unknown }[] };
189
+ timeline: (LogTokens & { bucketStart: string; label: string; totalRecords: number; issueCount: number })[];
190
+ pagination: { groups: LogPage; tools: LogPage; timeline: LogPage };
191
+ }
192
+ declare const logsink: {
193
+ /** Retained storage availability, not proof that the collector is capturing now. */
194
+ status(): Promise<LogResponse<LogAvailability>>;
195
+ /** Scoped structured query or FTS search. History requires explicit startTime/endTime. order is filter-only. Pages default to limit 100 (max 1000), offset 0. Continue with pagination.nextOffset and unchanged filters; live data is not a snapshot. Oversized results are refused: lower limits or narrow the window. */
196
+ search(input?: LogFilters & { query?: string; mode?: 'fts'; level?: string | string[]; traceId?: string; spanId?: string; errorType?: string; parentSessionId?: string; workflowId?: string; signalType?: 'log' | 'span'; limit?: number; offset?: number; order?: 'asc' | 'desc' }): Promise<LogResponse<LogSearch>>;
197
+ /** Pages deduplicated incidents, not scan coverage. Totals cover the whole bounded scan; truncated describes that scan. */
198
+ agentIssues(input?: LogFilters & { limit?: number; offset?: number; scanLimit?: number }): Promise<LogResponse<LogIssues>>;
199
+ /** A bounded trace page, filtered within scope before retrieval. */
200
+ trace(input: LogFilters & { traceId: string; limit?: number; offset?: number }): Promise<LogResponse<LogTrace>>;
201
+ /** Pages counts by level, service, agent, workflow, job or signal. totalEntries covers all matching groups. */
202
+ stats(input?: LogFilters & { groupBy?: 'level' | 'service' | 'both' | 'agent' | 'workflow' | 'job' | 'signal'; signalType?: 'log' | 'span' | 'all'; limit?: number; offset?: number }): Promise<LogResponse<LogStats>>;
203
+ /** Services that have retained records within scope, alphabetically paged. */
204
+ services(input?: LogFilters & { limit?: number; offset?: number }): Promise<LogResponse<LogServices>>;
205
+ /** Captured usage and tool turn costs, not exclusive per-tool token shares. Independently pages groups (limit/offset, default 50), tools (toolLimit/toolOffset, default 20), timeline (timelineLimit/timelineOffset, default 100). Totals cover the full scope. */
206
+ metrics(input?: LogFilters & { model?: string | string[]; provider?: string | string[]; groupBy?: 'session' | 'workflow-run' | 'workflow-name' | 'job' | 'step' | 'agent' | 'model' | 'provider'; sort?: 'last-seen' | 'total-tokens' | 'issues'; toolSort?: 'p90-total-tokens' | 'avg-total-tokens' | 'invocations'; limit?: number; offset?: number; toolLimit?: number; toolOffset?: number; timelineLimit?: number; timelineOffset?: number; period?: 'day' | 'week' | 'month' | 'all'; bucket?: 'hour' | 'day' | 'week' | 'month' }): Promise<LogResponse<LogMetrics>>;
207
+ };`;
208
+ const MAX_TRANSCRIPT_JSON = 12e3;
209
+ const TRANSCRIPT_LIST_SIZES = [
210
+ 20,
211
+ 5,
212
+ 0
213
+ ];
214
+ const RECORD_LISTS = /* @__PURE__ */ new Set([
215
+ "results",
216
+ "timeline",
217
+ "issues",
218
+ "groups",
219
+ "rows",
220
+ "statistics",
221
+ "services"
222
+ ]);
223
+ const RUN_DISPOSED = "Log Sink run is disposed.";
224
+ function cutLists(value, size) {
225
+ if (Array.isArray(value)) return value.map((item) => cutLists(item, size));
226
+ if (value === null || typeof value !== "object") return value;
227
+ return Object.fromEntries(Object.entries(value).map(([key, item]) => [key, RECORD_LISTS.has(key) && Array.isArray(item) ? item.slice(0, size) : cutLists(item, size)]));
228
+ }
229
+ /** The result as the transcript keeps it: whole when small, otherwise with record lists cut and a note. */
230
+ function transcriptCopy(result) {
231
+ const json = JSON.stringify(result);
232
+ if (json === void 0 || json.length <= MAX_TRANSCRIPT_JSON) return json === void 0 ? void 0 : JSON.parse(json);
233
+ for (const size of TRANSCRIPT_LIST_SIZES) {
234
+ const kept = {
235
+ ...cutLists(JSON.parse(json), size),
236
+ note: `Transcript copy keeps at most ${size} items per record list; the script received every record in the requested page.`
237
+ };
238
+ if (JSON.stringify(kept).length <= MAX_TRANSCRIPT_JSON) return kept;
239
+ }
240
+ }
241
+ function createLogsinkNamespace(operations) {
242
+ return {
243
+ name: "logsink",
244
+ summary: "Read captured log issues, metrics, traces and search results. Defaults to this session; explicit bounded history supports workflow analysis. Read-only, never manages the collector.",
245
+ declarations: DECLARATIONS,
246
+ portable: true,
247
+ bind(run) {
248
+ if (run.sessionId !== operations.sessionId) throw new Error("Log Sink namespace belongs to another session.");
249
+ let disposed = false;
250
+ const controller = new AbortController();
251
+ run.onDispose(() => {
252
+ disposed = true;
253
+ controller.abort(/* @__PURE__ */ new Error(RUN_DISPOSED));
254
+ });
255
+ const signal = AbortSignal.any([run.signal, controller.signal]);
256
+ const check = () => {
257
+ signal.throwIfAborted();
258
+ if (disposed) throw new Error(RUN_DISPOSED);
259
+ };
260
+ const members = Object.create(null);
261
+ for (const method of LOGSINK_METHODS) members[method] = async (input = {}) => {
262
+ const started = Date.now();
263
+ let args = {};
264
+ let result;
265
+ try {
266
+ check();
267
+ const snapshot = JSON.parse(JSON.stringify(input));
268
+ if (snapshot && typeof snapshot === "object" && !Array.isArray(snapshot)) args = snapshot;
269
+ result = await operations.read(method, input, signal);
270
+ check();
271
+ } catch (error) {
272
+ const message = error instanceof Error ? error.message : String(error);
273
+ run.record?.({
274
+ name: `logsink.${method}`,
275
+ tool: LOGSINK_TOOL_NAMES[LOGSINK_METHODS.indexOf(method)],
276
+ args,
277
+ ok: false,
278
+ ms: Date.now() - started,
279
+ error: message,
280
+ result: { content: [{
281
+ type: "text",
282
+ text: message
283
+ }] }
284
+ });
285
+ throw error;
286
+ }
287
+ const details = transcriptCopy(result);
288
+ run.record?.({
289
+ name: `logsink.${method}`,
290
+ tool: LOGSINK_TOOL_NAMES[LOGSINK_METHODS.indexOf(method)],
291
+ args,
292
+ ok: true,
293
+ ms: Date.now() - started,
294
+ result: {
295
+ content: [{
296
+ type: "text",
297
+ text: details === void 0 ? "[log result too large to keep]" : JSON.stringify(details)
298
+ }],
299
+ details
300
+ }
301
+ });
302
+ return result;
303
+ };
304
+ return members;
305
+ }
306
+ };
307
+ }
308
+ //#endregion
309
+ //#region src/services/metricsForwarder/index.ts
310
+ const RECORD_FAILED = "Metrics could not be recorded.";
311
+ const METRICS_ENTRY_ATTRIBUTES = new Set(Object.values(METRICS_ATTRIBUTE));
312
+ /** Only the fixed, scalar attributes a metrics entry may carry leave the session. */
313
+ function fixedAttributes(attributes) {
314
+ const kept = {};
315
+ for (const [key, value] of Object.entries(attributes)) {
316
+ if (!METRICS_ENTRY_ATTRIBUTES.has(key)) continue;
317
+ if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") kept[key] = value;
318
+ }
319
+ return kept;
320
+ }
321
+ /**
322
+ * Hands a session's sanitized telemetry records to the metrics service a host bound, in batches.
323
+ *
324
+ * A host that bound none, such as one that keeps the log sink, queues nothing. Records made in the same tick
325
+ * travel together, so a session pays one call for a turn rather than one per record.
326
+ */
327
+ function createMetricsForwarder(options) {
328
+ const now = options.now ?? Date.now;
329
+ let waiting = [];
330
+ let scheduled = false;
331
+ const flush = async () => {
332
+ scheduled = false;
333
+ const batch = waiting;
334
+ waiting = [];
335
+ if (batch.length === 0) return;
336
+ const service = options.resolve();
337
+ if (service === void 0) return;
338
+ for (let start = 0; start < batch.length; start += 500) try {
339
+ await service.record(batch.slice(start, start + 500));
340
+ } catch {
341
+ options.onDiagnostic?.(RECORD_FAILED);
342
+ }
343
+ };
344
+ return {
345
+ record(name, attributes) {
346
+ if (options.resolve() === void 0) return;
347
+ waiting.push({
348
+ at: now(),
349
+ event: name,
350
+ attributes: fixedAttributes(attributes)
351
+ });
352
+ if (scheduled) return;
353
+ scheduled = true;
354
+ queueMicrotask(() => {
355
+ flush().catch(() => options.onDiagnostic?.(RECORD_FAILED));
356
+ });
357
+ },
358
+ flush
359
+ };
360
+ }
361
+ //#endregion
18
362
  //#region src/services/telemetryEnabled/index.ts
19
363
  function isEnabled(value) {
20
364
  return value === "1" || value?.toLowerCase() === "true" || value?.toLowerCase() === "yes";
21
365
  }
22
366
  //#endregion
23
367
  //#region src/services/serverTelemetry/index.ts
368
+ /** A reason is a fixed token such as an error class or code, never free text that could carry output. */
369
+ const FAILURE_REASON_PATTERN = /^[A-Za-z][A-Za-z0-9_]{0,63}$/u;
370
+ /** Export only fixed categories from structured tool details, never displayed output. */
371
+ function failureAttributes(result) {
372
+ if (!result || typeof result !== "object" || !("details" in result)) return {};
373
+ const details = result.details;
374
+ if (!details || typeof details !== "object") return {};
375
+ const failure = "failure" in details ? details.failure : void 0;
376
+ const kind = failure && typeof failure === "object" && "kind" in failure ? failure.kind : void 0;
377
+ const reason = failure && typeof failure === "object" && "reason" in failure ? failure.reason : void 0;
378
+ return {
379
+ ...typeof kind === "string" && [
380
+ "timeout",
381
+ "exit_code",
382
+ "not_found",
383
+ "permission",
384
+ "validation",
385
+ "aborted",
386
+ "unknown"
387
+ ].includes(kind) ? { "failure.kind": kind } : {},
388
+ ...typeof reason === "string" && FAILURE_REASON_PATTERN.test(reason) ? { "failure.reason": reason } : {},
389
+ ..."exit_code" in details && typeof details.exit_code === "number" && Number.isFinite(details.exit_code) ? { exit_code: details.exit_code } : {}
390
+ };
391
+ }
24
392
  function contextAttributes(execution) {
25
393
  return {
26
394
  "pi.mode": "json",
@@ -50,7 +418,38 @@ function usageAttributes(message) {
50
418
  if (typeof cost === "number" && Number.isFinite(cost) && cost >= 0) attributes["gen_ai.usage.cost"] = cost;
51
419
  return attributes;
52
420
  }
53
- function createServerTelemetry(options = {}) {
421
+ async function shortHash(value) {
422
+ if (value === void 0) return void 0;
423
+ const bytes = new TextEncoder().encode(typeof value === "string" ? value : JSON.stringify(value));
424
+ const digest = new Uint8Array(await globalThis.crypto.subtle.digest("SHA-256", bytes));
425
+ return Array.from(digest.subarray(0, 6), (byte) => byte.toString(16).padStart(2, "0")).join("");
426
+ }
427
+ /** Cache-identity fingerprints of a Responses payload: which of key, instructions, or tools changed. Never content. */
428
+ async function requestShapeAttributes(payload) {
429
+ const attributes = {
430
+ "pi.request.cache_key_version": await shortHash(payload.prompt_cache_key),
431
+ "pi.request.instructions_version": await shortHash(payload.instructions ?? payload.system),
432
+ "pi.request.tools_version": await shortHash(payload.tools),
433
+ "pi.request.wire_model": typeof payload.model === "string" ? payload.model : void 0,
434
+ "pi.request.input_count": Array.isArray(payload.input) ? payload.input.length : void 0,
435
+ "pi.request.tool_count": Array.isArray(payload.tools) ? payload.tools.length : void 0
436
+ };
437
+ for (const key of Object.keys(attributes)) if (attributes[key] === void 0) delete attributes[key];
438
+ return attributes;
439
+ }
440
+ function createServerTelemetry(options = {}, localizationContext) {
441
+ const t = (key, fallback, vars) => (localizationContext ? readPoLang(localizationContext)?.t(readPoPersonLocale(localizationContext)?.read(), key, fallback, vars) : void 0) ?? translateMessage({}, void 0, key, fallback, vars);
442
+ const workflow = options.workflowContext;
443
+ const workflowAttributes = workflow === void 0 ? {} : {
444
+ "agent.parent_session.id": workflow.run.ownerSessionId,
445
+ "workflow.run.id": workflow.run.runId,
446
+ "workflow.run.key": workflow.run.runKey,
447
+ "workflow.job.name": workflow.job,
448
+ "workflow.step.name": workflow.step,
449
+ "workflow.step.attempt": workflow.attempt
450
+ };
451
+ let sessionTrace;
452
+ let turnTrace;
54
453
  let active = false;
55
454
  let finished = false;
56
455
  let queue = Promise.resolve();
@@ -58,11 +457,19 @@ function createServerTelemetry(options = {}) {
58
457
  let thinkingLevel;
59
458
  const sessionAttributes = (execution) => ({
60
459
  ...contextAttributes(execution),
460
+ ...workflowAttributes,
61
461
  ...thinkingLevel ? { "pi.thinking_level": thinkingLevel } : {}
62
462
  });
463
+ const diagnose = () => {
464
+ try {
465
+ options.onDiagnostic?.("Telemetry operation failed");
466
+ } catch (error) {
467
+ console.warn(`po-log telemetry diagnostic failed (${error instanceof Error ? error.name : typeof error})`);
468
+ }
469
+ };
63
470
  const enqueue = (operation) => {
64
471
  const pending = queue.then(operation);
65
- queue = pending.catch((error) => options.onDiagnostic?.(String(error)));
472
+ queue = pending.catch(diagnose);
66
473
  return pending;
67
474
  };
68
475
  let telemetry;
@@ -70,6 +477,67 @@ function createServerTelemetry(options = {}) {
70
477
  const tools = /* @__PURE__ */ new Map();
71
478
  let agentStartedAt;
72
479
  let turnIndex = 0;
480
+ const childDisposals = /* @__PURE__ */ new Set();
481
+ const childHooks = { bind(scope) {
482
+ let disposed = false;
483
+ let completion;
484
+ let laneTrace;
485
+ let parentTrace;
486
+ const attributes = () => ({
487
+ ...workflowAttributes,
488
+ "agent.parent_session.id": scope.request.parentSessionId,
489
+ "agent.child.run.id": scope.request.runId,
490
+ ...scope.sessionId() === void 0 ? {} : { "pi.session.id": scope.sessionId() }
491
+ });
492
+ const record = (name, extra = {}) => enqueue(async () => {
493
+ const current = telemetry;
494
+ if (!current) return;
495
+ if (name === "pi.child.started") parentTrace = turnTrace ?? sessionTrace;
496
+ const metadata = {
497
+ ...attributes(),
498
+ ...extra
499
+ };
500
+ await current.runInSpan(name, metadata, async (trace) => {
501
+ if (name === "pi.child.started") laneTrace = trace;
502
+ await current.recordEvent(name, metadata);
503
+ }, laneTrace ?? parentTrace);
504
+ }).catch(() => void 0);
505
+ const dispose = () => {
506
+ if (completion) return completion;
507
+ disposed = true;
508
+ scope.signal.removeEventListener("abort", onAbort);
509
+ childDisposals.delete(dispose);
510
+ completion = active ? record("pi.child.finished") : Promise.resolve();
511
+ return completion;
512
+ };
513
+ const onAbort = () => {
514
+ dispose();
515
+ };
516
+ if (active) {
517
+ childDisposals.add(dispose);
518
+ record("pi.child.started");
519
+ scope.signal.addEventListener("abort", onAbort, { once: true });
520
+ if (scope.signal.aborted) onAbort();
521
+ }
522
+ return {
523
+ beforeTool(event) {
524
+ if (active && !disposed) record("pi.child.tool_call", {
525
+ "tool.name": event.toolName,
526
+ "tool.call.id": event.toolCallId
527
+ });
528
+ },
529
+ afterTool(event) {
530
+ if (active && !disposed) record("pi.child.tool_result", {
531
+ "tool.name": event.toolName,
532
+ "tool.call.id": event.toolCallId,
533
+ success: !event.isError,
534
+ "tool.result.error": event.isError === true,
535
+ ...failureAttributes(event)
536
+ });
537
+ },
538
+ dispose
539
+ };
540
+ } };
73
541
  const activity = {
74
542
  name: PACKAGE_NAME$1,
75
543
  start(execution) {
@@ -79,7 +547,8 @@ function createServerTelemetry(options = {}) {
79
547
  cwd: execution.cwd,
80
548
  env: {
81
549
  ...options.env ?? execution.environment,
82
- PI_SESSION_ID: execution.sessionId
550
+ AGENT_SESSION_ID: execution.sessionId,
551
+ PO_SESSION_ID: execution.sessionId
83
552
  },
84
553
  allowFileFallback: options.allowFileFallback,
85
554
  telemetryFactory: options.telemetryFactory,
@@ -100,7 +569,19 @@ function createServerTelemetry(options = {}) {
100
569
  telemetry = current;
101
570
  active = true;
102
571
  finished = false;
572
+ let registration;
573
+ try {
574
+ registration = options.childSessionHookRegistry?.register(childHooks);
575
+ } catch {
576
+ diagnose();
577
+ }
103
578
  return () => disposal ??= (async () => {
579
+ try {
580
+ registration?.dispose();
581
+ } catch {
582
+ diagnose();
583
+ }
584
+ for (const dispose of childDisposals) dispose();
104
585
  active = false;
105
586
  await queue;
106
587
  if (telemetry === current) {
@@ -118,7 +599,11 @@ function createServerTelemetry(options = {}) {
118
599
  description: "Show headless telemetry sink status.",
119
600
  async execute(_args, execution) {
120
601
  await execution.client.notify({
121
- title: "Po telemetry",
602
+ title: t("log.notice.telemetryTitle", "Po telemetry"),
603
+ localization: { title: {
604
+ key: "log.notice.telemetryTitle",
605
+ fallback: "Po telemetry"
606
+ } },
122
607
  body: JSON.stringify(telemetry?.status() ?? { active: false }, null, 2),
123
608
  level: "info"
124
609
  });
@@ -193,8 +678,10 @@ function createServerTelemetry(options = {}) {
193
678
  if (message?.stopReason === "error" || message?.stopReason === "aborted") {
194
679
  const failure = {
195
680
  ...attributes,
196
- "error.type": "ProviderError",
197
- "error.code": message.stopReason,
681
+ ...message.stopReason === "error" ? {
682
+ "error.type": "ProviderError",
683
+ "error.code": "error"
684
+ } : {},
198
685
  outcome: message.stopReason === "aborted" ? "aborted" : "error"
199
686
  };
200
687
  if (message.stopReason === "aborted") await current.recordWarning("pi.turn.failed", void 0, failure);
@@ -231,6 +718,7 @@ function createServerTelemetry(options = {}) {
231
718
  "tool.call.id": event.toolCallId,
232
719
  success: event.isError !== true,
233
720
  "tool.result.error": event.isError === true,
721
+ ...failureAttributes(event.result),
234
722
  ...typeof duration === "number" ? { "tool.duration_ms": duration } : {}
235
723
  });
236
724
  if (typeof event.toolCallId === "string" && event.toolCallId.startsWith("external-")) await current.flush();
@@ -295,14 +783,39 @@ function createServerTelemetry(options = {}) {
295
783
  }
296
784
  return enqueue(async () => {
297
785
  thinkingLevel = (await execution.session?.readModelSettings?.())?.thinkingLevel;
298
- await handle({
299
- ...event,
300
- turnIndex: index,
301
- telemetryDurationMs: duration
302
- }, execution);
786
+ const current = telemetry;
787
+ if (!current) return;
788
+ const parent = hook.event === "session_start" ? workflow?.traceparent ? { traceparent: workflow.traceparent } : void 0 : hook.event.startsWith("tool_execution_") ? turnTrace ?? sessionTrace : sessionTrace;
789
+ await current.runInSpan(`pi.${hook.event}`, sessionAttributes(execution), async (trace) => {
790
+ if (hook.event === "session_start") sessionTrace = trace;
791
+ if (hook.event === "turn_start") turnTrace = trace;
792
+ await handle({
793
+ ...event,
794
+ turnIndex: index,
795
+ telemetryDurationMs: duration
796
+ }, execution);
797
+ }, parent);
798
+ if (hook.event === "turn_end") turnTrace = void 0;
303
799
  });
304
800
  };
305
801
  }
802
+ hooks.push({
803
+ event: "before_provider_request",
804
+ handle(event, execution) {
805
+ if (!active || !isRecord(event.payload)) return;
806
+ const payload = { ...event.payload };
807
+ const model = event.model;
808
+ enqueue(async () => {
809
+ await telemetry?.recordDebug("pi.provider.request", {
810
+ ...sessionAttributes(execution),
811
+ "gen_ai.provider.name": model.provider,
812
+ "gen_ai.request.model": model.id,
813
+ ...model.api === void 0 ? {} : { "pi.request.api_type": model.api },
814
+ ...await requestShapeAttributes(payload)
815
+ });
816
+ }).catch(() => void 0);
817
+ }
818
+ });
306
819
  return {
307
820
  activities: [activity],
308
821
  commands: [command],
@@ -311,62 +824,53 @@ function createServerTelemetry(options = {}) {
311
824
  }
312
825
  //#endregion
313
826
  //#region src/extensions/workspaces/sessions/(backend)/_lib/serverRoot.ts
314
- const createLogServerRoot = () => {
315
- const runtime = createServerTelemetry();
827
+ const createLogServerRoot = ({ context, agent, host, signal: ownerSignal }) => {
828
+ const metrics = createMetricsForwarder({
829
+ resolve: () => readPoServerScope(context)?.resolve(PO_LOG_METRICS_CONTRACT),
830
+ onDiagnostic: (message) => host.context.onNotice(message)
831
+ });
832
+ const runtime = createServerTelemetry({
833
+ workflowContext: readPoWorkflowContextService(context),
834
+ childSessionHookRegistry: readPoChildSessionHookRegistry(context),
835
+ metrics
836
+ }, context);
837
+ const sessionId = agent?.context.sessionId;
838
+ const logQueries = agent && sessionId ? createLogsinkOperations({
839
+ sessionId,
840
+ homeDirectory: host.context.homeDirectory,
841
+ authorize(signal) {
842
+ ownerSignal.throwIfAborted();
843
+ signal?.throwIfAborted();
844
+ agent.assertActive(PACKAGE_NAME$1);
845
+ if (agent.context.sessionId !== sessionId) throw new Error("Log Sink session changed.");
846
+ return signal ? AbortSignal.any([ownerSignal, signal]) : ownerSignal;
847
+ }
848
+ }) : void 0;
316
849
  return {
317
- value: runtime,
318
- activities: runtime.activities
850
+ value: {
851
+ ...runtime,
852
+ logQueries
853
+ },
854
+ activities: runtime.activities,
855
+ services: logQueries ? [(cordis) => {
856
+ cordis.inject([PO_CODEMODE_SERVICE], (scoped) => {
857
+ const codemode = readPoCodemode(scoped);
858
+ if (!codemode) return void 0;
859
+ const registration = codemode.register(PACKAGE_NAME$1, createLogsinkNamespace(logQueries));
860
+ const restriction = agent?.registerToolRestriction({ excludedTools: LOGSINK_TOOL_NAMES });
861
+ return () => {
862
+ restriction?.dispose();
863
+ registration.dispose();
864
+ };
865
+ });
866
+ }] : []
319
867
  };
320
868
  };
321
869
  //#endregion
322
870
  //#region src/extensions/workspaces/sessions/(backend)/root.server.ts
323
871
  var root_server_default = defineRoot(createLogServerRoot);
324
872
  //#endregion
325
- //#region src/services/issuesSource/index.ts
326
- /**
327
- * Agent-issue analysis over the sink's CLI.
328
- *
329
- * One transport, not two, because the daemon serves only /api/metrics and
330
- * /api/logs: there is no issues route to prefer. Every call is a subprocess,
331
- * which is why the page asks for this only when a reader opens the section
332
- * rather than alongside each report.
333
- */
334
- const PACKAGE_NAME = "@agimon-ai/po-logsink";
335
- const CLI_TIMEOUT_MS = 6e4;
336
- /** The analysis scans the whole window, so its output is larger than a metrics report. */
337
- const MAX_CLI_BUFFER = 33554432;
338
- function cliEntryPoint() {
339
- const packageJson = createRequire(import.meta.url).resolve(`${PACKAGE_NAME}/package.json`);
340
- return path.join(path.dirname(packageJson), "dist", "cli.mjs");
341
- }
342
- function runCli(params, dbPath) {
343
- return new Promise((resolve, reject) => {
344
- execFile(process.execPath, [
345
- cliEntryPoint(),
346
- "logs",
347
- "agent-issues",
348
- "--limit",
349
- String(params.limit),
350
- ...params.sessionId === void 0 ? [] : ["--session-id", params.sessionId],
351
- ...params.startTime === void 0 ? [] : ["--start-time", params.startTime],
352
- ...params.endTime === void 0 ? [] : ["--end-time", params.endTime],
353
- ...dbPath === void 0 ? [] : ["--db-path", dbPath]
354
- ], {
355
- timeout: CLI_TIMEOUT_MS,
356
- maxBuffer: MAX_CLI_BUFFER
357
- }, (error, stdout, stderr) => {
358
- if (error) {
359
- reject(new Error(stderr.trim() || error.message));
360
- return;
361
- }
362
- try {
363
- resolve(JSON.parse(stdout));
364
- } catch {
365
- reject(/* @__PURE__ */ new Error("The log sink returned output this version cannot read."));
366
- }
367
- });
368
- });
369
- }
873
+ //#region src/services/issuesSource/report.ts
370
874
  function isRecord$1(value) {
371
875
  return typeof value === "object" && value !== null && !Array.isArray(value);
372
876
  }
@@ -415,6 +919,52 @@ function toReport$1(raw) {
415
919
  samples
416
920
  };
417
921
  }
922
+ //#endregion
923
+ //#region src/services/issuesSource/index.ts
924
+ /**
925
+ * Agent-issue analysis over the sink's CLI.
926
+ *
927
+ * One transport, not two, because the daemon serves only /api/metrics and
928
+ * /api/logs: there is no issues route to prefer. Every call is a subprocess,
929
+ * which is why the page asks for this only when a reader opens the section
930
+ * rather than alongside each report.
931
+ */
932
+ const PACKAGE_NAME = "@agimon-ai/po-logsink";
933
+ const CLI_TIMEOUT_MS = 6e4;
934
+ /** The analysis scans the whole window, so its output is larger than a metrics report. */
935
+ const MAX_CLI_BUFFER = 33554432;
936
+ function cliEntryPoint() {
937
+ const packageJson = createRequire(import.meta.url).resolve(`${PACKAGE_NAME}/package.json`);
938
+ return path.join(path.dirname(packageJson), "dist", "cli.mjs");
939
+ }
940
+ function runCli(params, dbPath) {
941
+ return new Promise((resolve, reject) => {
942
+ execFile(process.execPath, [
943
+ cliEntryPoint(),
944
+ "logs",
945
+ "agent-issues",
946
+ "--limit",
947
+ String(params.limit),
948
+ ...params.sessionId === void 0 ? [] : ["--session-id", params.sessionId],
949
+ ...params.startTime === void 0 ? [] : ["--start-time", params.startTime],
950
+ ...params.endTime === void 0 ? [] : ["--end-time", params.endTime],
951
+ ...dbPath === void 0 ? [] : ["--db-path", dbPath]
952
+ ], {
953
+ timeout: CLI_TIMEOUT_MS,
954
+ maxBuffer: MAX_CLI_BUFFER
955
+ }, (error, stdout, stderr) => {
956
+ if (error) {
957
+ reject(new Error(stderr.trim() || error.message));
958
+ return;
959
+ }
960
+ try {
961
+ resolve(JSON.parse(stdout));
962
+ } catch {
963
+ reject(/* @__PURE__ */ new Error("The log sink returned output this version cannot read."));
964
+ }
965
+ });
966
+ });
967
+ }
418
968
  function createIssuesSource(options = {}) {
419
969
  const instance = resolveLogSinkInstance({
420
970
  env: options.env,
@@ -474,7 +1024,7 @@ function isMetricsPeriod(value) {
474
1024
  * This is the one file the routes, the Hono app and the browser all read, so a
475
1025
  * path cannot move on one side alone.
476
1026
  */
477
- var apiRoutes_default = defineApiRoutes({
1027
+ const routes = defineApiRoutes({
478
1028
  metrics: {
479
1029
  method: "GET",
480
1030
  path: "/metrics",
@@ -495,6 +1045,21 @@ var apiRoutes_default = defineApiRoutes({
495
1045
  path: "/issues",
496
1046
  query: [METRICS_QUERY_PARAMS.focus],
497
1047
  response: apiResponse()
1048
+ },
1049
+ /** The resources the host meters for its own account. Empty on a host that meters none. */
1050
+ usage: {
1051
+ method: "GET",
1052
+ path: "/usage",
1053
+ response: apiResponse()
1054
+ },
1055
+ /**
1056
+ * OTLP/JSON logs from clients that run no collector of their own, such as the
1057
+ * native app. Forwarded unchanged to the sink, which validates and redacts.
1058
+ */
1059
+ ingestLogs: {
1060
+ method: "POST",
1061
+ path: "/v1/logs",
1062
+ response: apiResponse()
498
1063
  }
499
1064
  });
500
1065
  //#endregion
@@ -513,6 +1078,9 @@ var apiRoutes_default = defineApiRoutes({
513
1078
  */
514
1079
  const DEFAULT_DIMENSION = "model";
515
1080
  const DEFAULT_PERIOD = "week";
1081
+ /** A client batch is a few dozen truncated records; the sink's own 5 MiB cap is for local exporters. */
1082
+ const MAX_INGEST_BYTES = 1048576;
1083
+ const FORWARD_TIMEOUT_MS = 5e3;
516
1084
  /** The sink groups sessions under a different name than the page's dimension. */
517
1085
  const SINK_GROUP_BY = {
518
1086
  session: "session",
@@ -619,6 +1187,25 @@ function toReport(report, source, dimension) {
619
1187
  function isEmpty(report) {
620
1188
  return report.totals.totalTokens === 0 && report.groups.length === 0 && report.tools.length === 0;
621
1189
  }
1190
+ /**
1191
+ * A bound store answers before any sink is looked for. It claims no transport: it is neither the sink's HTTP
1192
+ * API nor its worker. The store is looked up on every query, because a host binds it after this API starts.
1193
+ */
1194
+ function preferBound(bound, sink) {
1195
+ let answeredByStore = false;
1196
+ return {
1197
+ async query(params) {
1198
+ const store = bound();
1199
+ answeredByStore = store !== void 0;
1200
+ return store === void 0 ? sink.query(params) : store.query(params);
1201
+ },
1202
+ lastTransport: () => answeredByStore ? void 0 : sink.lastTransport(),
1203
+ instance: () => sink.instance?.(),
1204
+ close: async () => {
1205
+ await sink.close?.();
1206
+ }
1207
+ };
1208
+ }
622
1209
  function createLogHubApi(options = {}) {
623
1210
  const app = new Hono();
624
1211
  const identity = {
@@ -626,9 +1213,12 @@ function createLogHubApi(options = {}) {
626
1213
  serviceName: "pi",
627
1214
  ...options.env === void 0 ? {} : { env: options.env }
628
1215
  };
629
- const source = options.source ?? createMetricsSource(identity);
1216
+ const sink = options.source ?? createMetricsSource(identity);
1217
+ const source = options.metrics === void 0 ? sink : preferBound(options.metrics, sink);
630
1218
  const issues = options.issues ?? createIssuesSource(identity);
631
- app.get(apiRoutes_default.metrics.path, async (context) => {
1219
+ const fetchImpl = options.fetchImpl ?? globalThis.fetch;
1220
+ const sinkEndpoint = options.sinkEndpoint ?? (() => resolveMetricsEndpoint(identity));
1221
+ app.get(routes.metrics.path, async (context) => {
632
1222
  const requestedDimension = context.req.query(METRICS_QUERY_PARAMS.dimension) ?? DEFAULT_DIMENSION;
633
1223
  const requestedPeriod = context.req.query(METRICS_QUERY_PARAMS.period) ?? DEFAULT_PERIOD;
634
1224
  if (!isMetricsDimension(requestedDimension)) return context.json({ error: `Unknown dimension '${requestedDimension}'.` }, 400);
@@ -664,7 +1254,7 @@ function createLogHubApi(options = {}) {
664
1254
  * folding it into every report would make the whole page as slow as its
665
1255
  * slowest transport.
666
1256
  */
667
- app.get(apiRoutes_default.issues.path, async (context) => {
1257
+ app.get(routes.issues.path, async (context) => {
668
1258
  const focus = context.req.query(METRICS_QUERY_PARAMS.focus);
669
1259
  const startTime = context.req.query("startTime");
670
1260
  const endTime = context.req.query("endTime");
@@ -686,275 +1276,215 @@ function createLogHubApi(options = {}) {
686
1276
  return context.json(unavailable);
687
1277
  }
688
1278
  });
1279
+ app.get(routes.usage.path, async (context) => {
1280
+ try {
1281
+ const rows = await options.usage?.()?.read() ?? [];
1282
+ return context.json({ rows });
1283
+ } catch (error) {
1284
+ return context.json({ error: error instanceof Error ? error.message : "The usage read failed." }, 502);
1285
+ }
1286
+ });
1287
+ /**
1288
+ * Logs from clients with no collector of their own. The sink validates,
1289
+ * redacts and rate-limits OTLP itself, so this only bounds the size and
1290
+ * forwards; it never parses or rewrites records.
1291
+ */
1292
+ app.post(routes.ingestLogs.path, async (context) => {
1293
+ if (Number(context.req.header("content-length") ?? 0) > MAX_INGEST_BYTES) return context.json({ error: "Log batch is too large." }, 413);
1294
+ const body = await context.req.text();
1295
+ if (new TextEncoder().encode(body).byteLength > MAX_INGEST_BYTES) return context.json({ error: "Log batch is too large." }, 413);
1296
+ let response;
1297
+ try {
1298
+ const endpoint = await sinkEndpoint();
1299
+ if (endpoint === void 0) return context.json({ error: "The log sink is not running." }, 503);
1300
+ response = await fetchImpl(`${endpoint}/v1/logs`, {
1301
+ method: "POST",
1302
+ headers: { "content-type": "application/json" },
1303
+ body,
1304
+ signal: AbortSignal.timeout(FORWARD_TIMEOUT_MS)
1305
+ });
1306
+ } catch (error) {
1307
+ return context.json({ error: error instanceof Error ? error.message : "The log sink did not answer." }, 503);
1308
+ }
1309
+ if (response.ok) return context.json({ ok: true });
1310
+ const error = `The log sink refused the batch (${response.status}).`;
1311
+ if (response.status === 413) return context.json({ error }, 413);
1312
+ return context.json({ error }, response.status >= 500 ? 502 : 400);
1313
+ });
689
1314
  return app;
690
1315
  }
1316
+ /**
1317
+ * The package's API for a host. `metrics` resolves the store the host bound, if any, so a host that keeps its
1318
+ * own metrics answers from them and every other host keeps answering from the log sink.
1319
+ */
1320
+ function createLogApi(metrics, usage) {
1321
+ return {
1322
+ basePath: "log",
1323
+ start(context) {
1324
+ const env = { ...context.environment };
1325
+ const source = createMetricsSource({
1326
+ env,
1327
+ packageName: PACKAGE_NAME$1,
1328
+ serviceName: "pi"
1329
+ });
1330
+ const app = createLogHubApi({
1331
+ source,
1332
+ env,
1333
+ ...metrics === void 0 ? {} : { metrics },
1334
+ ...usage === void 0 ? {} : { usage }
1335
+ });
1336
+ return {
1337
+ fetch: (request) => app.fetch(request),
1338
+ close: () => source.close?.()
1339
+ };
1340
+ }
1341
+ };
1342
+ }
691
1343
  //#endregion
692
1344
  //#region src/extensions/(backend)/api/log/route.server.ts
693
- var route_server_default = defineRoute({
694
- basePath: "log",
695
- start(context) {
696
- const env = { ...context.environment };
697
- const source = createMetricsSource({
698
- env,
699
- packageName: PACKAGE_NAME$1,
700
- serviceName: "pi"
701
- });
702
- const app = createLogHubApi({
703
- source,
704
- env
705
- });
706
- return {
707
- fetch: (request) => app.fetch(request),
708
- close: () => source.close?.()
709
- };
710
- }
711
- });
1345
+ /** The store is resolved per request: a host that keeps its own metrics binds it after this API mounts. */
1346
+ var route_server_default = defineRoute(({ context }) => createLogApi(() => readPoServerScope(context)?.resolve(PO_LOG_METRICS_CONTRACT), () => readPoServerScope(context)?.resolve(PO_LOG_HOST_USAGE_CONTRACT)));
712
1347
  //#endregion
713
1348
  //#region src/extensions/workspaces/sessions/(backend)/command/log-metrics.server.ts
714
1349
  var log_metrics_server_default = defineServerCommand((context) => context.root.commands[0]);
715
1350
  //#endregion
716
1351
  //#region src/extensions/workspaces/sessions/(backend)/hook/agent-end.server.ts
717
- var agent_end_server_default = defineHook((context) => context.root.hooks[9]);
1352
+ var agent_end_server_default = defineHook((context) => ({
1353
+ ...context.root.hooks[9],
1354
+ name: "trace-agent-completion",
1355
+ description: "While telemetry is active, record agent duration and message count in a queued trace span, then flush telemetry."
1356
+ }));
718
1357
  //#endregion
719
1358
  //#region src/extensions/workspaces/sessions/(backend)/hook/agent-settled.server.ts
720
- var agent_settled_server_default = defineHook((context) => context.root.hooks[1]);
1359
+ var agent_settled_server_default = defineHook((context) => ({
1360
+ ...context.root.hooks[1],
1361
+ name: "trace-agent-settlement",
1362
+ description: "While telemetry is active, record agent settlement debug telemetry in a queued trace span."
1363
+ }));
721
1364
  //#endregion
722
1365
  //#region src/extensions/workspaces/sessions/(backend)/hook/agent-start.server.ts
723
- var agent_start_server_default = defineHook((context) => context.root.hooks[7]);
1366
+ var agent_start_server_default = defineHook((context) => ({
1367
+ ...context.root.hooks[7],
1368
+ name: "trace-agent-start",
1369
+ description: "While telemetry is active, reset turn timing and record agent startup in a queued trace span."
1370
+ }));
1371
+ //#endregion
1372
+ //#region src/extensions/workspaces/sessions/(backend)/hook/before-provider-request.server.ts
1373
+ var before_provider_request_server_default = defineHook((context) => ({
1374
+ ...context.root.hooks[10],
1375
+ name: "trace-provider-request",
1376
+ description: "When active with an object payload, snapshot the provider request and queue shape telemetry without delaying the request."
1377
+ }));
724
1378
  //#endregion
725
1379
  //#region src/extensions/workspaces/sessions/(backend)/hook/model-select.server.ts
726
- var model_select_server_default = defineHook((context) => context.root.hooks[8]);
1380
+ var model_select_server_default = defineHook((context) => ({
1381
+ ...context.root.hooks[8],
1382
+ name: "trace-model-selection",
1383
+ description: "While telemetry is active, record the selected provider and model in a queued trace span."
1384
+ }));
727
1385
  //#endregion
728
1386
  //#region src/extensions/workspaces/sessions/(backend)/hook/session-shutdown.server.ts
729
- var session_shutdown_server_default = defineHook((context) => context.root.hooks[2]);
1387
+ var session_shutdown_server_default = defineHook((context) => ({
1388
+ ...context.root.hooks[2],
1389
+ name: "trace-session-shutdown",
1390
+ description: "While telemetry is active, record session completion once and clear the telemetry status."
1391
+ }));
730
1392
  //#endregion
731
1393
  //#region src/extensions/workspaces/sessions/(backend)/hook/session-start.server.ts
732
- var session_start_server_default = defineHook((context) => context.root.hooks[0]);
1394
+ var session_start_server_default = defineHook((context) => ({
1395
+ ...context.root.hooks[0],
1396
+ name: "trace-session-start",
1397
+ description: "While telemetry is active, refresh thinking settings and record session startup in a queued trace span."
1398
+ }));
733
1399
  //#endregion
734
1400
  //#region src/extensions/workspaces/sessions/(backend)/hook/tool-execution-end.server.ts
735
- var tool_execution_end_server_default = defineHook((context) => context.root.hooks[6]);
1401
+ var tool_execution_end_server_default = defineHook((context) => ({
1402
+ ...context.root.hooks[6],
1403
+ name: "trace-tool-result",
1404
+ description: "While telemetry is active, record tool outcome and duration in a queued trace span and flush external tool results."
1405
+ }));
736
1406
  //#endregion
737
1407
  //#region src/extensions/workspaces/sessions/(backend)/hook/tool-execution-start.server.ts
738
- var tool_execution_start_server_default = defineHook((context) => context.root.hooks[5]);
1408
+ var tool_execution_start_server_default = defineHook((context) => ({
1409
+ ...context.root.hooks[5],
1410
+ name: "trace-tool-start",
1411
+ description: "While telemetry is active, capture tool timing and record tool-call debug telemetry in a queued trace span."
1412
+ }));
739
1413
  //#endregion
740
1414
  //#region src/extensions/workspaces/sessions/(backend)/hook/turn-end.server.ts
741
- var turn_end_server_default = defineHook((context) => context.root.hooks[4]);
1415
+ var turn_end_server_default = defineHook((context) => ({
1416
+ ...context.root.hooks[4],
1417
+ name: "trace-turn-results",
1418
+ description: "While telemetry is active, record turn duration, usage, failures, and tool token samples in a queued trace span."
1419
+ }));
742
1420
  //#endregion
743
1421
  //#region src/extensions/workspaces/sessions/(backend)/hook/turn-start.server.ts
744
- var turn_start_server_default = defineHook((context) => context.root.hooks[3]);
745
- //#endregion
746
- //#region src/constants/diagnostics.ts
747
- const DIAGNOSE_AGENT_NAME = "diagnose_agent";
748
- const DIAGNOSE_AGENT_DESCRIPTION = "Inspect captured failures and token usage for the current Po session. Read-only, bounded to the last day or week; omits prompts, tool arguments, credentials, and unrelated sessions.";
749
- const AGENT_DIAGNOSTIC_TIMEOUT_MS = 15e3;
750
- const AGENT_ISSUE_CATEGORIES = [
751
- "tool_failure",
752
- "infrastructure_failure",
753
- "caller_error",
754
- "expected_failure",
755
- "page_state",
756
- "api_error",
757
- "api_refusal",
758
- "api_retries_exhausted",
759
- "tool_rejected",
760
- "log_error"
761
- ];
1422
+ var turn_start_server_default = defineHook((context) => ({
1423
+ ...context.root.hooks[3],
1424
+ name: "trace-turn-start",
1425
+ description: "While telemetry is active, capture turn timing and record turn-start debug telemetry in a queued trace span."
1426
+ }));
1427
+ //#endregion
1428
+ //#region src/extensions/workspaces/sessions/(backend)/resource/codemode-how-to-logsink.server.ts
1429
+ var codemode_how_to_logsink_server_default = defineResource({
1430
+ name: "codemode-how-to-logsink",
1431
+ description: "Find out what went wrong and what it cost: captured failures, token usage, logs and traces. Use when debugging a tool or runtime error in this session, or when reviewing past sessions to improve a workflow.",
1432
+ kind: "skill",
1433
+ pinned: true,
1434
+ path: packageResourcePath(import.meta.url, "src/prompts/codemode-how-to-logsink/SKILL.md"),
1435
+ read: () => readPackageResource(import.meta.url, "src/prompts/codemode-how-to-logsink/SKILL.md")
1436
+ });
762
1437
  //#endregion
763
- //#region src/extensions/workspaces/sessions/(backend)/resource/po-debug-agent.server.ts
764
- var po_debug_agent_server_default = defineResource({
765
- name: "po-debug-agent",
1438
+ //#region src/extensions/workspaces/sessions/(backend)/resource/help-how-to-log.server.ts
1439
+ var help_how_to_log_server_default = defineResource({
1440
+ name: "help-how-to-log",
766
1441
  description: "Debug a Po agent using session-scoped failure and usage evidence. Distinguish missing telemetry from a healthy run, diagnose expensive or failed tools, and investigate deeper traces without exposing secrets or changing the sink.",
767
1442
  when: PO_HELP_WHEN,
768
1443
  kind: "skill",
769
- path: packageResourcePath(import.meta.url, "src/prompts/po-debug-agent/SKILL.md"),
770
- read: () => readPackageResource(import.meta.url, "src/prompts/po-debug-agent/SKILL.md")
1444
+ path: packageResourcePath(import.meta.url, "src/prompts/help-how-to-log/SKILL.md"),
1445
+ read: () => readPackageResource(import.meta.url, "src/prompts/help-how-to-log/SKILL.md")
771
1446
  });
772
1447
  //#endregion
773
- //#region src/schemas/agentDiagnostics.ts
774
- const count = Type.Number({ minimum: 0 });
775
- const coverage = Type.Number({
776
- minimum: 0,
777
- maximum: 100
778
- });
779
- const agentDiagnosticParameters = Type.Object({
780
- period: Type.Optional(Type.Union([Type.Literal("day"), Type.Literal("week")])),
781
- toolLimit: Type.Optional(Type.Integer({
782
- minimum: 1,
783
- maximum: 20
784
- }))
785
- }, { additionalProperties: false });
786
- /** Validate only the fields we return. Extra upstream fields never cross this boundary. */
787
- const scopedMetricsSchema = Type.Object({
788
- groupBy: Type.Literal("session"),
789
- period: Type.Union([Type.Literal("day"), Type.Literal("week")]),
790
- filters: Type.Object({ sessionId: Type.String({ minLength: 1 }) }),
791
- totals: Type.Object({
792
- totalRecords: count,
793
- issueCount: count,
794
- usageEventCount: count,
795
- inputTokens: count,
796
- outputTokens: count,
797
- totalTokens: count,
798
- cachedInputTokens: count,
799
- reasoningOutputTokens: count,
800
- tokenCoveragePercent: coverage
801
- }),
802
- groups: Type.Array(Type.Object({
803
- sessionId: Type.String({ minLength: 1 }),
804
- byCategory: Type.Record(Type.String(), count)
805
- }), { maxItems: 1 }),
806
- tools: Type.Object({
807
- returnedTools: count,
808
- rows: Type.Array(Type.Object({
809
- toolName: Type.String({
810
- minLength: 1,
811
- maxLength: 128,
812
- pattern: "^[A-Za-z0-9_./:-]+$"
813
- }),
814
- invocationCount: count,
815
- toolCallTurn: Type.Object({
816
- samples: count,
817
- avgTotalTokens: count,
818
- p90TotalTokens: count
819
- })
820
- }), { maxItems: 20 })
821
- })
822
- });
1448
+ //#region src/extensions/workspaces/sessions/(backend)/tool/logsink_agent_issues.server.ts
1449
+ var logsink_agent_issues_server_default = defineTool$1((context) => createLogsinkTool("agentIssues", context.root.logQueries));
823
1450
  //#endregion
824
- //#region src/services/agentDiagnostics/index.ts
825
- async function readAgentDiagnostics(source, sessionId, input, signal) {
826
- const period = input.period ?? "day";
827
- const limit = input.toolLimit ?? 10;
828
- signal.throwIfAborted();
829
- let onAbort = () => {};
830
- try {
831
- const report = await Promise.race([source.query({
832
- groupBy: "session",
833
- period,
834
- limit: 1,
835
- toolLimit: limit,
836
- filter: { sessionId }
837
- }), new Promise((_resolve, reject) => {
838
- onAbort = () => reject(signal.reason);
839
- signal.addEventListener("abort", onAbort, { once: true });
840
- if (signal.aborted) onAbort();
841
- })]);
842
- signal.throwIfAborted();
843
- if (!Check(scopedMetricsSchema, report) || report.filters.sessionId !== sessionId || report.period !== period || report.groups.some((group) => group.sessionId !== sessionId)) return {
844
- evidence: "unavailable",
845
- code: "METRICS_SCOPE_NOT_CONFIRMED",
846
- scope: "current-session",
847
- period
848
- };
849
- const totals = report.totals;
850
- return {
851
- scope: "current-session",
852
- period,
853
- evidence: totals.totalRecords === 0 ? "empty" : "available",
854
- transport: source.lastTransport(),
855
- capturedRecords: totals.totalRecords,
856
- capturedIssues: totals.issueCount,
857
- issuesByCategory: Object.fromEntries(AGENT_ISSUE_CATEGORIES.map((category) => [category, report.groups[0]?.byCategory[category] ?? 0])),
858
- usage: {
859
- inputTokens: totals.inputTokens,
860
- outputTokens: totals.outputTokens,
861
- totalTokens: totals.totalTokens,
862
- cachedInputTokens: totals.cachedInputTokens,
863
- reasoningOutputTokens: totals.reasoningOutputTokens,
864
- usageEventCount: totals.usageEventCount,
865
- tokenCoveragePercent: totals.tokenCoveragePercent
866
- },
867
- tools: report.tools.rows.slice(0, limit).map((tool) => ({
868
- name: tool.toolName,
869
- invocations: tool.invocationCount,
870
- sampledTurns: tool.toolCallTurn.samples,
871
- averageTurnTokens: tool.toolCallTurn.avgTotalTokens,
872
- p90TurnTokens: tool.toolCallTurn.p90TotalTokens
873
- })),
874
- toolRowLimit: limit,
875
- limitReached: report.tools.rows.length >= limit,
876
- captureCompleteness: "not-reported",
877
- limitations: "Only captured records in this window are represented. Empty data is not proof of a healthy run. Token coverage is not event-capture coverage; per-tool token samples describe the containing turn, not exclusive tool cost. Raw prompts, error messages, tool arguments and traces are omitted. Use po-debug-agent for deeper authorized investigation."
878
- };
879
- } catch (error) {
880
- if (signal.aborted) throw error;
881
- return {
882
- evidence: "unavailable",
883
- code: "METRICS_UNAVAILABLE",
884
- scope: "current-session",
885
- period
886
- };
887
- } finally {
888
- signal.removeEventListener("abort", onAbort);
889
- }
890
- }
891
- function createAgentDiagnosticsTool(readScope, authorize) {
892
- return defineTool({
893
- name: DIAGNOSE_AGENT_NAME,
894
- description: DIAGNOSE_AGENT_DESCRIPTION,
895
- parameters: agentDiagnosticParameters,
896
- when: PO_HELP_WHEN,
897
- executionMode: "serial",
898
- async execute(input, execution) {
899
- const active = authorize(execution.signal);
900
- const signal = AbortSignal.any([active, AbortSignal.timeout(AGENT_DIAGNOSTIC_TIMEOUT_MS)]);
901
- const scope = readScope();
902
- if (!scope.sessionId) throw new Error("Agent diagnostics require an active session.");
903
- const source = createMetricsSource({
904
- packageName: PACKAGE_NAME$1,
905
- serviceName: "pi",
906
- ...scope.options
907
- });
908
- try {
909
- const report = await readAgentDiagnostics(source, scope.sessionId, input, signal);
910
- signal.throwIfAborted();
911
- authorize(execution.signal);
912
- return {
913
- content: [{
914
- type: "text",
915
- text: JSON.stringify(report, null, 2)
916
- }],
917
- details: report
918
- };
919
- } finally {
920
- await source.close?.();
921
- }
922
- }
923
- });
924
- }
1451
+ //#region src/extensions/workspaces/sessions/(backend)/tool/logsink_metrics.server.ts
1452
+ var logsink_metrics_server_default = defineTool$1((context) => createLogsinkTool("metrics", context.root.logQueries));
925
1453
  //#endregion
926
- //#region src/extensions/workspaces/sessions/(backend)/tool/diagnose_agent.server.ts
927
- var diagnose_agent_server_default = defineTool$1(({ agent, signal: ownerSignal }) => {
928
- if (!agent) throw new Error("Agent diagnostics require a session host.");
929
- return createAgentDiagnosticsTool(() => ({
930
- sessionId: agent.context.sessionId,
931
- options: {
932
- cwd: agent.context.cwd,
933
- env: {
934
- ...agent.context.environment,
935
- PI_SESSION_ID: agent.context.sessionId
936
- }
937
- }
938
- }), (signal) => {
939
- ownerSignal.throwIfAborted();
940
- signal?.throwIfAborted();
941
- agent.assertActive(PACKAGE_NAME$1);
942
- if (!(agent.context.selection.state?.["minor-mode"] ?? []).includes("help")) throw new Error("Help mode is not active.");
943
- return signal ? AbortSignal.any([signal, ownerSignal]) : ownerSignal;
944
- });
945
- });
1454
+ //#region src/extensions/workspaces/sessions/(backend)/tool/logsink_search.server.ts
1455
+ var logsink_search_server_default = defineTool$1((context) => createLogsinkTool("search", context.root.logQueries));
1456
+ //#endregion
1457
+ //#region src/extensions/workspaces/sessions/(backend)/tool/logsink_services.server.ts
1458
+ var logsink_services_server_default = defineTool$1((context) => createLogsinkTool("services", context.root.logQueries));
1459
+ //#endregion
1460
+ //#region src/extensions/workspaces/sessions/(backend)/tool/logsink_stats.server.ts
1461
+ var logsink_stats_server_default = defineTool$1((context) => createLogsinkTool("stats", context.root.logQueries));
1462
+ //#endregion
1463
+ //#region src/extensions/workspaces/sessions/(backend)/tool/logsink_status.server.ts
1464
+ var logsink_status_server_default = defineTool$1((context) => createLogsinkTool("status", context.root.logQueries));
1465
+ //#endregion
1466
+ //#region src/extensions/workspaces/sessions/(backend)/tool/logsink_trace.server.ts
1467
+ var logsink_trace_server_default = defineTool$1((context) => createLogsinkTool("trace", context.root.logQueries));
946
1468
  //#endregion
947
1469
  //#region generated/server.ts
948
1470
  const at = (value, context) => typeof value === "function" ? value(context) : value;
949
- const via = (identity, value) => value === void 0 ? void 0 : {
950
- ...identity,
951
- ...value
1471
+ const via = (identity, value) => {
1472
+ if (value === void 0) return void 0;
1473
+ const declaration = value;
1474
+ return {
1475
+ ...identity,
1476
+ ...declaration,
1477
+ ...declaration.relations === void 0 ? {} : { relations: declaration.relations.map((relation) => ({
1478
+ evidence: "declared",
1479
+ ...relation
1480
+ })) }
1481
+ };
952
1482
  };
953
1483
  const serverPlugin = defineServerPlugin({
954
1484
  name: "@agimon-ai/po-log",
955
1485
  providerOverrides: composeServerProviderOverrides(root_server_default),
956
1486
  injects: composeRootInjects({ session: [root_server_default] }),
957
- global: (context) => ({ get api() {
1487
+ host: (context) => ({ get api() {
958
1488
  return [at(route_server_default, context)];
959
1489
  } }),
960
1490
  workspace: (context) => ({ get api() {
@@ -979,6 +1509,7 @@ const serverPlugin = defineServerPlugin({
979
1509
  via({ event: "agent_end" }, at(agent_end_server_default, contextSession)),
980
1510
  via({ event: "agent_settled" }, at(agent_settled_server_default, contextSession)),
981
1511
  via({ event: "agent_start" }, at(agent_start_server_default, contextSession)),
1512
+ via({ event: "before_provider_request" }, at(before_provider_request_server_default, contextSession)),
982
1513
  via({ event: "model_select" }, at(model_select_server_default, contextSession)),
983
1514
  via({ event: "session_shutdown" }, at(session_shutdown_server_default, contextSession)),
984
1515
  via({ event: "session_start" }, at(session_start_server_default, contextSession)),
@@ -989,10 +1520,18 @@ const serverPlugin = defineServerPlugin({
989
1520
  ];
990
1521
  },
991
1522
  get resources() {
992
- return [at(po_debug_agent_server_default, contextSession)];
1523
+ return [at(codemode_how_to_logsink_server_default, contextSession), at(help_how_to_log_server_default, contextSession)];
993
1524
  },
994
1525
  get tools() {
995
- return [via({ name: "diagnose_agent" }, at(diagnose_agent_server_default, contextSession))];
1526
+ return [
1527
+ via({ name: "logsink_agent_issues" }, at(logsink_agent_issues_server_default, contextSession)),
1528
+ via({ name: "logsink_metrics" }, at(logsink_metrics_server_default, contextSession)),
1529
+ via({ name: "logsink_search" }, at(logsink_search_server_default, contextSession)),
1530
+ via({ name: "logsink_services" }, at(logsink_services_server_default, contextSession)),
1531
+ via({ name: "logsink_stats" }, at(logsink_stats_server_default, contextSession)),
1532
+ via({ name: "logsink_status" }, at(logsink_status_server_default, contextSession)),
1533
+ via({ name: "logsink_trace" }, at(logsink_trace_server_default, contextSession))
1534
+ ];
996
1535
  },
997
1536
  services: [...scopeSession.services ?? []],
998
1537
  get activities() {