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