@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 +1 @@
1
- {"version":3,"file":"server.mjs","names":["PACKAGE_NAME","PACKAGE_NAME","isRecord","toReport","PACKAGE_NAME","routes","HELP_WHEN","HELP_WHEN","PACKAGE_NAME","defineTool","PACKAGE_NAME","rootSession","apiRoute","commandLogMetrics","hookAgentEnd","hookAgentSettled","hookAgentStart","hookModelSelect","hookSessionShutdown","hookSessionStart","hookToolExecutionEnd","hookToolExecutionStart","hookTurnEnd","hookTurnStart","resourcePoDebugAgent","toolDiagnoseAgent"],"sources":["../../src/constants/telemetry.ts","../../src/services/telemetryEnabled/index.ts","../../src/services/serverTelemetry/index.ts","../../src/extensions/workspaces/sessions/(backend)/_lib/serverRoot.ts","../../src/extensions/workspaces/sessions/(backend)/root.server.ts","../../src/services/issuesSource/index.ts","../../src/types/webMetrics.ts","../../src/types/apiRoutes.ts","../../src/services/hubApi/index.ts","../../src/extensions/(backend)/api/log/route.server.ts","../../src/extensions/workspaces/sessions/(backend)/command/log-metrics.server.ts","../../src/extensions/workspaces/sessions/(backend)/hook/agent-end.server.ts","../../src/extensions/workspaces/sessions/(backend)/hook/agent-settled.server.ts","../../src/extensions/workspaces/sessions/(backend)/hook/agent-start.server.ts","../../src/extensions/workspaces/sessions/(backend)/hook/model-select.server.ts","../../src/extensions/workspaces/sessions/(backend)/hook/session-shutdown.server.ts","../../src/extensions/workspaces/sessions/(backend)/hook/session-start.server.ts","../../src/extensions/workspaces/sessions/(backend)/hook/tool-execution-end.server.ts","../../src/extensions/workspaces/sessions/(backend)/hook/tool-execution-start.server.ts","../../src/extensions/workspaces/sessions/(backend)/hook/turn-end.server.ts","../../src/extensions/workspaces/sessions/(backend)/hook/turn-start.server.ts","../../src/constants/diagnostics.ts","../../src/extensions/workspaces/sessions/(backend)/resource/po-debug-agent.server.ts","../../src/schemas/agentDiagnostics.ts","../../src/services/agentDiagnostics/index.ts","../../src/extensions/workspaces/sessions/(backend)/tool/diagnose_agent.server.ts","../../generated/server.ts"],"sourcesContent":["export const SERVICE_NAME = 'pi';\nexport const PACKAGE_NAME = '@agimon-ai/po-log';\n/** Opt back into stderr diagnostics when debugging outside a live TUI. */\nexport const DIAGNOSTICS_STDERR = 'stderr';\nexport const LEADER_SOURCE = '@agimon-ai/po-log';\nexport const LOG_METRICS_COMMAND = 'log-metrics';\nexport const LOG_METRICS_DESCRIPTION = 'Show session-local log metrics';\nexport const HELP_GROUP_ORDER = 70;\n/** Must match the Help group published by po-ui, or the registry drops this. */\nexport const HELP_GROUP_DETAIL = 'package docs and logs';\nexport const NO_ENDPOINT = 'none';\nexport const API_ERROR_STATUS = 400;\nexport const FAILURE_STOP_REASONS = ['error', 'aborted'];\n","export function isEnabled(value: string | undefined): boolean {\n return value === '1' || value?.toLowerCase() === 'true' || value?.toLowerCase() === 'yes';\n}\n","import type {\n PoHeadlessActivity,\n PoHeadlessCommand,\n PoHeadlessExecutionContext,\n PoHeadlessHook,\n} from '@agimon-ai/po-core/headless';\nimport { isRecord } from '@agimon-ai/po-core/runtimeJson';\nimport { createPoTelemetry, type PoTelemetry } from '@agimon-ai/po-telemetry';\n\nimport { PACKAGE_NAME, SERVICE_NAME } from '../../constants/telemetry';\nimport type { PiTelemetryExtensionOptions } from '../../types/piTelemetry';\nimport { isEnabled } from '../telemetryEnabled';\n\nfunction contextAttributes(execution: PoHeadlessExecutionContext): Record<string, unknown> {\n return {\n 'pi.mode': 'json',\n 'pi.session.id': execution.sessionId,\n ...(execution.model === undefined\n ? {}\n : {\n 'gen_ai.provider.name': execution.model.provider,\n 'gen_ai.request.model': execution.model.id,\n }),\n };\n}\n\n/** Headless hooks carry untrusted records, not Pi's typed assistant messages. */\nfunction usageAttributes(message: Record<string, unknown>): Record<string, unknown> {\n const usage = isRecord(message.usage) ? message.usage : {};\n const attributes: Record<string, unknown> = {};\n for (const [field, attribute] of Object.entries({\n input: 'gen_ai.usage.input_tokens',\n output: 'gen_ai.usage.output_tokens',\n cacheRead: 'gen_ai.usage.cache_read_tokens',\n cacheWrite: 'gen_ai.usage.cache_write_tokens',\n totalTokens: 'gen_ai.usage.total_tokens',\n reasoning: 'gen_ai.usage.reasoning_tokens',\n })) {\n const value = usage[field];\n if (typeof value === 'number' && Number.isFinite(value) && value >= 0) attributes[attribute] = value;\n }\n const cost = isRecord(usage.cost) ? usage.cost.total : undefined;\n if (typeof cost === 'number' && Number.isFinite(cost) && cost >= 0) attributes['gen_ai.usage.cost'] = cost;\n return attributes;\n}\n\nexport function createServerTelemetry(options: PiTelemetryExtensionOptions = {}) {\n let active = false;\n let finished = false;\n let queue = Promise.resolve();\n let disposal: Promise<void> | undefined;\n let thinkingLevel: string | undefined;\n const sessionAttributes = (execution: PoHeadlessExecutionContext) => ({\n ...contextAttributes(execution),\n ...(thinkingLevel ? { 'pi.thinking_level': thinkingLevel } : {}),\n });\n const enqueue = (operation: () => Promise<void>) => {\n const pending = queue.then(operation);\n // Advisory telemetry must not poison the queue after a failed exporter.\n queue = pending.catch((error: unknown) => options.onDiagnostic?.(String(error)));\n return pending;\n };\n let telemetry: PoTelemetry | undefined;\n const turns = new Map<string, number>();\n const tools = new Map<string, number>();\n let agentStartedAt: number | undefined;\n let turnIndex = 0;\n const activity: PoHeadlessActivity = {\n name: PACKAGE_NAME,\n start(execution) {\n const current = createPoTelemetry({\n serviceName: options.serviceName ?? SERVICE_NAME,\n packageName: PACKAGE_NAME,\n cwd: execution.cwd,\n env: { ...(options.env ?? execution.environment), PI_SESSION_ID: execution.sessionId },\n allowFileFallback: options.allowFileFallback,\n telemetryFactory: options.telemetryFactory,\n warn: options.onDiagnostic ?? (() => undefined),\n onRecord: (record) => options.metrics?.record(record.event, record.attributes),\n onStatus: (status) =>\n options.onSinkStatus?.({\n service: status.serviceName,\n backend: status.backend,\n endpoint: status.endpoint ?? 'none',\n endpointSource: status.endpointSource,\n traces: status.traces,\n redaction: true,\n fileFallback: status.fileFallback,\n }),\n enableLogs: true,\n enableTraces:\n (options.env ?? execution.environment).AGENT_OTEL_TRACES === undefined ||\n isEnabled((options.env ?? execution.environment).AGENT_OTEL_TRACES),\n });\n telemetry = current;\n active = true;\n finished = false;\n return () =>\n (disposal ??= (async () => {\n active = false;\n // Drain admitted records before shutting down their exporter.\n await queue;\n if (telemetry === current) {\n telemetry = undefined;\n turns.clear();\n tools.clear();\n agentStartedAt = undefined;\n }\n await current.shutdown();\n })());\n },\n };\n\n const command: PoHeadlessCommand = {\n name: 'log-metrics',\n description: 'Show headless telemetry sink status.',\n async execute(_args, execution) {\n await execution.client.notify({\n title: 'Po telemetry',\n body: JSON.stringify(telemetry?.status() ?? { active: false }, null, 2),\n level: 'info',\n });\n },\n };\n\n const hooks: PoHeadlessHook[] = [\n {\n event: 'session_start',\n async handle(_event, execution) {\n thinkingLevel = (await execution.session?.readModelSettings?.())?.thinkingLevel;\n await telemetry?.recordEvent('pi.session.started', {\n ...sessionAttributes(execution),\n 'pi.session.reason': 'startup',\n 'pi.session.previous': false,\n });\n },\n },\n {\n event: 'agent_settled',\n async handle(_event, execution) {\n await telemetry?.recordDebug('pi.agent.settled', sessionAttributes(execution));\n },\n },\n {\n event: 'session_shutdown',\n async handle(_event, execution) {\n if (finished) return;\n finished = true;\n await telemetry?.recordEvent('pi.session.finished', {\n ...sessionAttributes(execution),\n 'pi.session.reason': 'quit',\n });\n execution.client.setStatus('po-log', undefined);\n },\n },\n {\n event: 'turn_start',\n async handle(event, execution) {\n if (!telemetry) return;\n await telemetry.recordDebug('pi.turn.started', {\n ...sessionAttributes(execution),\n 'pi.turn.index': event.turnIndex,\n ...(typeof event.turnId === 'string' ? { 'pi.turn.id': event.turnId } : {}),\n });\n },\n },\n {\n event: 'turn_end',\n async handle(event, execution) {\n const current = telemetry;\n if (!current) return;\n const duration = event.telemetryDurationMs;\n const message = isRecord(event.message) && event.message.role === 'assistant' ? event.message : undefined;\n const usage = message === undefined ? {} : usageAttributes(message);\n const attributes = {\n ...sessionAttributes(execution),\n 'pi.turn.index': event.turnIndex,\n ...(typeof event.turnId === 'string' ? { 'pi.turn.id': event.turnId } : {}),\n ...(message === undefined\n ? {}\n : {\n 'gen_ai.provider.name': message.provider ?? execution.model?.provider,\n 'gen_ai.response.model': message.responseModel ?? message.model,\n 'gen_ai.response.finish_reasons': message.stopReason,\n }),\n };\n const results = Array.isArray(event.toolResults) ? event.toolResults.filter(isRecord) : [];\n await current.recordEvent('pi.turn.finished', {\n ...attributes,\n ...usage,\n 'pi.tool_result.count': results.length,\n ...(typeof duration === 'number' ? { 'pi.turn.duration_ms': duration } : {}),\n });\n if (message?.stopReason === 'error' || message?.stopReason === 'aborted') {\n const failure = {\n ...attributes,\n 'error.type': 'ProviderError',\n 'error.code': message.stopReason,\n outcome: message.stopReason === 'aborted' ? 'aborted' : 'error',\n };\n // Usage belongs to the finished record only, not the failure marker.\n if (message.stopReason === 'aborted') await current.recordWarning('pi.turn.failed', undefined, failure);\n else await current.recordError('pi.turn.failed', undefined, failure);\n }\n if (Object.keys(usage).length > 0) {\n for (const result of results) {\n await current.recordDebug('pi.tool_token_sample', {\n ...attributes,\n ...usage,\n 'tool.name': result.toolName,\n token_attribution: 'toolCallTurn',\n });\n }\n }\n },\n },\n {\n event: 'tool_execution_start',\n async handle(event, execution) {\n if (!telemetry) return;\n await telemetry.recordDebug('pi.tool_call', {\n ...sessionAttributes(execution),\n 'tool.name': event.toolName,\n 'tool.call.id': event.toolCallId,\n });\n },\n },\n {\n event: 'tool_execution_end',\n async handle(event, execution) {\n const current = telemetry;\n if (!current) return;\n const duration = event.telemetryDurationMs;\n await current.recordEvent('pi.tool_result', {\n ...sessionAttributes(execution),\n 'tool.name': event.toolName,\n 'tool.call.id': event.toolCallId,\n success: event.isError !== true,\n 'tool.result.error': event.isError === true,\n ...(typeof duration === 'number' ? { 'tool.duration_ms': duration } : {}),\n });\n // External MCP calls have no agent_settled event to flush their results.\n if (typeof event.toolCallId === 'string' && event.toolCallId.startsWith('external-')) await current.flush();\n },\n },\n {\n event: 'agent_start',\n async handle(_event, execution) {\n if (!telemetry) return;\n await telemetry.recordEvent('pi.agent.started', sessionAttributes(execution));\n },\n },\n {\n event: 'model_select',\n async handle(event, execution) {\n await telemetry?.recordEvent('pi.model.selected', {\n ...sessionAttributes(execution),\n 'pi.model.source': 'set',\n 'gen_ai.provider.name': event.model.provider,\n 'gen_ai.request.model': event.model.id,\n });\n },\n },\n {\n event: 'agent_end',\n async handle(event, execution) {\n await telemetry?.recordEvent('pi.agent.finished', {\n ...sessionAttributes(execution),\n 'pi.message.count': Array.isArray(event.messages) ? event.messages.length : 0,\n ...(typeof event.telemetryDurationMs === 'number'\n ? { 'pi.agent.duration_ms': event.telemetryDurationMs }\n : {}),\n });\n await telemetry?.flush();\n },\n },\n ];\n for (const hook of hooks) {\n const handle = hook.handle.bind(hook);\n hook.handle = (event: Readonly<Record<string, unknown>>, execution: PoHeadlessExecutionContext) => {\n if (!active) return;\n const now = Date.now();\n if (hook.event === 'agent_start') turnIndex = 0;\n const index = typeof event.turnIndex === 'number' ? event.turnIndex : turnIndex;\n const turnKey = typeof event.turnId === 'string' ? event.turnId : String(index);\n if (hook.event === 'turn_start') turns.set(turnKey, now);\n if (hook.event === 'tool_execution_start' && typeof event.toolCallId === 'string')\n tools.set(event.toolCallId, now);\n if (hook.event === 'agent_start') agentStartedAt = now;\n let duration: number | undefined;\n if (hook.event === 'turn_end') {\n const start = turns.get(turnKey);\n turns.delete(turnKey);\n turnIndex += 1;\n if (start !== undefined) duration = now - start;\n }\n if (hook.event === 'tool_execution_end' && typeof event.toolCallId === 'string') {\n const start = tools.get(event.toolCallId);\n tools.delete(event.toolCallId);\n if (start !== undefined) duration = now - start;\n }\n if (hook.event === 'agent_end') {\n if (agentStartedAt !== undefined) duration = now - agentStartedAt;\n agentStartedAt = undefined;\n }\n return enqueue(async () => {\n thinkingLevel = (await execution.session?.readModelSettings?.())?.thinkingLevel;\n await handle({ ...event, turnIndex: index, telemetryDurationMs: duration } as never, execution);\n });\n };\n }\n // Telemetry sink status is operator information, not model-actionable.\n return { activities: [activity], commands: [command], hooks };\n}\n","import { createServerTelemetry } from '../../../../../services/serverTelemetry';\nexport const createLogServerRoot = () => {\n const runtime = createServerTelemetry();\n return { value: runtime, activities: runtime.activities };\n};\nexport type LogServerScope = Awaited<ReturnType<typeof createLogServerRoot>>['value'];\n","import { defineRoot } from '@agimon-ai/po-core/extensionFile';\n\nimport { createLogServerRoot } from './_lib/serverRoot';\n\nexport default defineRoot(createLogServerRoot);\n","import { execFile } from 'node:child_process';\nimport { createRequire } from 'node:module';\nimport path from 'node:path';\n\nimport { resolveLogSinkInstance } from '@agimon-ai/po-logsink';\n\nimport type { AgentIssueSample, IssuesQueryParams, IssuesReport, IssuesSource } from '../../types/issuesSource';\n\n/**\n * Agent-issue analysis over the sink's CLI.\n *\n * One transport, not two, because the daemon serves only /api/metrics and\n * /api/logs: there is no issues route to prefer. Every call is a subprocess,\n * which is why the page asks for this only when a reader opens the section\n * rather than alongside each report.\n */\n\nconst PACKAGE_NAME = '@agimon-ai/po-logsink';\nconst CLI_TIMEOUT_MS = 60000;\n/** The analysis scans the whole window, so its output is larger than a metrics report. */\nconst MAX_CLI_BUFFER = 32 * 1024 * 1024;\n\nexport interface IssuesSourceOptions {\n env?: NodeJS.ProcessEnv;\n cwd?: string;\n packageName?: string;\n serviceName?: string;\n /** Overrides the subprocess in tests. */\n cliRunner?: (params: IssuesQueryParams) => Promise<unknown>;\n}\n\nfunction cliEntryPoint(): string {\n const require = createRequire(import.meta.url);\n const packageJson = require.resolve(`${PACKAGE_NAME}/package.json`);\n return path.join(path.dirname(packageJson), 'dist', 'cli.mjs');\n}\n\nfunction runCli(params: IssuesQueryParams, dbPath: string | undefined): Promise<unknown> {\n return new Promise((resolve, reject) => {\n execFile(\n process.execPath,\n [\n cliEntryPoint(),\n 'logs',\n 'agent-issues',\n '--limit',\n String(params.limit),\n ...(params.sessionId === undefined ? [] : ['--session-id', params.sessionId]),\n ...(params.startTime === undefined ? [] : ['--start-time', params.startTime]),\n ...(params.endTime === undefined ? [] : ['--end-time', params.endTime]),\n ...(dbPath === undefined ? [] : ['--db-path', dbPath]),\n ],\n { timeout: CLI_TIMEOUT_MS, maxBuffer: MAX_CLI_BUFFER },\n (error, stdout, stderr) => {\n if (error) {\n reject(new Error(stderr.trim() || error.message));\n return;\n }\n try {\n resolve(JSON.parse(stdout) as unknown);\n } catch {\n reject(new Error('The log sink returned output this version cannot read.'));\n }\n },\n );\n });\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\nfunction counts(value: unknown): Record<string, number> {\n if (!isRecord(value)) return {};\n const entries = Object.entries(value).flatMap(([key, count]) =>\n typeof count === 'number' ? [[key, count] as [string, number]] : [],\n );\n return Object.fromEntries(entries);\n}\n\nfunction text(value: unknown): string {\n return typeof value === 'string' ? value : '';\n}\n\nfunction nullableText(value: unknown): string | null {\n return typeof value === 'string' && value !== '' ? value : null;\n}\n\nfunction toSample(value: unknown): AgentIssueSample[] {\n if (!isRecord(value)) return [];\n return [\n {\n fingerprint: text(value.fingerprint),\n occurrenceCount: typeof value.occurrenceCount === 'number' ? value.occurrenceCount : 1,\n category: text(value.category),\n timestamp: text(value.timestamp),\n level: text(value.level),\n message: text(value.message),\n // The sink leaves detail null when the message already is the detail.\n detail: nullableText(value.detail) ?? text(value.message),\n tool: nullableText(value.tool),\n errorType: nullableText(value.errorType),\n agentName: nullableText(value.agentName),\n model: nullableText(value.model),\n statusCode: nullableText(value.statusCode),\n },\n ];\n}\n\n/**\n * The CLI's report is a foreign process's JSON, so every field is narrowed\n * here rather than cast. A sink one version ahead may add fields, and a sink\n * one version behind may omit them; neither should throw.\n */\nfunction toReport(raw: unknown): IssuesReport {\n if (!isRecord(raw)) throw new Error('The log sink returned output this version cannot read.');\n const samples = Array.isArray(raw.issues) ? raw.issues.flatMap(toSample) : [];\n return {\n totalIssues: typeof raw.totalIssues === 'number' ? raw.totalIssues : 0,\n uniqueIncidents: typeof raw.uniqueIncidents === 'number' ? raw.uniqueIncidents : 0,\n byCategory: counts(raw.byCategory),\n byTool: counts(raw.byTool),\n byErrorType: counts(raw.byErrorType),\n samples,\n };\n}\n\nexport function createIssuesSource(options: IssuesSourceOptions = {}): IssuesSource {\n const instance = resolveLogSinkInstance({\n env: options.env,\n cwd: options.cwd,\n packageName: options.packageName,\n serviceName: options.serviceName,\n });\n const cliRunner = options.cliRunner ?? ((params: IssuesQueryParams) => runCli(params, instance?.dbPath));\n\n return {\n async query(params) {\n return toReport(await cliRunner(params));\n },\n };\n}\n","/**\n * The metrics API, shared by this package's hub-scoped route and its cockpit\n * plugin. The two halves run in different processes, so the wire vocabulary is\n * declared here: the `(frontend)` half may reach `src/types` and nothing else\n * on the node side.\n *\n * The shapes are narrower than po-logsink's own report, which carries filter\n * echoes, span counts and token distributions the page never draws.\n * Re-exporting the sink's types would also tie the browser bundle to a node\n * package. What crosses the wire is what a chart reads.\n *\n * Two things the sink does not have, so this contract does not pretend to:\n * money, and per-tool failures. This metrics report records tokens, and its tool rows\n * carry an invocation count with no error field.\n */\n\n/**\n * The segment this package's API is mounted under.\n *\n * Read by the hub's `PoApi`, which still declares its own base path. The\n * browser does not read it: the generated client is handed the same segment by\n * the build, off the `api/log/` folder that creates the mount, so no URL is\n * spelled twice.\n */\nexport const LOG_API_BASE_PATH = 'log';\n\n/**\n * The dimensions the page offers.\n *\n * po-logsink also groups by 'workflow-run', 'workflow-name', 'job' and\n * 'step'. Those are omitted on purpose: no Po package emits the matching\n * attributes today, so offering them would draw an empty chart and read as a\n * bug rather than as a gap.\n */\nexport const METRICS_DIMENSIONS = ['session', 'agent', 'model', 'provider'] as const;\nexport type MetricsDimension = (typeof METRICS_DIMENSIONS)[number];\n\nexport const METRICS_PERIODS = ['day', 'week', 'month', 'all'] as const;\nexport type MetricsPeriod = (typeof METRICS_PERIODS)[number];\n\nexport const METRICS_QUERY_PARAMS = {\n dimension: 'dimension',\n period: 'period',\n /** Narrows the whole report to one value of the current dimension. */\n focus: 'focus',\n} as const;\n\n/** How many groups and tools one response carries; the page ranks, it does not page. */\nexport const METRICS_GROUP_LIMIT = 20;\n\n/** One point on the token timeline. */\nexport interface MetricsBucket {\n /**\n * The sink's own local-time label ('YYYY-MM-DD', or 'YYYY-MM-DD HH:00' for an\n * hour bucket). Carried rather than derived: bucket boundaries are aligned to\n * local time, so slicing the ISO instant renders the wrong day east of\n * Greenwich.\n */\n label: string;\n totalTokens: number;\n inputTokens: number;\n outputTokens: number;\n}\n\n/** One row of the selected dimension. */\nexport interface MetricsGroup {\n /**\n * The group's identity as the sink reports it. For the session dimension\n * this is an opaque hash, never a session the cockpit can open, because\n * po-telemetry hashes identifier-shaped attributes before export.\n */\n key: string;\n totalTokens: number;\n inputTokens: number;\n outputTokens: number;\n /** Problems the sink detected for this group; 0 when it saw none. */\n issueCount: number;\n failed: boolean;\n}\n\n/**\n * One tool's activity.\n *\n * `calls` counts token-attributed samples, not every execution. External MCP\n * calls without model usage remain queryable as logs but have no sample here.\n * `p90TotalTokens` attributes the whole turn's tokens to each tool in that turn,\n * so it ranks tools rather than measuring their own consumption.\n *\n * There is no failure count here because the sink's tool rows do not carry\n * one. Per-tool failures live in its separate agent-issues report, which the\n * running daemon does not expose over HTTP.\n */\nexport interface MetricsTool {\n name: string;\n calls: number;\n p90TotalTokens: number;\n}\n\n/** Which transport answered, so the page can say where its numbers came from. */\nexport type MetricsTransport = 'http' | 'worker';\n\nexport interface MetricsTotals {\n /** Optional so an older hub remains distinguishable from a measured zero. */\n usageEventCount?: number;\n totalRecords?: number;\n /**\n * The providers' own reported total. It is not inputTokens + outputTokens:\n * providers report these counters independently. Their relationship cannot\n * be inferred from a difference, so the page must not stack them as parts\n * of the total or label the difference as cache traffic.\n */\n totalTokens: number;\n inputTokens: number;\n outputTokens: number;\n /** Independently reported cache reads, not an inferred remainder. */\n cachedTokens: number;\n reasoningTokens: number;\n groupCount: number;\n /** Groups the sink flagged as having failed, out of groupCount. */\n failedGroups: number;\n issueCount: number;\n}\n\nexport interface MetricsReport {\n /** Echoed query window, so issue details can use the same recorded period. */\n startTime?: string;\n endTime?: string;\n generatedAt: string;\n dimension: MetricsDimension;\n period: MetricsPeriod;\n /**\n * The width of one timeline bucket, chosen by the sink from the period. A\n * long period over a short history collapses to a single bucket, so the page\n * says which unit it is drawing rather than implying a series it does not\n * have.\n */\n bucketUnit: string;\n /**\n * The dimension value this report is narrowed to, echoed back from the sink\n * rather than from the request. A daemon older than the filter ignores it\n * and returns everything, so trusting the request would label unfiltered\n * numbers as filtered; absence here means the drill-down did not happen.\n */\n focus?: string;\n /** Undefined when the source could not say which transport answered. */\n transport?: MetricsTransport;\n totals: MetricsTotals;\n timeline: MetricsBucket[];\n groups: MetricsGroup[];\n tools: MetricsTool[];\n}\n\n/**\n * Why the page has nothing to draw.\n *\n * The sink is a separate daemon that may be missing or simply empty, and those\n * are different things to tell a reader. Neither is an error: the metrics\n * source already treats a rejecting daemon as unavailable rather than fatal.\n *\n * 'no-api' is the third case and belongs to the cockpit rather than the sink.\n * A hub serving a bundle without package APIs mounted answers this route with\n * the SPA shell, and a 200 of HTML must read as a feature that is not\n * installed, not as a corrupt response.\n */\nexport type MetricsUnavailableReason = 'no-sink' | 'no-data' | 'no-api' | 'query-error';\n\nexport interface MetricsUnavailable {\n unavailable: MetricsUnavailableReason;\n detail: string;\n}\n\nexport type MetricsResponse = MetricsReport | MetricsUnavailable;\n\nexport function isMetricsUnavailable(response: MetricsResponse): response is MetricsUnavailable {\n return 'unavailable' in response;\n}\n\nexport function isMetricsDimension(value: string): value is MetricsDimension {\n return (METRICS_DIMENSIONS as readonly string[]).includes(value);\n}\n\nexport function isMetricsPeriod(value: string): value is MetricsPeriod {\n return (METRICS_PERIODS as readonly string[]).includes(value);\n}\n\n/** One tool's failure count, paired with its call count from the metrics report. */\nexport interface IssueToolRow {\n name: string;\n failures: number;\n}\n\n/**\n * One recurring problem, as the sink fingerprints it.\n *\n * `occurrenceCount` is how many times it happened, which is the number a\n * reader acts on. `detail` is the actionable line; `message` is often only a\n * record name such as 'pi.tool_result'.\n */\nexport interface IssueSample {\n fingerprint: string;\n occurrenceCount: number;\n category: string;\n timestamp: string;\n level: string;\n message: string;\n detail: string;\n tool: string | null;\n errorType: string | null;\n agentName: string | null;\n model: string | null;\n statusCode: string | null;\n}\n\n/**\n * The detail behind the issue count.\n *\n * Fetched separately from the report because the running sink exposes no\n * issues route over HTTP, so this costs a subprocess. The page asks for it\n * when a reader opens the section, not with every refresh.\n */\nexport interface IssuesView {\n totalIssues: number;\n uniqueIncidents: number;\n byCategory: Record<string, number>;\n byTool: Record<string, number>;\n byErrorType: Record<string, number>;\n samples: IssueSample[];\n}\n\nexport type IssuesResponse = IssuesView | MetricsUnavailable;\n\nexport function isIssuesUnavailable(response: IssuesResponse): response is MetricsUnavailable {\n return 'unavailable' in response;\n}\n\n/** How many incidents the issues section ranks. */\nexport const ISSUE_SAMPLE_LIMIT = 50;\n\n/** How many tool rows the report ranks, so a failing tool has a denominator. */\nexport const METRICS_TOOL_LIMIT = 15;\n","import { apiResponse, defineApiRoutes } from '@agimon-ai/po-core/web';\n\nimport { METRICS_QUERY_PARAMS, type IssuesResponse, type MetricsResponse } from './webMetrics';\n\n/**\n * This package's routes, as data.\n *\n * No scope and no base path. The build reads both off\n * `src/extensions/(backend)/api/log/`, so the mount is stated once, by the\n * folder that creates it. They used to be written here, in the contract, and\n * again inside every URL the page built, and the copies were free to disagree.\n *\n * This is the one file the routes, the Hono app and the browser all read, so a\n * path cannot move on one side alone.\n */\nexport default defineApiRoutes({\n metrics: {\n method: 'GET',\n path: '/metrics',\n query: [METRICS_QUERY_PARAMS.dimension, METRICS_QUERY_PARAMS.period, METRICS_QUERY_PARAMS.focus],\n response: apiResponse<MetricsResponse>(),\n },\n /**\n * Separate from the report because the hub answers it from a subprocess: the\n * running daemon exposes no issues route, so folding it in would make every\n * refresh wait on the slowest transport.\n */\n issues: {\n method: 'GET',\n path: '/issues',\n query: [METRICS_QUERY_PARAMS.focus],\n response: apiResponse<IssuesResponse>(),\n },\n});\n","import type { PoApi, PoApiContext, PoApiHandler } from '@agimon-ai/po-core/packageApi';\nimport type { LogMetricGroupRow, LogMetricsReport, ToolMetricRow } from '@agimon-ai/po-logsink';\nimport { Hono } from 'hono';\n\nimport { PACKAGE_NAME, SERVICE_NAME } from '../../constants/telemetry';\nimport { createIssuesSource } from '../../services/issuesSource';\nimport { createMetricsSource } from '../../services/metricsSource';\nimport routes from '../../types/apiRoutes';\nimport type { IssuesSource } from '../../types/issuesSource';\nimport type { MetricsFilter, MetricsSource } from '../../types/metricsSource';\nimport {\n isMetricsDimension,\n isMetricsPeriod,\n LOG_API_BASE_PATH,\n ISSUE_SAMPLE_LIMIT,\n METRICS_GROUP_LIMIT,\n METRICS_QUERY_PARAMS,\n METRICS_TOOL_LIMIT,\n type MetricsBucket,\n type MetricsDimension,\n type MetricsGroup,\n type MetricsPeriod,\n type MetricsReport,\n type MetricsTool,\n type MetricsUnavailable,\n type IssuesView,\n} from '../../types/webMetrics';\n\n/**\n * The cockpit's half of this package's metrics access.\n *\n * Hub-scoped rather than session-scoped: the questions this answers, where the\n * tokens went and which agents failed, are about the machine over time, and a\n * session server can only see itself. The sink is already machine-wide, so the\n * hub is the only place the two agree.\n *\n * The query path is not reimplemented here. `createMetricsSource` already owns\n * the sink's two transports and its fallback order, and the TUI overlay reads\n * through the same source, so both surfaces answer from one implementation.\n */\n\nconst DEFAULT_DIMENSION: MetricsDimension = 'model';\nconst DEFAULT_PERIOD: MetricsPeriod = 'week';\n\n/** The sink groups sessions under a different name than the page's dimension. */\nconst SINK_GROUP_BY = {\n session: 'session',\n agent: 'agent',\n model: 'model',\n provider: 'provider',\n} as const;\n\nfunction toBucket(bucket: LogMetricsReport['timeline'][number]): MetricsBucket {\n return {\n label: bucket.label,\n totalTokens: bucket.totalTokens,\n inputTokens: bucket.inputTokens,\n outputTokens: bucket.outputTokens,\n };\n}\n\nfunction toGroup(row: LogMetricGroupRow): MetricsGroup {\n return {\n key: row.key,\n totalTokens: row.totalTokens,\n inputTokens: row.inputTokens,\n outputTokens: row.outputTokens,\n issueCount: row.issueCount,\n failed: row.failed,\n };\n}\n\n/**\n * The turn's p90 rather than a sum: the sink attributes a whole turn's tokens\n * to every tool that ran in it, so adding them across calls would multiply the\n * same tokens by however many tools shared the turn.\n */\nfunction toTool(row: ToolMetricRow): MetricsTool {\n return {\n name: row.toolName,\n calls: row.invocationCount,\n p90TotalTokens: row.toolCallTurn.p90TotalTokens,\n };\n}\n\n/** Which filter field carries a focus value, per dimension. */\nconst FOCUS_FIELD: Record<MetricsDimension, keyof MetricsFilter> = {\n session: 'sessionId',\n agent: 'agentName',\n model: 'model',\n provider: 'provider',\n};\n\n/**\n * The focus the sink actually applied, read from its own echo.\n *\n * A daemon that predates a filter ignores it and answers with everything. If\n * the page trusted the request instead of this echo, it would label the whole\n * machine's numbers as one model's.\n */\nfunction appliedFocus(report: LogMetricsReport, dimension: MetricsDimension): string | undefined {\n // The daemon is a separate process on its own release cadence, so its\n // response is parsed defensively rather than trusted to carry every field.\n const filters = report.filters as LogMetricsReport['filters'] | undefined;\n if (filters === undefined) return undefined;\n if (dimension === 'session') return filters.sessionId;\n if (dimension === 'agent') return filters.agentName;\n const applied = dimension === 'model' ? filters.model : filters.provider;\n if (applied === undefined) return undefined;\n return Array.isArray(applied) ? applied[0] : applied;\n}\n\n/**\n * The sink's own type says Date, but both transports parse JSON, so what\n * arrives is an ISO string. Trusting the declared type here throws on every\n * real response, which no test using a hand-built Date would ever catch.\n */\nfunction generatedAtIso(value: Date | string): string {\n if (value instanceof Date) return value.toISOString();\n const parsed = new Date(value);\n return Number.isNaN(parsed.getTime()) ? new Date(0).toISOString() : parsed.toISOString();\n}\n\nfunction toReport(report: LogMetricsReport, source: MetricsSource, dimension: MetricsDimension): MetricsReport {\n const focus = appliedFocus(report, dimension);\n return {\n generatedAt: generatedAtIso(report.generatedAt),\n ...(report.filters?.startTime === undefined ? {} : { startTime: generatedAtIso(report.filters.startTime) }),\n endTime: generatedAtIso(report.filters?.endTime ?? report.generatedAt),\n dimension: report.groupBy as MetricsDimension,\n period: report.period as MetricsPeriod,\n bucketUnit: String(report.bucket),\n transport: source.lastTransport(),\n ...(focus === undefined ? {} : { focus }),\n totals: {\n usageEventCount: report.totals.usageEventCount,\n totalRecords: report.totals.totalRecords,\n totalTokens: report.totals.totalTokens,\n inputTokens: report.totals.inputTokens,\n outputTokens: report.totals.outputTokens,\n cachedTokens: report.totals.cachedInputTokens,\n reasoningTokens: report.totals.reasoningOutputTokens,\n groupCount: report.totals.groupCount,\n failedGroups: report.totals.failedGroups,\n issueCount: report.totals.issueCount,\n },\n timeline: report.timeline.map(toBucket),\n groups: report.groups.map(toGroup),\n tools: report.tools.rows.map(toTool),\n };\n}\n\n/**\n * A report with nothing in it reads as \"no data\", not as an empty chart. The\n * reader may have used the HTTP sink or a worker against an empty history, so\n * the empty-state detail must not claim the sink is running.\n */\nfunction isEmpty(report: MetricsReport): boolean {\n return report.totals.totalTokens === 0 && report.groups.length === 0 && report.tools.length === 0;\n}\n\nexport interface HubApiOptions {\n /** Injected by tests; production resolves the machine's sink. */\n source?: MetricsSource;\n issues?: IssuesSource;\n env?: NodeJS.ProcessEnv;\n}\n\nexport function createLogHubApi(options: HubApiOptions = {}): Hono {\n const app = new Hono();\n // One source for the life of the hub: it caches the resolved sink endpoint,\n // and rebuilding it per request would re-probe the daemon every time.\n const identity = {\n packageName: PACKAGE_NAME,\n serviceName: SERVICE_NAME,\n ...(options.env === undefined ? {} : { env: options.env }),\n };\n const source = options.source ?? createMetricsSource(identity);\n const issues = options.issues ?? createIssuesSource(identity);\n\n app.get(routes.metrics.path, async (context) => {\n const requestedDimension = context.req.query(METRICS_QUERY_PARAMS.dimension) ?? DEFAULT_DIMENSION;\n const requestedPeriod = context.req.query(METRICS_QUERY_PARAMS.period) ?? DEFAULT_PERIOD;\n if (!isMetricsDimension(requestedDimension)) {\n return context.json({ error: `Unknown dimension '${requestedDimension}'.` }, 400);\n }\n if (!isMetricsPeriod(requestedPeriod)) {\n return context.json({ error: `Unknown period '${requestedPeriod}'.` }, 400);\n }\n\n const focus = context.req.query(METRICS_QUERY_PARAMS.focus);\n const filter: MetricsFilter | undefined =\n focus === undefined || focus === '' ? undefined : { [FOCUS_FIELD[requestedDimension]]: focus };\n\n let report: LogMetricsReport;\n try {\n report = await source.query({\n groupBy: SINK_GROUP_BY[requestedDimension],\n period: requestedPeriod,\n limit: METRICS_GROUP_LIMIT,\n toolLimit: METRICS_TOOL_LIMIT,\n ...(filter === undefined ? {} : { filter }),\n });\n } catch (error) {\n // A missing daemon can still be read through its database. Failure of both\n // transports is a query fault, including a broken worker dependency graph.\n const unavailable: MetricsUnavailable = {\n unavailable: 'query-error',\n detail: error instanceof Error ? error.message : 'The metrics query failed.',\n };\n return context.json(unavailable);\n }\n\n const body = toReport(report, source, requestedDimension);\n if (isEmpty(body)) {\n const unavailable: MetricsUnavailable = {\n unavailable: 'no-data',\n detail: 'No recorded usage was found for this period.',\n };\n return context.json(unavailable);\n }\n return context.json(body);\n });\n\n /**\n * The detail behind the count the report carries. Separate from /metrics\n * because it costs a subprocess: the running daemon has no issues route, so\n * folding it into every report would make the whole page as slow as its\n * slowest transport.\n */\n app.get(routes.issues.path, async (context) => {\n const focus = context.req.query(METRICS_QUERY_PARAMS.focus);\n const startTime = context.req.query('startTime');\n const endTime = context.req.query('endTime');\n // Only ISO instants are accepted at this boundary, not locale-dependent dates.\n const validTime = (value: string | undefined): boolean =>\n value === undefined ||\n (/^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(?:\\.\\d+)?(?:Z|[+-]\\d{2}:\\d{2})$/.test(value) &&\n Number.isFinite(Date.parse(value)));\n if (\n !validTime(startTime) ||\n !validTime(endTime) ||\n (startTime !== undefined && endTime !== undefined && Date.parse(startTime) > Date.parse(endTime))\n ) {\n return context.json({ error: 'Issue time bounds must be valid ISO instants in chronological order.' }, 400);\n }\n try {\n const report = await issues.query({\n limit: ISSUE_SAMPLE_LIMIT,\n ...(startTime === undefined ? {} : { startTime }),\n ...(endTime === undefined ? {} : { endTime }),\n ...(focus === undefined || focus === '' ? {} : { sessionId: focus }),\n });\n return context.json(report satisfies IssuesView);\n } catch (error) {\n const unavailable: MetricsUnavailable = {\n unavailable: 'query-error',\n detail: error instanceof Error ? error.message : 'The issues query failed.',\n };\n return context.json(unavailable);\n }\n });\n\n return app;\n}\n\n/** The named export a host imports from this package's built hub entry. */\nexport const api: PoApi = {\n basePath: LOG_API_BASE_PATH,\n start(context: PoApiContext): PoApiHandler {\n const env = { ...context.environment };\n const source = createMetricsSource({ env, packageName: PACKAGE_NAME, serviceName: SERVICE_NAME });\n const app = createLogHubApi({ source, env });\n return {\n fetch: (request) => app.fetch(request),\n close: () => source.close?.(),\n };\n },\n};\n","import { defineRoute } from '@agimon-ai/po-core/extensionFile';\n\nimport { api } from '../../../../services/hubApi';\n\nexport default defineRoute(api);\n","import { defineServerCommand, type WithRoot } from '@agimon-ai/po-core/extensionFile';\nimport type { PoServerPluginContext } from '@agimon-ai/po-core/serverPlugin';\n\nimport type { LogServerScope } from '../_lib/serverRoot';\nexport default defineServerCommand(\n (context: WithRoot<PoServerPluginContext, LogServerScope>) => context.root.commands[0]!,\n);\n","import { defineHook, type WithRoot } from '@agimon-ai/po-core/extensionFile';\nimport type { PoServerPluginContext } from '@agimon-ai/po-core/serverPlugin';\n\nimport type { LogServerScope } from '../_lib/serverRoot';\nexport default defineHook((context: WithRoot<PoServerPluginContext, LogServerScope>) => context.root.hooks[9]!);\n","import { defineHook, type WithRoot } from '@agimon-ai/po-core/extensionFile';\nimport type { PoServerPluginContext } from '@agimon-ai/po-core/serverPlugin';\n\nimport type { LogServerScope } from '../_lib/serverRoot';\nexport default defineHook((context: WithRoot<PoServerPluginContext, LogServerScope>) => context.root.hooks[1]!);\n","import { defineHook, type WithRoot } from '@agimon-ai/po-core/extensionFile';\nimport type { PoServerPluginContext } from '@agimon-ai/po-core/serverPlugin';\n\nimport type { LogServerScope } from '../_lib/serverRoot';\nexport default defineHook((context: WithRoot<PoServerPluginContext, LogServerScope>) => context.root.hooks[7]!);\n","import { defineHook, type WithRoot } from '@agimon-ai/po-core/extensionFile';\nimport type { PoServerPluginContext } from '@agimon-ai/po-core/serverPlugin';\n\nimport type { LogServerScope } from '../_lib/serverRoot';\nexport default defineHook((context: WithRoot<PoServerPluginContext, LogServerScope>) => context.root.hooks[8]!);\n","import { defineHook, type WithRoot } from '@agimon-ai/po-core/extensionFile';\nimport type { PoServerPluginContext } from '@agimon-ai/po-core/serverPlugin';\n\nimport type { LogServerScope } from '../_lib/serverRoot';\nexport default defineHook((context: WithRoot<PoServerPluginContext, LogServerScope>) => context.root.hooks[2]!);\n","import { defineHook, type WithRoot } from '@agimon-ai/po-core/extensionFile';\nimport type { PoServerPluginContext } from '@agimon-ai/po-core/serverPlugin';\n\nimport type { LogServerScope } from '../_lib/serverRoot';\nexport default defineHook((context: WithRoot<PoServerPluginContext, LogServerScope>) => context.root.hooks[0]!);\n","import { defineHook, type WithRoot } from '@agimon-ai/po-core/extensionFile';\nimport type { PoServerPluginContext } from '@agimon-ai/po-core/serverPlugin';\n\nimport type { LogServerScope } from '../_lib/serverRoot';\nexport default defineHook((context: WithRoot<PoServerPluginContext, LogServerScope>) => context.root.hooks[6]!);\n","import { defineHook, type WithRoot } from '@agimon-ai/po-core/extensionFile';\nimport type { PoServerPluginContext } from '@agimon-ai/po-core/serverPlugin';\n\nimport type { LogServerScope } from '../_lib/serverRoot';\nexport default defineHook((context: WithRoot<PoServerPluginContext, LogServerScope>) => context.root.hooks[5]!);\n","import { defineHook, type WithRoot } from '@agimon-ai/po-core/extensionFile';\nimport type { PoServerPluginContext } from '@agimon-ai/po-core/serverPlugin';\n\nimport type { LogServerScope } from '../_lib/serverRoot';\nexport default defineHook((context: WithRoot<PoServerPluginContext, LogServerScope>) => context.root.hooks[4]!);\n","import { defineHook, type WithRoot } from '@agimon-ai/po-core/extensionFile';\nimport type { PoServerPluginContext } from '@agimon-ai/po-core/serverPlugin';\n\nimport type { LogServerScope } from '../_lib/serverRoot';\nexport default defineHook((context: WithRoot<PoServerPluginContext, LogServerScope>) => context.root.hooks[3]!);\n","export const DIAGNOSE_AGENT_NAME = 'diagnose_agent';\nexport const DIAGNOSE_AGENT_DESCRIPTION =\n '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.';\nexport const AGENT_DIAGNOSTIC_TOOL_LIMIT = 10;\nexport const AGENT_DIAGNOSTIC_MAX_TOOLS = 20;\nexport const AGENT_DIAGNOSTIC_TIMEOUT_MS = 15_000;\nexport const AGENT_ISSUE_CATEGORIES = [\n 'tool_failure',\n 'infrastructure_failure',\n 'caller_error',\n 'expected_failure',\n 'page_state',\n 'api_error',\n 'api_refusal',\n 'api_retries_exhausted',\n 'tool_rejected',\n 'log_error',\n] as const;\nexport const AGENT_DIAGNOSTIC_SKILL = {\n name: 'po-debug-agent',\n description:\n '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.',\n} as const;\n","import { defineResource } from '@agimon-ai/po-core/extensionFile';\nimport { PO_HELP_WHEN as HELP_WHEN } from '@agimon-ai/po-core/help';\nimport { packageResourcePath, readPackageResource } from '@agimon-ai/po-core/serverPlugin';\n\nimport { AGENT_DIAGNOSTIC_SKILL } from '../../../../../constants/diagnostics';\n\nexport default defineResource({\n ...AGENT_DIAGNOSTIC_SKILL,\n when: HELP_WHEN,\n kind: 'skill' as const,\n path: packageResourcePath(import.meta.url, 'src/prompts/po-debug-agent/SKILL.md'),\n read: () => readPackageResource(import.meta.url, 'src/prompts/po-debug-agent/SKILL.md'),\n});\n","import { Type } from 'typebox';\n\nimport { AGENT_DIAGNOSTIC_MAX_TOOLS } from '../constants/diagnostics';\n\nconst count = Type.Number({ minimum: 0 });\nconst coverage = Type.Number({ minimum: 0, maximum: 100 });\nexport const agentDiagnosticParameters = Type.Object(\n {\n period: Type.Optional(Type.Union([Type.Literal('day'), Type.Literal('week')])),\n toolLimit: Type.Optional(Type.Integer({ minimum: 1, maximum: AGENT_DIAGNOSTIC_MAX_TOOLS })),\n },\n { additionalProperties: false },\n);\n\n/** Validate only the fields we return. Extra upstream fields never cross this boundary. */\nexport const scopedMetricsSchema = Type.Object({\n groupBy: Type.Literal('session'),\n period: Type.Union([Type.Literal('day'), Type.Literal('week')]),\n filters: Type.Object({ sessionId: Type.String({ minLength: 1 }) }),\n totals: Type.Object({\n totalRecords: count,\n issueCount: count,\n usageEventCount: count,\n inputTokens: count,\n outputTokens: count,\n totalTokens: count,\n cachedInputTokens: count,\n reasoningOutputTokens: count,\n tokenCoveragePercent: coverage,\n }),\n groups: Type.Array(\n Type.Object({\n sessionId: Type.String({ minLength: 1 }),\n byCategory: Type.Record(Type.String(), count),\n }),\n { maxItems: 1 },\n ),\n tools: Type.Object({\n returnedTools: count,\n rows: Type.Array(\n Type.Object({\n toolName: Type.String({ minLength: 1, maxLength: 128, pattern: '^[A-Za-z0-9_./:-]+$' }),\n invocationCount: count,\n toolCallTurn: Type.Object({ samples: count, avgTotalTokens: count, p90TotalTokens: count }),\n }),\n { maxItems: AGENT_DIAGNOSTIC_MAX_TOOLS },\n ),\n }),\n});\n","import { PO_HELP_WHEN as HELP_WHEN } from '@agimon-ai/po-core/help';\nimport { defineTool } from '@agimon-ai/po-core/serverPlugin';\nimport type { Static } from 'typebox';\nimport { Check } from 'typebox/value';\n\nimport {\n AGENT_DIAGNOSTIC_TIMEOUT_MS,\n AGENT_DIAGNOSTIC_TOOL_LIMIT,\n AGENT_ISSUE_CATEGORIES,\n DIAGNOSE_AGENT_DESCRIPTION,\n DIAGNOSE_AGENT_NAME,\n} from '../../constants/diagnostics';\nimport { PACKAGE_NAME, SERVICE_NAME } from '../../constants/telemetry';\nimport { agentDiagnosticParameters, scopedMetricsSchema } from '../../schemas/agentDiagnostics';\nimport type { MetricsSource } from '../../types/metricsSource';\nimport { createMetricsSource, type MetricsSourceOptions } from '../metricsSource';\n\nexport async function readAgentDiagnostics(\n source: MetricsSource,\n sessionId: string,\n input: Static<typeof agentDiagnosticParameters>,\n signal: AbortSignal,\n) {\n const period = input.period ?? 'day';\n const limit = input.toolLimit ?? AGENT_DIAGNOSTIC_TOOL_LIMIT;\n signal.throwIfAborted();\n let onAbort = () => {};\n try {\n const report: unknown = await Promise.race([\n source.query({ groupBy: 'session', period, limit: 1, toolLimit: limit, filter: { sessionId } }),\n new Promise<never>((_resolve, reject) => {\n onAbort = () => reject(signal.reason);\n signal.addEventListener('abort', onAbort, { once: true });\n if (signal.aborted) onAbort();\n }),\n ]);\n signal.throwIfAborted();\n if (\n !Check(scopedMetricsSchema, report) ||\n report.filters.sessionId !== sessionId ||\n report.period !== period ||\n report.groups.some((group) => group.sessionId !== sessionId)\n ) {\n return { evidence: 'unavailable', code: 'METRICS_SCOPE_NOT_CONFIRMED', scope: 'current-session', period };\n }\n const totals = report.totals;\n return {\n scope: 'current-session',\n period,\n evidence: totals.totalRecords === 0 ? 'empty' : 'available',\n transport: source.lastTransport(),\n capturedRecords: totals.totalRecords,\n capturedIssues: totals.issueCount,\n issuesByCategory: Object.fromEntries(\n AGENT_ISSUE_CATEGORIES.map((category) => [category, report.groups[0]?.byCategory[category] ?? 0]),\n ),\n usage: {\n inputTokens: totals.inputTokens,\n outputTokens: totals.outputTokens,\n totalTokens: totals.totalTokens,\n cachedInputTokens: totals.cachedInputTokens,\n reasoningOutputTokens: totals.reasoningOutputTokens,\n usageEventCount: totals.usageEventCount,\n tokenCoveragePercent: totals.tokenCoveragePercent,\n },\n tools: report.tools.rows.slice(0, limit).map((tool) => ({\n name: tool.toolName,\n invocations: tool.invocationCount,\n sampledTurns: tool.toolCallTurn.samples,\n averageTurnTokens: tool.toolCallTurn.avgTotalTokens,\n p90TurnTokens: tool.toolCallTurn.p90TotalTokens,\n })),\n toolRowLimit: limit,\n limitReached: report.tools.rows.length >= limit,\n captureCompleteness: 'not-reported',\n limitations:\n '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.',\n };\n } catch (error) {\n if (signal.aborted) throw error;\n return { evidence: 'unavailable', code: 'METRICS_UNAVAILABLE', scope: 'current-session', period };\n } finally {\n signal.removeEventListener('abort', onAbort);\n }\n}\n\nexport function createAgentDiagnosticsTool(\n readScope: () => { sessionId: string; options: MetricsSourceOptions },\n authorize: (signal?: AbortSignal) => AbortSignal,\n) {\n return defineTool({\n name: DIAGNOSE_AGENT_NAME,\n description: DIAGNOSE_AGENT_DESCRIPTION,\n parameters: agentDiagnosticParameters,\n when: HELP_WHEN,\n executionMode: 'serial',\n async execute(input, execution) {\n const active = authorize(execution.signal);\n const signal = AbortSignal.any([active, AbortSignal.timeout(AGENT_DIAGNOSTIC_TIMEOUT_MS)]);\n const scope = readScope();\n if (!scope.sessionId) throw new Error('Agent diagnostics require an active session.');\n const source = createMetricsSource({ packageName: PACKAGE_NAME, serviceName: SERVICE_NAME, ...scope.options });\n try {\n const report = await readAgentDiagnostics(source, scope.sessionId, input, signal);\n signal.throwIfAborted();\n authorize(execution.signal);\n return { content: [{ type: 'text', text: JSON.stringify(report, null, 2) }], details: report };\n } finally {\n await source.close?.();\n }\n },\n });\n}\n","import { defineTool } from '@agimon-ai/po-core/extensionFile';\nimport type { PoServerPluginContext } from '@agimon-ai/po-core/serverPlugin';\n\nimport { PACKAGE_NAME } from '../../../../../constants/telemetry';\nimport { createAgentDiagnosticsTool } from '../../../../../services/agentDiagnostics';\n\nexport default defineTool(({ agent, signal: ownerSignal }: PoServerPluginContext) => {\n if (!agent) throw new Error('Agent diagnostics require a session host.');\n return createAgentDiagnosticsTool(\n () => ({\n sessionId: agent.context.sessionId,\n options: {\n cwd: agent.context.cwd,\n env: { ...agent.context.environment, PI_SESSION_ID: agent.context.sessionId },\n },\n }),\n (signal) => {\n ownerSignal.throwIfAborted();\n signal?.throwIfAborted();\n agent.assertActive(PACKAGE_NAME);\n if (!(agent.context.selection.state?.['minor-mode'] ?? []).includes('help'))\n throw new Error('Help mode is not active.');\n return signal ? AbortSignal.any([signal, ownerSignal]) : ownerSignal;\n },\n );\n});\n","// Generated by @agimon-ai/po-build. Do not edit by hand.\nimport { defineServerPlugin, type PoServerSessionPlugin } from '@agimon-ai/po-core/serverPlugin';\nimport { composeServerProviderOverrides } from '@agimon-ai/po-core/serverPlugin';\nimport { composeRootHooks, composeRootInjects } from '@agimon-ai/po-core/extensionFile';\n\nimport rootSession from '../src/extensions/workspaces/sessions/(backend)/root.server';\nimport apiRoute from '../src/extensions/(backend)/api/log/route.server';\nimport commandLogMetrics from '../src/extensions/workspaces/sessions/(backend)/command/log-metrics.server';\nimport hookAgentEnd from '../src/extensions/workspaces/sessions/(backend)/hook/agent-end.server';\nimport hookAgentSettled from '../src/extensions/workspaces/sessions/(backend)/hook/agent-settled.server';\nimport hookAgentStart from '../src/extensions/workspaces/sessions/(backend)/hook/agent-start.server';\nimport hookModelSelect from '../src/extensions/workspaces/sessions/(backend)/hook/model-select.server';\nimport hookSessionShutdown from '../src/extensions/workspaces/sessions/(backend)/hook/session-shutdown.server';\nimport hookSessionStart from '../src/extensions/workspaces/sessions/(backend)/hook/session-start.server';\nimport hookToolExecutionEnd from '../src/extensions/workspaces/sessions/(backend)/hook/tool-execution-end.server';\nimport hookToolExecutionStart from '../src/extensions/workspaces/sessions/(backend)/hook/tool-execution-start.server';\nimport hookTurnEnd from '../src/extensions/workspaces/sessions/(backend)/hook/turn-end.server';\nimport hookTurnStart from '../src/extensions/workspaces/sessions/(backend)/hook/turn-start.server';\nimport resourcePoDebugAgent from '../src/extensions/workspaces/sessions/(backend)/resource/po-debug-agent.server';\nimport toolDiagnoseAgent from '../src/extensions/workspaces/sessions/(backend)/tool/diagnose_agent.server';\n\ntype Factory<T, C> = (context: C) => T;\nconst at = <T, C>(value: T | Factory<T, C>, context: C): T =>\n typeof value === 'function' ? (value as Factory<T, C>)(context) : value;\nconst via = <T>(identity: Record<string, unknown>, value: unknown): T =>\n (value === undefined ? undefined : { ...identity, ...(value as object) }) as T;\n\nexport const serverPlugin = defineServerPlugin({\n name: '@agimon-ai/po-log',\n providerOverrides: composeServerProviderOverrides(rootSession),\n injects: composeRootInjects({ session: [rootSession] }),\n global: (context) => ({\n get api(): PoServerSessionPlugin['api'] { return [at(apiRoute, context)]; },\n }),\n workspace: (context) => ({\n get api(): PoServerSessionPlugin['api'] { return [at(apiRoute, context)]; },\n }),\n session: async (context) => {\n const scopeSession = await context.scopeRoot('session', rootSession, context);\n const contextSession = { ...context, root: scopeSession.value };\n return {\n ...composeRootHooks(scopeSession),\n get api(): PoServerSessionPlugin['api'] { return [at(apiRoute, context)]; },\n get commands(): PoServerSessionPlugin['commands'] { return [via({ name: 'log-metrics' }, at(commandLogMetrics, contextSession))]; },\n get hooks(): PoServerSessionPlugin['hooks'] { return [via({ event: 'agent_end' }, at(hookAgentEnd, contextSession)), via({ event: 'agent_settled' }, at(hookAgentSettled, contextSession)), via({ event: 'agent_start' }, at(hookAgentStart, contextSession)), via({ event: 'model_select' }, at(hookModelSelect, contextSession)), via({ event: 'session_shutdown' }, at(hookSessionShutdown, contextSession)), via({ event: 'session_start' }, at(hookSessionStart, contextSession)), via({ event: 'tool_execution_end' }, at(hookToolExecutionEnd, contextSession)), via({ event: 'tool_execution_start' }, at(hookToolExecutionStart, contextSession)), via({ event: 'turn_end' }, at(hookTurnEnd, contextSession)), via({ event: 'turn_start' }, at(hookTurnStart, contextSession))]; },\n get resources(): PoServerSessionPlugin['resources'] { return [at(resourcePoDebugAgent, contextSession)]; },\n get tools(): PoServerSessionPlugin['tools'] { return [via({ name: 'diagnose_agent' }, at(toolDiagnoseAgent, contextSession))]; },\n services: [...(scopeSession.services ?? [])],\n get activities(): PoServerSessionPlugin['activities'] { return [...(scopeSession.activities ?? [])]; },\n };\n },\n});\n\nexport default serverPlugin;\n"],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AC,CAAC;GAAG;GAClI,IAAI,QAAwC;IAAE,OAAO;KAAC,IAAI,EAAE,OAAO,YAAY,GAAG,GAAGC,0BAAc,cAAc,CAAC;KAAG,IAAI,EAAE,OAAO,gBAAgB,GAAG,GAAGC,8BAAkB,cAAc,CAAC;KAAG,IAAI,EAAE,OAAO,cAAc,GAAG,GAAGC,4BAAgB,cAAc,CAAC;KAAG,IAAI,EAAE,OAAO,eAAe,GAAG,GAAGC,6BAAiB,cAAc,CAAC;KAAG,IAAI,EAAE,OAAO,mBAAmB,GAAG,GAAGC,iCAAqB,cAAc,CAAC;KAAG,IAAI,EAAE,OAAO,gBAAgB,GAAG,GAAGC,8BAAkB,cAAc,CAAC;KAAG,IAAI,EAAE,OAAO,qBAAqB,GAAG,GAAGC,mCAAsB,cAAc,CAAC;KAAG,IAAI,EAAE,OAAO,uBAAuB,GAAG,GAAGC,qCAAwB,cAAc,CAAC;KAAG,IAAI,EAAE,OAAO,WAAW,GAAG,GAAGC,yBAAa,cAAc,CAAC;KAAG,IAAI,EAAE,OAAO,aAAa,GAAG,GAAGC,2BAAe,cAAc,CAAC;IAAC;GAAG;GAC3vB,IAAI,YAAgD;IAAE,OAAO,CAAC,GAAGC,+BAAsB,cAAc,CAAC;GAAG;GACzG,IAAI,QAAwC;IAAE,OAAO,CAAC,IAAI,EAAE,MAAM,iBAAiB,GAAG,GAAGC,+BAAmB,cAAc,CAAC,CAAC;GAAG;GAC/H,UAAU,CAAC,GAAI,aAAa,YAAY,CAAC,CAAE;GAC3C,IAAI,aAAkD;IAAE,OAAO,CAAC,GAAI,aAAa,cAAc,CAAC,CAAE;GAAG;EACvG;CACF;AACF,CAAC"}
1
+ {"version":3,"file":"server.mjs","names":["PACKAGE_NAME","PACKAGE_NAME","PACKAGE_NAME","isRecord","toReport","toReport","PACKAGE_NAME","HELP_WHEN","defineTool","defineTool","defineTool","defineTool","defineTool","defineTool","defineTool","rootSession","apiRoute","commandLogMetrics","hookAgentEnd","hookAgentSettled","hookAgentStart","hookBeforeProviderRequest","hookModelSelect","hookSessionShutdown","hookSessionStart","hookToolExecutionEnd","hookToolExecutionStart","hookTurnEnd","hookTurnStart","resourceCodemodeHowToLogsink","resourceHelpHowToLog","toolLogsinkAgentIssues","toolLogsinkMetrics","toolLogsinkSearch","toolLogsinkServices","toolLogsinkStats","toolLogsinkStatus","toolLogsinkTrace"],"sources":["../../src/constants/telemetry.ts","../../src/schemas/logsink.ts","../../src/services/logQuerySource/index.ts","../../src/services/logsink/index.ts","../../src/services/logsinkNamespace/index.ts","../../src/services/metricsForwarder/index.ts","../../src/services/telemetryEnabled/index.ts","../../src/services/serverTelemetry/index.ts","../../src/extensions/workspaces/sessions/(backend)/_lib/serverRoot.ts","../../src/extensions/workspaces/sessions/(backend)/root.server.ts","../../src/services/issuesSource/report.ts","../../src/services/issuesSource/index.ts","../../src/types/webMetrics.ts","../../src/types/apiRoutes.ts","../../src/services/hubApi/index.ts","../../src/extensions/(backend)/api/log/route.server.ts","../../src/extensions/workspaces/sessions/(backend)/command/log-metrics.server.ts","../../src/extensions/workspaces/sessions/(backend)/hook/agent-end.server.ts","../../src/extensions/workspaces/sessions/(backend)/hook/agent-settled.server.ts","../../src/extensions/workspaces/sessions/(backend)/hook/agent-start.server.ts","../../src/extensions/workspaces/sessions/(backend)/hook/before-provider-request.server.ts","../../src/extensions/workspaces/sessions/(backend)/hook/model-select.server.ts","../../src/extensions/workspaces/sessions/(backend)/hook/session-shutdown.server.ts","../../src/extensions/workspaces/sessions/(backend)/hook/session-start.server.ts","../../src/extensions/workspaces/sessions/(backend)/hook/tool-execution-end.server.ts","../../src/extensions/workspaces/sessions/(backend)/hook/tool-execution-start.server.ts","../../src/extensions/workspaces/sessions/(backend)/hook/turn-end.server.ts","../../src/extensions/workspaces/sessions/(backend)/hook/turn-start.server.ts","../../src/extensions/workspaces/sessions/(backend)/resource/codemode-how-to-logsink.server.ts","../../src/constants/diagnostics.ts","../../src/extensions/workspaces/sessions/(backend)/resource/help-how-to-log.server.ts","../../src/extensions/workspaces/sessions/(backend)/tool/logsink_agent_issues.server.ts","../../src/extensions/workspaces/sessions/(backend)/tool/logsink_metrics.server.ts","../../src/extensions/workspaces/sessions/(backend)/tool/logsink_search.server.ts","../../src/extensions/workspaces/sessions/(backend)/tool/logsink_services.server.ts","../../src/extensions/workspaces/sessions/(backend)/tool/logsink_stats.server.ts","../../src/extensions/workspaces/sessions/(backend)/tool/logsink_status.server.ts","../../src/extensions/workspaces/sessions/(backend)/tool/logsink_trace.server.ts","../../generated/server.ts"],"sourcesContent":["export const SERVICE_NAME = 'pi';\nexport const PACKAGE_NAME = '@agimon-ai/po-log';\n/** Opt back into stderr diagnostics when debugging outside a live TUI. */\nexport const DIAGNOSTICS_STDERR = 'stderr';\nexport const LEADER_SOURCE = '@agimon-ai/po-log';\nexport const LOG_METRICS_COMMAND = 'log-metrics';\nexport const LOG_METRICS_DESCRIPTION = 'Show session-local log metrics';\nexport const HELP_GROUP_ORDER = 70;\n/** Must match the Help group published by po-ui, or the registry drops this. */\nexport const HELP_GROUP_DETAIL = 'package docs and logs';\nexport const NO_ENDPOINT = 'none';\nexport const API_ERROR_STATUS = 400;\nexport const FAILURE_STOP_REASONS = ['error', 'aborted'];\nexport const LOCAL_LOG_HISTORY_UNAVAILABLE_MESSAGE = 'Local Log Sink queries are unavailable on this host.';\n","import { sanitizeTelemetryAttributes } from '@agimon-ai/po-core/telemetry';\nimport {\n LOG_QUERY_INPUT_SCHEMAS,\n parseLogQueryInput,\n type LogQueryInputs,\n type LogQueryMethod,\n type LogQueryResults,\n} from '@agimon-ai/po-logsink/queryContracts';\nimport { Type } from 'typebox';\n\nexport const LOGSINK_METHODS = [\n 'status',\n 'search',\n 'agentIssues',\n 'trace',\n 'stats',\n 'services',\n 'metrics',\n] as const satisfies readonly LogQueryMethod[];\nexport const LOGSINK_TOOL_NAMES = LOGSINK_METHODS.map(\n (method) => `logsink_${method.replace(/[A-Z]/g, (letter) => `_${letter.toLowerCase()}`)}`,\n);\n\nexport interface LogsinkScope {\n kind: 'session' | 'history';\n sessionId?: string;\n startTime?: string;\n endTime?: string;\n}\n\nexport interface LogsinkResponse<K extends LogQueryMethod> {\n scope: LogsinkScope;\n data: LogQueryResults[K];\n}\n\n/** The direct tools advertise the same schema the reader validates, plus Po's scope selector. */\nexport function logsinkParameters(method: LogQueryMethod) {\n const schema = LOG_QUERY_INPUT_SCHEMAS[method];\n return Type.Unsafe<Record<string, unknown>>({\n ...schema,\n properties: {\n ...(schema.properties as Record<string, unknown>),\n ...(method === 'status'\n ? {}\n : {\n scope: {\n type: 'string',\n enum: ['session', 'history'],\n description: 'Defaults to this session. History requires explicit startTime and endTime.',\n },\n }),\n },\n });\n}\n\nexport function parseLogsinkInput<K extends LogQueryMethod>(\n method: K,\n value: unknown,\n sessionId: string,\n): { scope: LogsinkScope; input: LogQueryInputs[K] } {\n if (!value || typeof value !== 'object' || Array.isArray(value))\n throw new Error('Log query input must be an object.');\n const { scope: requestedScope, ...query } = value as Record<string, unknown>;\n const storedSessionId = sanitizeTelemetryAttributes({ 'pi.session.id': sessionId })['pi.session.id'];\n if (typeof storedSessionId !== 'string') throw new Error('Log queries require a valid session identity.');\n if (method === 'status') {\n if (requestedScope !== undefined) throw new Error('status does not accept a scope.');\n return { scope: { kind: 'session', sessionId: storedSessionId }, input: parseLogQueryInput(method, query) };\n }\n const kind = requestedScope ?? 'session';\n if (kind !== 'session' && kind !== 'history') throw new Error('scope must be session or history.');\n if (kind === 'session') {\n if (query.sessionId !== undefined && query.sessionId !== sessionId && query.sessionId !== storedSessionId)\n throw new Error('Use explicit history scope to query another session.');\n query.sessionId = storedSessionId;\n } else if (typeof query.startTime !== 'string' || typeof query.endTime !== 'string') {\n throw new Error('History queries require explicit ISO startTime and endTime.');\n }\n const input = parseLogQueryInput(method, query);\n const filters = input as Record<string, unknown>;\n return {\n scope: {\n kind,\n ...(typeof filters.sessionId === 'string' ? { sessionId: filters.sessionId } : {}),\n ...(typeof filters.startTime === 'string' ? { startTime: filters.startTime } : {}),\n ...(typeof filters.endTime === 'string' ? { endTime: filters.endTime } : {}),\n },\n input,\n };\n}\n","import { createAsyncLogQueryReader, resolveGlobalLogQueryDbPath, type LogQueryReader } from '@agimon-ai/po-logsink';\n\n/** The host supplies its home; inspection must not run the sink's directory-creating resolver. */\nexport function createLogQuerySource(homeDirectory?: string): LogQueryReader {\n if (!homeDirectory) throw new Error('Log queries require the host home directory.');\n return createAsyncLogQueryReader({ dbPath: resolveGlobalLogQueryDbPath(homeDirectory) });\n}\n","import { defineTool } from '@agimon-ai/po-core/serverPlugin';\nimport type { LogQueryReader } from '@agimon-ai/po-logsink';\nimport type { LogQueryInputs, LogQueryMethod, LogQueryResults } from '@agimon-ai/po-logsink/queryContracts';\n\nimport {\n LOGSINK_METHODS,\n LOGSINK_TOOL_NAMES,\n logsinkParameters,\n parseLogsinkInput,\n type LogsinkResponse,\n} from '../../schemas/logsink';\nimport { createLogQuerySource } from '../logQuerySource';\n\nconst DESCRIPTIONS: Record<LogQueryMethod, string> = {\n status: 'Check whether retained Log Sink data is available without starting a collector.',\n search: 'Search retained logs with structured filters and optional FTS text.',\n agentIssues: 'Aggregate captured agent failures, then inspect bounded issue samples and coverage.',\n trace: 'Read a bounded chronological trace within the selected session or history scope.',\n stats: 'Aggregate retained log statistics within the selected scope.',\n services: 'List services with retained records within the selected scope.',\n metrics: 'Inspect captured token usage, tool turn costs, and failure metrics.',\n};\n\nexport interface LogsinkOptions {\n sessionId: string;\n homeDirectory?: string;\n authorize(signal?: AbortSignal): AbortSignal;\n createReader?: () => LogQueryReader;\n}\n\nexport function createLogsinkOperations(options: LogsinkOptions) {\n return {\n sessionId: options.sessionId,\n async read<K extends LogQueryMethod>(\n method: K,\n value: unknown = {},\n inputSignal?: AbortSignal,\n ): Promise<LogsinkResponse<K>> {\n const active = options.authorize(inputSignal);\n const signal = AbortSignal.any([active, AbortSignal.timeout(25000)]);\n const parsed = parseLogsinkInput(method, value, options.sessionId);\n signal.throwIfAborted();\n const reader = options.createReader?.() ?? createLogQuerySource(options.homeDirectory);\n let report: LogsinkResponse<K>;\n try {\n const data =\n method === 'status'\n ? await reader.status(signal)\n : await (reader[method] as (input: LogQueryInputs[K], signal: AbortSignal) => Promise<LogQueryResults[K]>)(\n parsed.input,\n signal,\n );\n report = JSON.parse(JSON.stringify({ scope: parsed.scope, data })) as LogsinkResponse<K>;\n } finally {\n await reader.close();\n }\n signal.throwIfAborted();\n options.authorize(inputSignal);\n return report;\n },\n };\n}\n\nexport type LogsinkOperations = ReturnType<typeof createLogsinkOperations>;\n\nexport function createLogsinkTool(method: LogQueryMethod, operations?: LogsinkOperations) {\n if (!operations) throw new Error('Log Sink tools require a session host.');\n return defineTool({\n name: LOGSINK_TOOL_NAMES[LOGSINK_METHODS.indexOf(method)],\n description: `${DESCRIPTIONS[method]} Defaults to this session. Cross-session workflow analysis requires scope: history and explicit startTime/endTime.`,\n parameters: logsinkParameters(method),\n async execute(input, execution) {\n const report = await operations.read(method, input, execution.signal);\n return { content: [{ type: 'text', text: JSON.stringify(report) }], details: report };\n },\n });\n}\n","import type { PoCodemodeNamespace } from '@agimon-ai/po-core/codemode';\n\nimport { LOGSINK_METHODS, LOGSINK_TOOL_NAMES } from '../../schemas/logsink';\nimport type { LogsinkOperations } from '../logsink';\n\nconst DECLARATIONS = `interface LogScope { kind: 'session' | 'history'; sessionId?: string; startTime?: string; endTime?: string }\ninterface LogResponse<T> { scope: LogScope; data: T }\ninterface LogPage { offset: number; limit: number; hasMore: boolean; nextOffset: number | null }\ninterface LogFilters {\n scope?: 'session' | 'history'; sessionId?: string; startTime?: string; endTime?: string;\n workflowRunId?: string; workflowName?: string; jobName?: string; jobId?: string;\n agentName?: string; workflowRunKey?: string; workflowWorkspace?: string; stepName?: string; phase?: string;\n service?: string | string[];\n}\ninterface LogAvailability { available: boolean; reason?: 'missing-database' }\ninterface LogRecord {\n id: string; timestamp: string; level: string; service: string; message: string;\n sessionId: string | null; traceId: string | null; spanId: string | null;\n metadata: Record<string, unknown> | null; errorType: string | null; errorMessage: string | null;\n [field: string]: unknown;\n}\ninterface LogSearch { mode: 'filter' | 'fts'; count: number; total: number; truncated: boolean; results: LogRecord[]; pagination: LogPage }\ninterface LogIssue {\n category: string; timestamp: string; service: string; sessionId: string | null; tool: string | null;\n errorType: string | null; message: string; detail: string | null; fingerprint: string; occurrenceCount: number;\n traceId: string | null; spanId: string | null; [field: string]: unknown;\n}\ninterface LogIssues {\n scanned: number; matchingLogs: number; truncated: boolean; coveragePercent: number; oldestScannedTimestamp: string | null;\n totalIssues: number; uniqueIncidents: number; byCategory: Record<string, number>; byTool: Record<string, number>;\n byErrorType: Record<string, number>; bySession: Record<string, number>; issues: LogIssue[]; pagination: LogPage;\n}\ninterface LogTraceEntry { timestamp: string; service: string; spanId: string | null; parentSpanId: string | null; level: string; message: string; [field: string]: unknown }\ninterface LogTrace { traceId: string; count: number; truncated: boolean; timeline: LogTraceEntry[]; pagination: LogPage }\ninterface LogStats { groupBy: string; signalType: 'log' | 'span' | 'all'; totalEntries: number; statistics: { service: string; level: string; count: number }[]; pagination: LogPage }\ninterface LogServices { count: number; truncated: boolean; services: string[]; pagination: LogPage }\ninterface LogTokens {\n inputTokens: number; totalPromptTokens: number; outputTokens: number; totalTokens: number;\n cachedInputTokens: number; reasoningOutputTokens: number; usageEventCount: number;\n /** Completed requests with explicit cache-read usage. */\n requestCache: { measuredRequests: number; hitRequests: number; totalPromptTokens: number; cachedInputTokens: number };\n}\ninterface LogTokenDistribution { samples: number; avgInputTokens: number; p50InputTokens: number; p90InputTokens: number; avgOutputTokens: number; p50OutputTokens: number; p90OutputTokens: number; avgTotalTokens: number; p50TotalTokens: number; p90TotalTokens: number }\ninterface LogMetrics {\n generatedAt: string; groupBy: string; sort: string; toolSort: string; period: string; bucket: string;\n filters: Record<string, unknown>;\n totals: LogTokens & { totalRecords: number; issueCount: number; groupCount: number; returnedGroups: number; tokenCoveragePercent: number; [field: string]: unknown };\n groups: (LogTokens & { key: string; sessionId: string | null; issueCount: number; byCategory: Record<string, number>; [field: string]: unknown })[];\n tools: { returnedTools: number; rows: { toolName: string; invocationCount: number; toolCallTurn: LogTokenDistribution; toolOutputImpact: LogTokenDistribution; [field: string]: unknown }[] };\n timeline: (LogTokens & { bucketStart: string; label: string; totalRecords: number; issueCount: number })[];\n pagination: { groups: LogPage; tools: LogPage; timeline: LogPage };\n}\ndeclare const logsink: {\n /** Retained storage availability, not proof that the collector is capturing now. */\n status(): Promise<LogResponse<LogAvailability>>;\n /** 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. */\n 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>>;\n /** Pages deduplicated incidents, not scan coverage. Totals cover the whole bounded scan; truncated describes that scan. */\n agentIssues(input?: LogFilters & { limit?: number; offset?: number; scanLimit?: number }): Promise<LogResponse<LogIssues>>;\n /** A bounded trace page, filtered within scope before retrieval. */\n trace(input: LogFilters & { traceId: string; limit?: number; offset?: number }): Promise<LogResponse<LogTrace>>;\n /** Pages counts by level, service, agent, workflow, job or signal. totalEntries covers all matching groups. */\n stats(input?: LogFilters & { groupBy?: 'level' | 'service' | 'both' | 'agent' | 'workflow' | 'job' | 'signal'; signalType?: 'log' | 'span' | 'all'; limit?: number; offset?: number }): Promise<LogResponse<LogStats>>;\n /** Services that have retained records within scope, alphabetically paged. */\n services(input?: LogFilters & { limit?: number; offset?: number }): Promise<LogResponse<LogServices>>;\n /** 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. */\n 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>>;\n};`;\n\n// codemode drops recorded details over 16,000 characters, which leaves the log card blank;\n// the transcript copy stays under that by cutting record lists, never counts or scope.\nconst MAX_TRANSCRIPT_JSON = 12_000;\nconst TRANSCRIPT_LIST_SIZES = [20, 5, 0];\nconst RECORD_LISTS = new Set(['results', 'timeline', 'issues', 'groups', 'rows', 'statistics', 'services']);\nconst RUN_DISPOSED = 'Log Sink run is disposed.';\n\nfunction cutLists(value: unknown, size: number): unknown {\n if (Array.isArray(value)) return value.map((item) => cutLists(item, size));\n if (value === null || typeof value !== 'object') return value;\n return Object.fromEntries(\n Object.entries(value).map(([key, item]) => [\n key,\n RECORD_LISTS.has(key) && Array.isArray(item) ? item.slice(0, size) : cutLists(item, size),\n ]),\n );\n}\n\n/** The result as the transcript keeps it: whole when small, otherwise with record lists cut and a note. */\nexport function transcriptCopy(result: unknown): unknown {\n const json = JSON.stringify(result);\n if (json === undefined || json.length <= MAX_TRANSCRIPT_JSON)\n return json === undefined ? undefined : JSON.parse(json);\n for (const size of TRANSCRIPT_LIST_SIZES) {\n const cut = cutLists(JSON.parse(json), size);\n const kept = {\n ...(cut as Record<string, unknown>),\n note: `Transcript copy keeps at most ${size} items per record list; the script received every record in the requested page.`,\n };\n if (JSON.stringify(kept).length <= MAX_TRANSCRIPT_JSON) return kept;\n }\n return undefined;\n}\n\nexport function createLogsinkNamespace(operations: LogsinkOperations): PoCodemodeNamespace {\n return {\n name: 'logsink',\n summary:\n '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.',\n declarations: DECLARATIONS,\n portable: true,\n bind(run) {\n if (run.sessionId !== operations.sessionId) throw new Error('Log Sink namespace belongs to another session.');\n let disposed = false;\n const controller = new AbortController();\n run.onDispose(() => {\n disposed = true;\n controller.abort(new Error(RUN_DISPOSED));\n });\n const signal = AbortSignal.any([run.signal, controller.signal]);\n const check = () => {\n signal.throwIfAborted();\n if (disposed) throw new Error(RUN_DISPOSED);\n };\n const members: Record<string, unknown> = Object.create(null);\n for (const method of LOGSINK_METHODS) {\n members[method] = async (input: unknown = {}) => {\n const started = Date.now();\n let args: Record<string, unknown> = {};\n let result: unknown;\n try {\n check();\n const snapshot: unknown = JSON.parse(JSON.stringify(input));\n if (snapshot && typeof snapshot === 'object' && !Array.isArray(snapshot)) {\n args = snapshot as Record<string, unknown>;\n }\n result = await operations.read(method, input, signal);\n check();\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n run.record?.({\n name: `logsink.${method}`,\n tool: LOGSINK_TOOL_NAMES[LOGSINK_METHODS.indexOf(method)],\n args,\n ok: false,\n ms: Date.now() - started,\n error: message,\n result: { content: [{ type: 'text', text: message }] },\n });\n throw error;\n }\n const details = transcriptCopy(result);\n run.record?.({\n name: `logsink.${method}`,\n tool: LOGSINK_TOOL_NAMES[LOGSINK_METHODS.indexOf(method)],\n args,\n ok: true,\n ms: Date.now() - started,\n result: {\n content: [\n {\n type: 'text',\n text: details === undefined ? '[log result too large to keep]' : JSON.stringify(details),\n },\n ],\n details,\n },\n });\n return result;\n };\n }\n return members;\n },\n };\n}\n","import { METRICS_ATTRIBUTE, METRICS_MAX_ENTRIES_PER_CALL } from '../../constants/metricsStore';\nimport type { LogMetricsAttributes, LogMetricsEntry } from '../metricsStore/type';\nimport type { MetricsForwarder, MetricsForwarderOptions } from './type';\n\nconst RECORD_FAILED = 'Metrics could not be recorded.';\nconst METRICS_ENTRY_ATTRIBUTES: ReadonlySet<string> = new Set(Object.values(METRICS_ATTRIBUTE));\n\n/** Only the fixed, scalar attributes a metrics entry may carry leave the session. */\nfunction fixedAttributes(attributes: Record<string, unknown>): LogMetricsAttributes {\n const kept: Record<string, string | number | boolean> = {};\n for (const [key, value] of Object.entries(attributes)) {\n if (!METRICS_ENTRY_ATTRIBUTES.has(key)) continue;\n if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') kept[key] = value;\n }\n return kept;\n}\n\n/**\n * Hands a session's sanitized telemetry records to the metrics service a host bound, in batches.\n *\n * A host that bound none, such as one that keeps the log sink, queues nothing. Records made in the same tick\n * travel together, so a session pays one call for a turn rather than one per record.\n */\nexport function createMetricsForwarder(options: MetricsForwarderOptions): MetricsForwarder {\n const now = options.now ?? Date.now;\n let waiting: LogMetricsEntry[] = [];\n let scheduled = false;\n\n const flush = async (): Promise<void> => {\n scheduled = false;\n const batch = waiting;\n waiting = [];\n if (batch.length === 0) return;\n const service = options.resolve();\n // Unbound between the record and now: the host kept no store, so there is nowhere to send it.\n if (service === undefined) return;\n for (let start = 0; start < batch.length; start += METRICS_MAX_ENTRIES_PER_CALL) {\n try {\n await service.record(batch.slice(start, start + METRICS_MAX_ENTRIES_PER_CALL));\n } catch {\n // The failure's message may carry what the store refused, so only the fact of it is reported.\n options.onDiagnostic?.(RECORD_FAILED);\n }\n }\n };\n\n return {\n record(name, attributes) {\n if (options.resolve() === undefined) return;\n waiting.push({ at: now(), event: name, attributes: fixedAttributes(attributes) });\n if (scheduled) return;\n scheduled = true;\n queueMicrotask(() => {\n flush().catch(() => options.onDiagnostic?.(RECORD_FAILED));\n });\n },\n flush,\n };\n}\n","export function isEnabled(value: string | undefined): boolean {\n return value === '1' || value?.toLowerCase() === 'true' || value?.toLowerCase() === 'yes';\n}\n","import type { PoChildSessionHooks } from '@agimon-ai/po-core/childSession';\nimport type {\n PoHeadlessActivity,\n PoHeadlessCommand,\n PoHeadlessExecutionContext,\n PoHeadlessHook,\n} from '@agimon-ai/po-core/headless';\nimport { readPoLang, readPoPersonLocale, translateMessage } from '@agimon-ai/po-core/locale';\nimport { isRecord } from '@agimon-ai/po-core/runtimeJson';\nimport { createPoTelemetry, type PoTelemetry, type PoTraceContext } from '@agimon-ai/po-core/telemetry';\nimport type { Context } from '@deepseek-ai/cordis';\n\nimport { PACKAGE_NAME, SERVICE_NAME } from '../../constants/telemetry';\nimport type { PiTelemetryExtensionOptions } from '../../types/piTelemetry';\nimport { isEnabled } from '../telemetryEnabled';\n\n/** A reason is a fixed token such as an error class or code, never free text that could carry output. */\nconst FAILURE_REASON_PATTERN = /^[A-Za-z][A-Za-z0-9_]{0,63}$/u;\n\n/** Export only fixed categories from structured tool details, never displayed output. */\nfunction failureAttributes(result: unknown): Record<string, string | number> {\n if (!result || typeof result !== 'object' || !('details' in result)) return {};\n const details = result.details;\n if (!details || typeof details !== 'object') return {};\n const failure = 'failure' in details ? details.failure : undefined;\n const kind = failure && typeof failure === 'object' && 'kind' in failure ? failure.kind : undefined;\n const reason = failure && typeof failure === 'object' && 'reason' in failure ? failure.reason : undefined;\n return {\n ...(typeof kind === 'string' &&\n ['timeout', 'exit_code', 'not_found', 'permission', 'validation', 'aborted', 'unknown'].includes(kind)\n ? { 'failure.kind': kind }\n : {}),\n ...(typeof reason === 'string' && FAILURE_REASON_PATTERN.test(reason) ? { 'failure.reason': reason } : {}),\n ...('exit_code' in details && typeof details.exit_code === 'number' && Number.isFinite(details.exit_code)\n ? { exit_code: details.exit_code }\n : {}),\n };\n}\n\nfunction contextAttributes(execution: PoHeadlessExecutionContext): Record<string, unknown> {\n return {\n 'pi.mode': 'json',\n 'pi.session.id': execution.sessionId,\n ...(execution.model === undefined\n ? {}\n : {\n 'gen_ai.provider.name': execution.model.provider,\n 'gen_ai.request.model': execution.model.id,\n }),\n };\n}\n\n/** Headless hooks carry untrusted records, not Pi's typed assistant messages. */\nfunction usageAttributes(message: Record<string, unknown>): Record<string, unknown> {\n const usage = isRecord(message.usage) ? message.usage : {};\n const attributes: Record<string, unknown> = {};\n for (const [field, attribute] of Object.entries({\n input: 'gen_ai.usage.input_tokens',\n output: 'gen_ai.usage.output_tokens',\n cacheRead: 'gen_ai.usage.cache_read_tokens',\n cacheWrite: 'gen_ai.usage.cache_write_tokens',\n totalTokens: 'gen_ai.usage.total_tokens',\n reasoning: 'gen_ai.usage.reasoning_tokens',\n })) {\n const value = usage[field];\n if (typeof value === 'number' && Number.isFinite(value) && value >= 0) attributes[attribute] = value;\n }\n const cost = isRecord(usage.cost) ? usage.cost.total : undefined;\n if (typeof cost === 'number' && Number.isFinite(cost) && cost >= 0) attributes['gen_ai.usage.cost'] = cost;\n return attributes;\n}\n\nasync function shortHash(value: unknown): Promise<string | undefined> {\n if (value === undefined) return undefined;\n const bytes = new TextEncoder().encode(typeof value === 'string' ? value : JSON.stringify(value));\n const digest = new Uint8Array(await globalThis.crypto.subtle.digest('SHA-256', bytes));\n return Array.from(digest.subarray(0, 6), (byte) => byte.toString(16).padStart(2, '0')).join('');\n}\n\n/** Cache-identity fingerprints of a Responses payload: which of key, instructions, or tools changed. Never content. */\nasync function requestShapeAttributes(payload: Record<string, unknown>): Promise<Record<string, unknown>> {\n const attributes: Record<string, unknown> = {\n 'pi.request.cache_key_version': await shortHash(payload.prompt_cache_key),\n 'pi.request.instructions_version': await shortHash(payload.instructions ?? payload.system),\n 'pi.request.tools_version': await shortHash(payload.tools),\n 'pi.request.wire_model': typeof payload.model === 'string' ? payload.model : undefined,\n 'pi.request.input_count': Array.isArray(payload.input) ? payload.input.length : undefined,\n 'pi.request.tool_count': Array.isArray(payload.tools) ? payload.tools.length : undefined,\n };\n for (const key of Object.keys(attributes)) if (attributes[key] === undefined) delete attributes[key];\n return attributes;\n}\n\nexport function createServerTelemetry(options: PiTelemetryExtensionOptions = {}, localizationContext?: Context) {\n const t = (key: string, fallback: string, vars?: Readonly<Record<string, string | number>>) =>\n (localizationContext\n ? readPoLang(localizationContext)?.t(readPoPersonLocale(localizationContext)?.read(), key, fallback, vars)\n : undefined) ?? translateMessage({}, undefined, key, fallback, vars);\n\n const workflow = options.workflowContext;\n const workflowAttributes =\n workflow === undefined\n ? {}\n : {\n 'agent.parent_session.id': workflow.run.ownerSessionId,\n 'workflow.run.id': workflow.run.runId,\n 'workflow.run.key': workflow.run.runKey,\n 'workflow.job.name': workflow.job,\n 'workflow.step.name': workflow.step,\n 'workflow.step.attempt': workflow.attempt,\n };\n let sessionTrace: PoTraceContext | undefined;\n let turnTrace: PoTraceContext | undefined;\n let active = false;\n let finished = false;\n let queue = Promise.resolve();\n let disposal: Promise<void> | undefined;\n let thinkingLevel: string | undefined;\n const sessionAttributes = (execution: PoHeadlessExecutionContext) => ({\n ...contextAttributes(execution),\n ...workflowAttributes,\n ...(thinkingLevel ? { 'pi.thinking_level': thinkingLevel } : {}),\n });\n const diagnose = () => {\n try {\n options.onDiagnostic?.('Telemetry operation failed');\n } catch (error) {\n // Diagnostics are advisory too: the sink failed, so fall back to the console with the error\n // name only, never its message, and keep telemetry from breaking the session.\n console.warn(`po-log telemetry diagnostic failed (${error instanceof Error ? error.name : typeof error})`);\n }\n };\n const enqueue = (operation: () => Promise<void>) => {\n const pending = queue.then(operation);\n // Advisory telemetry must not poison the queue after a failed exporter.\n queue = pending.catch(diagnose);\n return pending;\n };\n let telemetry: PoTelemetry | undefined;\n const turns = new Map<string, number>();\n const tools = new Map<string, number>();\n let agentStartedAt: number | undefined;\n let turnIndex = 0;\n const childDisposals = new Set<() => Promise<void>>();\n const childHooks: PoChildSessionHooks = {\n bind(scope) {\n let disposed = false;\n let completion: Promise<void> | undefined;\n let laneTrace: PoTraceContext | undefined;\n let parentTrace: PoTraceContext | undefined;\n const attributes = () => ({\n ...workflowAttributes,\n 'agent.parent_session.id': scope.request.parentSessionId,\n 'agent.child.run.id': scope.request.runId,\n ...(scope.sessionId() === undefined ? {} : { 'pi.session.id': scope.sessionId() }),\n });\n // Short spans only: no lane lifetime promise can block exporter shutdown.\n const record = (name: string, extra: Record<string, unknown> = {}) =>\n enqueue(async () => {\n const current = telemetry;\n if (!current) return;\n if (name === 'pi.child.started') parentTrace = turnTrace ?? sessionTrace;\n const metadata = { ...attributes(), ...extra };\n await current.runInSpan(\n name,\n metadata,\n async (trace) => {\n if (name === 'pi.child.started') laneTrace = trace;\n await current.recordEvent(name, metadata);\n },\n laneTrace ?? parentTrace,\n );\n }).catch(() => undefined);\n const dispose = () => {\n if (completion) return completion;\n disposed = true;\n scope.signal.removeEventListener('abort', onAbort);\n childDisposals.delete(dispose);\n completion = active ? record('pi.child.finished') : Promise.resolve();\n return completion;\n };\n const onAbort = () => {\n void dispose();\n };\n if (active) {\n childDisposals.add(dispose);\n void record('pi.child.started');\n scope.signal.addEventListener('abort', onAbort, { once: true });\n if (scope.signal.aborted) onAbort();\n }\n return {\n beforeTool(event) {\n if (active && !disposed)\n void record('pi.child.tool_call', {\n 'tool.name': event.toolName,\n 'tool.call.id': event.toolCallId,\n });\n return undefined;\n },\n afterTool(event) {\n if (active && !disposed)\n void record('pi.child.tool_result', {\n 'tool.name': event.toolName,\n 'tool.call.id': event.toolCallId,\n success: !event.isError,\n 'tool.result.error': event.isError === true,\n ...failureAttributes(event),\n });\n return undefined;\n },\n dispose,\n };\n },\n };\n const activity: PoHeadlessActivity = {\n name: PACKAGE_NAME,\n start(execution) {\n const current = createPoTelemetry({\n serviceName: options.serviceName ?? SERVICE_NAME,\n packageName: PACKAGE_NAME,\n cwd: execution.cwd,\n env: {\n ...(options.env ?? execution.environment),\n AGENT_SESSION_ID: execution.sessionId,\n PO_SESSION_ID: execution.sessionId,\n },\n allowFileFallback: options.allowFileFallback,\n telemetryFactory: options.telemetryFactory,\n warn: options.onDiagnostic ?? (() => undefined),\n onRecord: (record) => options.metrics?.record(record.event, record.attributes),\n onStatus: (status) =>\n options.onSinkStatus?.({\n service: status.serviceName,\n backend: status.backend,\n endpoint: status.endpoint ?? 'none',\n endpointSource: status.endpointSource,\n traces: status.traces,\n redaction: true,\n fileFallback: status.fileFallback,\n }),\n enableLogs: true,\n enableTraces:\n (options.env ?? execution.environment).AGENT_OTEL_TRACES === undefined ||\n isEnabled((options.env ?? execution.environment).AGENT_OTEL_TRACES),\n });\n telemetry = current;\n active = true;\n finished = false;\n let registration: { dispose(): void } | undefined;\n try {\n registration = options.childSessionHookRegistry?.register(childHooks);\n } catch {\n diagnose();\n }\n return () =>\n (disposal ??= (async () => {\n try {\n registration?.dispose();\n } catch {\n diagnose();\n }\n for (const dispose of childDisposals) void dispose();\n active = false;\n // Drain admitted records before shutting down their exporter.\n await queue;\n if (telemetry === current) {\n telemetry = undefined;\n turns.clear();\n tools.clear();\n agentStartedAt = undefined;\n }\n await current.shutdown();\n })());\n },\n };\n\n const command: PoHeadlessCommand = {\n name: 'log-metrics',\n description: 'Show headless telemetry sink status.',\n async execute(_args, execution) {\n await execution.client.notify({\n title: t('log.notice.telemetryTitle', 'Po telemetry'),\n localization: { title: { key: 'log.notice.telemetryTitle', fallback: 'Po telemetry' } },\n body: JSON.stringify(telemetry?.status() ?? { active: false }, null, 2),\n level: 'info',\n });\n },\n };\n\n const hooks: PoHeadlessHook[] = [\n {\n event: 'session_start',\n async handle(_event, execution) {\n thinkingLevel = (await execution.session?.readModelSettings?.())?.thinkingLevel;\n await telemetry?.recordEvent('pi.session.started', {\n ...sessionAttributes(execution),\n 'pi.session.reason': 'startup',\n 'pi.session.previous': false,\n });\n },\n },\n {\n event: 'agent_settled',\n async handle(_event, execution) {\n await telemetry?.recordDebug('pi.agent.settled', sessionAttributes(execution));\n },\n },\n {\n event: 'session_shutdown',\n async handle(_event, execution) {\n if (finished) return;\n finished = true;\n await telemetry?.recordEvent('pi.session.finished', {\n ...sessionAttributes(execution),\n 'pi.session.reason': 'quit',\n });\n execution.client.setStatus('po-log', undefined);\n },\n },\n {\n event: 'turn_start',\n async handle(event, execution) {\n if (!telemetry) return;\n await telemetry.recordDebug('pi.turn.started', {\n ...sessionAttributes(execution),\n 'pi.turn.index': event.turnIndex,\n ...(typeof event.turnId === 'string' ? { 'pi.turn.id': event.turnId } : {}),\n });\n },\n },\n {\n event: 'turn_end',\n async handle(event, execution) {\n const current = telemetry;\n if (!current) return;\n const duration = event.telemetryDurationMs;\n const message = isRecord(event.message) && event.message.role === 'assistant' ? event.message : undefined;\n const usage = message === undefined ? {} : usageAttributes(message);\n const attributes = {\n ...sessionAttributes(execution),\n 'pi.turn.index': event.turnIndex,\n ...(typeof event.turnId === 'string' ? { 'pi.turn.id': event.turnId } : {}),\n ...(message === undefined\n ? {}\n : {\n 'gen_ai.provider.name': message.provider ?? execution.model?.provider,\n 'gen_ai.response.model': message.responseModel ?? message.model,\n 'gen_ai.response.finish_reasons': message.stopReason,\n }),\n };\n const results = Array.isArray(event.toolResults) ? event.toolResults.filter(isRecord) : [];\n await current.recordEvent('pi.turn.finished', {\n ...attributes,\n ...usage,\n 'pi.tool_result.count': results.length,\n ...(typeof duration === 'number' ? { 'pi.turn.duration_ms': duration } : {}),\n });\n if (message?.stopReason === 'error' || message?.stopReason === 'aborted') {\n const failure = {\n ...attributes,\n ...(message.stopReason === 'error' ? { 'error.type': 'ProviderError', 'error.code': 'error' } : {}),\n outcome: message.stopReason === 'aborted' ? 'aborted' : 'error',\n };\n // Usage belongs to the finished record only, not the failure marker.\n if (message.stopReason === 'aborted') await current.recordWarning('pi.turn.failed', undefined, failure);\n else await current.recordError('pi.turn.failed', undefined, failure);\n }\n if (Object.keys(usage).length > 0) {\n for (const result of results) {\n await current.recordDebug('pi.tool_token_sample', {\n ...attributes,\n ...usage,\n 'tool.name': result.toolName,\n token_attribution: 'toolCallTurn',\n });\n }\n }\n },\n },\n {\n event: 'tool_execution_start',\n async handle(event, execution) {\n if (!telemetry) return;\n await telemetry.recordDebug('pi.tool_call', {\n ...sessionAttributes(execution),\n 'tool.name': event.toolName,\n 'tool.call.id': event.toolCallId,\n });\n },\n },\n {\n event: 'tool_execution_end',\n async handle(event, execution) {\n const current = telemetry;\n if (!current) return;\n const duration = event.telemetryDurationMs;\n await current.recordEvent('pi.tool_result', {\n ...sessionAttributes(execution),\n 'tool.name': event.toolName,\n 'tool.call.id': event.toolCallId,\n success: event.isError !== true,\n 'tool.result.error': event.isError === true,\n ...failureAttributes(event.result),\n ...(typeof duration === 'number' ? { 'tool.duration_ms': duration } : {}),\n });\n // External MCP calls have no agent_settled event to flush their results.\n if (typeof event.toolCallId === 'string' && event.toolCallId.startsWith('external-')) await current.flush();\n },\n },\n {\n event: 'agent_start',\n async handle(_event, execution) {\n if (!telemetry) return;\n await telemetry.recordEvent('pi.agent.started', sessionAttributes(execution));\n },\n },\n {\n event: 'model_select',\n async handle(event, execution) {\n await telemetry?.recordEvent('pi.model.selected', {\n ...sessionAttributes(execution),\n 'pi.model.source': 'set',\n 'gen_ai.provider.name': event.model.provider,\n 'gen_ai.request.model': event.model.id,\n });\n },\n },\n {\n event: 'agent_end',\n async handle(event, execution) {\n await telemetry?.recordEvent('pi.agent.finished', {\n ...sessionAttributes(execution),\n 'pi.message.count': Array.isArray(event.messages) ? event.messages.length : 0,\n ...(typeof event.telemetryDurationMs === 'number'\n ? { 'pi.agent.duration_ms': event.telemetryDurationMs }\n : {}),\n });\n await telemetry?.flush();\n },\n },\n ];\n for (const hook of hooks) {\n const handle = hook.handle.bind(hook);\n hook.handle = (event: Readonly<Record<string, unknown>>, execution: PoHeadlessExecutionContext) => {\n if (!active) return;\n const now = Date.now();\n if (hook.event === 'agent_start') turnIndex = 0;\n const index = typeof event.turnIndex === 'number' ? event.turnIndex : turnIndex;\n const turnKey = typeof event.turnId === 'string' ? event.turnId : String(index);\n if (hook.event === 'turn_start') turns.set(turnKey, now);\n if (hook.event === 'tool_execution_start' && typeof event.toolCallId === 'string')\n tools.set(event.toolCallId, now);\n if (hook.event === 'agent_start') agentStartedAt = now;\n let duration: number | undefined;\n if (hook.event === 'turn_end') {\n const start = turns.get(turnKey);\n turns.delete(turnKey);\n turnIndex += 1;\n if (start !== undefined) duration = now - start;\n }\n if (hook.event === 'tool_execution_end' && typeof event.toolCallId === 'string') {\n const start = tools.get(event.toolCallId);\n tools.delete(event.toolCallId);\n if (start !== undefined) duration = now - start;\n }\n if (hook.event === 'agent_end') {\n if (agentStartedAt !== undefined) duration = now - agentStartedAt;\n agentStartedAt = undefined;\n }\n return enqueue(async () => {\n thinkingLevel = (await execution.session?.readModelSettings?.())?.thinkingLevel;\n const current = telemetry;\n if (!current) return;\n const parent =\n hook.event === 'session_start'\n ? workflow?.traceparent\n ? { traceparent: workflow.traceparent }\n : undefined\n : hook.event.startsWith('tool_execution_')\n ? (turnTrace ?? sessionTrace)\n : sessionTrace;\n await current.runInSpan(\n `pi.${hook.event}`,\n sessionAttributes(execution),\n async (trace) => {\n if (hook.event === 'session_start') sessionTrace = trace;\n if (hook.event === 'turn_start') turnTrace = trace;\n await handle({ ...event, turnIndex: index, telemetryDurationMs: duration } as never, execution);\n },\n parent,\n );\n if (hook.event === 'turn_end') turnTrace = undefined;\n });\n };\n }\n // Outside the span wrapper: the provider request must not wait on the telemetry queue.\n hooks.push({\n event: 'before_provider_request',\n handle(event, execution) {\n if (!active || !isRecord(event.payload)) return;\n // Snapshot now: later hooks may replace the payload.\n const payload = { ...event.payload };\n const model = event.model;\n void enqueue(async () => {\n await telemetry?.recordDebug('pi.provider.request', {\n ...sessionAttributes(execution),\n 'gen_ai.provider.name': model.provider,\n 'gen_ai.request.model': model.id,\n ...(model.api === undefined ? {} : { 'pi.request.api_type': model.api }),\n ...(await requestShapeAttributes(payload)),\n });\n }).catch(() => undefined);\n },\n });\n // Telemetry sink status is operator information, not model-actionable.\n return { activities: [activity], commands: [command], hooks };\n}\n","import { readPoChildSessionHookRegistry } from '@agimon-ai/po-core/childSession';\nimport { PO_CODEMODE_SERVICE, readPoCodemode } from '@agimon-ai/po-core/codemode';\nimport { readPoServerScope, type PoServerPluginContext } from '@agimon-ai/po-core/serverPlugin';\nimport { readPoWorkflowContextService } from '@agimon-ai/po-core/workflow';\n\nimport { PACKAGE_NAME } from '../../../../../constants/telemetry';\nimport { LOGSINK_TOOL_NAMES } from '../../../../../schemas/logsink';\nimport { PO_LOG_METRICS_CONTRACT } from '../../../../../schemas/metricsContract';\nimport { createLogsinkOperations } from '../../../../../services/logsink';\nimport { createLogsinkNamespace } from '../../../../../services/logsinkNamespace';\nimport { createMetricsForwarder } from '../../../../../services/metricsForwarder';\nimport { createServerTelemetry } from '../../../../../services/serverTelemetry';\n\nexport const createLogServerRoot = ({ context, agent, host, signal: ownerSignal }: PoServerPluginContext) => {\n // A host that keeps its own metrics binds a store; every other host binds none and keeps the log sink.\n const metrics = createMetricsForwarder({\n resolve: () => readPoServerScope(context)?.resolve(PO_LOG_METRICS_CONTRACT),\n onDiagnostic: (message) => host.context.onNotice(message),\n });\n const runtime = createServerTelemetry(\n {\n workflowContext: readPoWorkflowContextService(context),\n childSessionHookRegistry: readPoChildSessionHookRegistry(context),\n metrics,\n },\n context,\n );\n const sessionId = agent?.context.sessionId;\n const logQueries =\n agent && sessionId\n ? createLogsinkOperations({\n sessionId,\n homeDirectory: host.context.homeDirectory,\n authorize(signal) {\n ownerSignal.throwIfAborted();\n signal?.throwIfAborted();\n agent.assertActive(PACKAGE_NAME);\n if (agent.context.sessionId !== sessionId) throw new Error('Log Sink session changed.');\n return signal ? AbortSignal.any([ownerSignal, signal]) : ownerSignal;\n },\n })\n : undefined;\n return {\n value: { ...runtime, logQueries },\n activities: runtime.activities,\n services: logQueries\n ? [\n (cordis: PoServerPluginContext['context']) => {\n cordis.inject([PO_CODEMODE_SERVICE], (scoped) => {\n const codemode = readPoCodemode(scoped);\n if (!codemode) return undefined;\n const registration = codemode.register(PACKAGE_NAME, createLogsinkNamespace(logQueries));\n const restriction = agent?.registerToolRestriction({ excludedTools: LOGSINK_TOOL_NAMES });\n return () => {\n restriction?.dispose();\n registration.dispose();\n };\n });\n },\n ]\n : [],\n };\n};\nexport type LogServerScope = Awaited<ReturnType<typeof createLogServerRoot>>['value'];\n","import { defineRoot } from '@agimon-ai/po-core/extensionFile';\n\nimport { createLogServerRoot } from './_lib/serverRoot';\n\nexport default defineRoot(createLogServerRoot);\n","import type { AgentIssueSample, IssuesReport } from '../../types/issuesSource';\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\nfunction counts(value: unknown): Record<string, number> {\n if (!isRecord(value)) return {};\n const entries = Object.entries(value).flatMap(([key, count]) =>\n typeof count === 'number' ? [[key, count] as [string, number]] : [],\n );\n return Object.fromEntries(entries);\n}\n\nfunction text(value: unknown): string {\n return typeof value === 'string' ? value : '';\n}\n\nfunction nullableText(value: unknown): string | null {\n return typeof value === 'string' && value !== '' ? value : null;\n}\n\nfunction toSample(value: unknown): AgentIssueSample[] {\n if (!isRecord(value)) return [];\n return [\n {\n fingerprint: text(value.fingerprint),\n occurrenceCount: typeof value.occurrenceCount === 'number' ? value.occurrenceCount : 1,\n category: text(value.category),\n timestamp: text(value.timestamp),\n level: text(value.level),\n message: text(value.message),\n // The sink leaves detail null when the message already is the detail.\n detail: nullableText(value.detail) ?? text(value.message),\n tool: nullableText(value.tool),\n errorType: nullableText(value.errorType),\n agentName: nullableText(value.agentName),\n model: nullableText(value.model),\n statusCode: nullableText(value.statusCode),\n },\n ];\n}\n\n/**\n * The CLI's report is a foreign process's JSON, so every field is narrowed\n * here rather than cast. A sink one version ahead may add fields, and a sink\n * one version behind may omit them; neither should throw.\n */\nexport function toReport(raw: unknown): IssuesReport {\n if (!isRecord(raw)) throw new Error('The log sink returned output this version cannot read.');\n const samples = Array.isArray(raw.issues) ? raw.issues.flatMap(toSample) : [];\n return {\n totalIssues: typeof raw.totalIssues === 'number' ? raw.totalIssues : 0,\n uniqueIncidents: typeof raw.uniqueIncidents === 'number' ? raw.uniqueIncidents : 0,\n byCategory: counts(raw.byCategory),\n byTool: counts(raw.byTool),\n byErrorType: counts(raw.byErrorType),\n samples,\n };\n}\n","import { execFile } from 'node:child_process';\nimport { createRequire } from 'node:module';\nimport path from 'node:path';\n\nimport { resolveLogSinkInstance } from '@agimon-ai/po-logsink';\n\nimport type { IssuesQueryParams, IssuesSource, IssuesSourceOptions } from '../../types/issuesSource';\nimport { toReport } from './report';\n\n/**\n * Agent-issue analysis over the sink's CLI.\n *\n * One transport, not two, because the daemon serves only /api/metrics and\n * /api/logs: there is no issues route to prefer. Every call is a subprocess,\n * which is why the page asks for this only when a reader opens the section\n * rather than alongside each report.\n */\n\nconst PACKAGE_NAME = '@agimon-ai/po-logsink';\nconst CLI_TIMEOUT_MS = 60000;\n/** The analysis scans the whole window, so its output is larger than a metrics report. */\nconst MAX_CLI_BUFFER = 32 * 1024 * 1024;\n\nfunction cliEntryPoint(): string {\n const require = createRequire(import.meta.url);\n const packageJson = require.resolve(`${PACKAGE_NAME}/package.json`);\n return path.join(path.dirname(packageJson), 'dist', 'cli.mjs');\n}\n\nfunction runCli(params: IssuesQueryParams, dbPath: string | undefined): Promise<unknown> {\n return new Promise((resolve, reject) => {\n execFile(\n process.execPath,\n [\n cliEntryPoint(),\n 'logs',\n 'agent-issues',\n '--limit',\n String(params.limit),\n ...(params.sessionId === undefined ? [] : ['--session-id', params.sessionId]),\n ...(params.startTime === undefined ? [] : ['--start-time', params.startTime]),\n ...(params.endTime === undefined ? [] : ['--end-time', params.endTime]),\n ...(dbPath === undefined ? [] : ['--db-path', dbPath]),\n ],\n { timeout: CLI_TIMEOUT_MS, maxBuffer: MAX_CLI_BUFFER },\n (error, stdout, stderr) => {\n if (error) {\n reject(new Error(stderr.trim() || error.message));\n return;\n }\n try {\n resolve(JSON.parse(stdout) as unknown);\n } catch {\n reject(new Error('The log sink returned output this version cannot read.'));\n }\n },\n );\n });\n}\n\nexport function createIssuesSource(options: IssuesSourceOptions = {}): IssuesSource {\n const instance = resolveLogSinkInstance({\n env: options.env,\n cwd: options.cwd,\n packageName: options.packageName,\n serviceName: options.serviceName,\n });\n const cliRunner = options.cliRunner ?? ((params: IssuesQueryParams) => runCli(params, instance?.dbPath));\n\n return {\n async query(params) {\n return toReport(await cliRunner(params));\n },\n };\n}\n","/**\n * The metrics API, shared by this package's hub-scoped route and its cockpit\n * plugin. The two halves run in different processes, so the wire vocabulary is\n * declared here: the `(frontend)` half may reach `src/types` and nothing else\n * on the node side.\n *\n * The shapes are narrower than po-logsink's own report, which carries filter\n * echoes, span counts and token distributions the page never draws.\n * Re-exporting the sink's types would also tie the browser bundle to a node\n * package. What crosses the wire is what a chart reads.\n *\n * Two things the sink does not have, so this contract does not pretend to:\n * money, and per-tool failures. This metrics report records tokens, and its tool rows\n * carry an invocation count with no error field.\n */\n\n/**\n * The segment this package's API is mounted under.\n *\n * Read by the hub's `PoApi`, which still declares its own base path. The\n * browser does not read it: the generated client is handed the same segment by\n * the build, off the `api/log/` folder that creates the mount, so no URL is\n * spelled twice.\n */\nexport const LOG_API_BASE_PATH = 'log';\n\n/**\n * The dimensions the page offers.\n *\n * po-logsink also groups by 'workflow-run', 'workflow-name', 'job' and\n * 'step'. Those are omitted on purpose: no Po package emits the matching\n * attributes today, so offering them would draw an empty chart and read as a\n * bug rather than as a gap.\n */\nexport const METRICS_DIMENSIONS = ['session', 'agent', 'model', 'provider'] as const;\nexport type MetricsDimension = (typeof METRICS_DIMENSIONS)[number];\n\nexport const METRICS_PERIODS = ['day', 'week', 'month', 'all'] as const;\nexport type MetricsPeriod = (typeof METRICS_PERIODS)[number];\n\nexport const METRICS_QUERY_PARAMS = {\n dimension: 'dimension',\n period: 'period',\n /** Narrows the whole report to one value of the current dimension. */\n focus: 'focus',\n} as const;\n\n/** How many groups and tools one response carries; the page ranks, it does not page. */\nexport const METRICS_GROUP_LIMIT = 20;\n\n/** One point on the token timeline. */\nexport interface MetricsBucket {\n /**\n * The sink's own local-time label ('YYYY-MM-DD', or 'YYYY-MM-DD HH:00' for an\n * hour bucket). Carried rather than derived: bucket boundaries are aligned to\n * local time, so slicing the ISO instant renders the wrong day east of\n * Greenwich.\n */\n label: string;\n totalTokens: number;\n inputTokens: number;\n outputTokens: number;\n}\n\n/** One row of the selected dimension. */\nexport interface MetricsGroup {\n /**\n * The group's identity as the sink reports it. For the session dimension\n * this is an opaque hash, never a session the cockpit can open, because\n * po-core/telemetry hashes identifier-shaped attributes before export.\n */\n key: string;\n totalTokens: number;\n inputTokens: number;\n outputTokens: number;\n /** Problems the sink detected for this group; 0 when it saw none. */\n issueCount: number;\n failed: boolean;\n}\n\n/**\n * One tool's activity.\n *\n * `calls` counts token-attributed samples, not every execution. External MCP\n * calls without model usage remain queryable as logs but have no sample here.\n * `p90TotalTokens` attributes the whole turn's tokens to each tool in that turn,\n * so it ranks tools rather than measuring their own consumption.\n *\n * There is no failure count here because the sink's tool rows do not carry\n * one. Per-tool failures live in its separate agent-issues report, which the\n * running daemon does not expose over HTTP.\n */\nexport interface MetricsTool {\n name: string;\n calls: number;\n p90TotalTokens: number;\n}\n\n/** Which transport answered, so the page can say where its numbers came from. */\nexport type MetricsTransport = 'http' | 'worker';\n\nexport interface MetricsTotals {\n /** Optional so an older hub remains distinguishable from a measured zero. */\n usageEventCount?: number;\n totalRecords?: number;\n /**\n * The providers' own reported total. It is not inputTokens + outputTokens:\n * providers report these counters independently. Their relationship cannot\n * be inferred from a difference, so the page must not stack them as parts\n * of the total or label the difference as cache traffic.\n */\n totalTokens: number;\n inputTokens: number;\n outputTokens: number;\n /** Independently reported cache reads, not an inferred remainder. */\n cachedTokens: number;\n reasoningTokens: number;\n groupCount: number;\n /** Groups the sink flagged as having failed, out of groupCount. */\n failedGroups: number;\n issueCount: number;\n}\n\nexport interface MetricsReport {\n /** Echoed query window, so issue details can use the same recorded period. */\n startTime?: string;\n endTime?: string;\n generatedAt: string;\n dimension: MetricsDimension;\n period: MetricsPeriod;\n /**\n * The width of one timeline bucket, chosen by the sink from the period. A\n * long period over a short history collapses to a single bucket, so the page\n * says which unit it is drawing rather than implying a series it does not\n * have.\n */\n bucketUnit: string;\n /**\n * The dimension value this report is narrowed to, echoed back from the sink\n * rather than from the request. A daemon older than the filter ignores it\n * and returns everything, so trusting the request would label unfiltered\n * numbers as filtered; absence here means the drill-down did not happen.\n */\n focus?: string;\n /** Undefined when the source could not say which transport answered. */\n transport?: MetricsTransport;\n totals: MetricsTotals;\n timeline: MetricsBucket[];\n groups: MetricsGroup[];\n tools: MetricsTool[];\n}\n\n/**\n * Why the page has nothing to draw.\n *\n * The sink is a separate daemon that may be missing or simply empty, and those\n * are different things to tell a reader. Neither is an error: the metrics\n * source already treats a rejecting daemon as unavailable rather than fatal.\n *\n * 'no-api' is the third case and belongs to the cockpit rather than the sink.\n * A hub serving a bundle without package APIs mounted answers this route with\n * the SPA shell, and a 200 of HTML must read as a feature that is not\n * installed, not as a corrupt response.\n */\nexport type MetricsUnavailableReason = 'no-sink' | 'no-data' | 'no-api' | 'query-error';\n\nexport interface MetricsUnavailable {\n unavailable: MetricsUnavailableReason;\n detail: string;\n}\n\nexport type MetricsResponse = MetricsReport | MetricsUnavailable;\n\nexport function isMetricsUnavailable(response: MetricsResponse): response is MetricsUnavailable {\n return 'unavailable' in response;\n}\n\nexport function isMetricsDimension(value: string): value is MetricsDimension {\n return (METRICS_DIMENSIONS as readonly string[]).includes(value);\n}\n\nexport function isMetricsPeriod(value: string): value is MetricsPeriod {\n return (METRICS_PERIODS as readonly string[]).includes(value);\n}\n\n/** One tool's failure count, paired with its call count from the metrics report. */\nexport interface IssueToolRow {\n name: string;\n failures: number;\n}\n\n/**\n * One recurring problem, as the sink fingerprints it.\n *\n * `occurrenceCount` is how many times it happened, which is the number a\n * reader acts on. `detail` is the actionable line; `message` is often only a\n * record name such as 'pi.tool_result'.\n */\nexport interface IssueSample {\n fingerprint: string;\n occurrenceCount: number;\n category: string;\n timestamp: string;\n level: string;\n message: string;\n detail: string;\n tool: string | null;\n errorType: string | null;\n agentName: string | null;\n model: string | null;\n statusCode: string | null;\n}\n\n/**\n * The detail behind the issue count.\n *\n * Fetched separately from the report because the running sink exposes no\n * issues route over HTTP, so this costs a subprocess. The page asks for it\n * when a reader opens the section, not with every refresh.\n */\nexport interface IssuesView {\n totalIssues: number;\n uniqueIncidents: number;\n byCategory: Record<string, number>;\n byTool: Record<string, number>;\n byErrorType: Record<string, number>;\n samples: IssueSample[];\n}\n\nexport type IssuesResponse = IssuesView | MetricsUnavailable;\n\nexport function isIssuesUnavailable(response: IssuesResponse): response is MetricsUnavailable {\n return 'unavailable' in response;\n}\n\n/** How many incidents the issues section ranks. */\nexport const ISSUE_SAMPLE_LIMIT = 50;\n\n/** How many tool rows the report ranks, so a failing tool has a denominator. */\nexport const METRICS_TOOL_LIMIT = 15;\n\n/** One resource a host meters for its own account, such as remote browser time. */\nexport interface HostUsageRow {\n readonly key: string;\n readonly label: string;\n readonly used: number;\n /** Absent when the host sets no limit. */\n readonly limit?: number;\n readonly unit: 'seconds' | 'bytes';\n /** What the number covers, such as the day it counts. */\n readonly detail: string;\n}\n\nexport interface HostUsageResponse {\n readonly rows: readonly HostUsageRow[];\n}\n\n/** What a host binds to report the resources it meters. */\nexport interface HostUsageService {\n read(): Promise<readonly HostUsageRow[]>;\n}\n","import { apiResponse, defineApiRoutes } from '@agimon-ai/po-core/web';\n\nimport { METRICS_QUERY_PARAMS, type HostUsageResponse, type IssuesResponse, type MetricsResponse } from './webMetrics';\n\n/**\n * This package's routes, as data.\n *\n * No scope and no base path. The build reads both off\n * `src/extensions/(backend)/api/log/`, so the mount is stated once, by the\n * folder that creates it. They used to be written here, in the contract, and\n * again inside every URL the page built, and the copies were free to disagree.\n *\n * This is the one file the routes, the Hono app and the browser all read, so a\n * path cannot move on one side alone.\n */\nexport const routes = defineApiRoutes({\n metrics: {\n method: 'GET',\n path: '/metrics',\n query: [METRICS_QUERY_PARAMS.dimension, METRICS_QUERY_PARAMS.period, METRICS_QUERY_PARAMS.focus],\n response: apiResponse<MetricsResponse>(),\n },\n /**\n * Separate from the report because the hub answers it from a subprocess: the\n * running daemon exposes no issues route, so folding it in would make every\n * refresh wait on the slowest transport.\n */\n issues: {\n method: 'GET',\n path: '/issues',\n query: [METRICS_QUERY_PARAMS.focus],\n response: apiResponse<IssuesResponse>(),\n },\n /** The resources the host meters for its own account. Empty on a host that meters none. */\n usage: {\n method: 'GET',\n path: '/usage',\n response: apiResponse<HostUsageResponse>(),\n },\n /**\n * OTLP/JSON logs from clients that run no collector of their own, such as the\n * native app. Forwarded unchanged to the sink, which validates and redacts.\n */\n ingestLogs: {\n method: 'POST',\n path: '/v1/logs',\n response: apiResponse<{ ok: true }>(),\n },\n});\n","import type { PoApi, PoApiContext, PoApiHandler } from '@agimon-ai/po-core/packageApi';\nimport type { LogMetricGroupRow, LogMetricsReport, ToolMetricRow } from '@agimon-ai/po-logsink';\nimport { Hono } from 'hono';\n\nimport { PACKAGE_NAME, SERVICE_NAME } from '../../constants/telemetry';\nimport { createIssuesSource } from '../../services/issuesSource';\nimport { createMetricsSource, resolveMetricsEndpoint } from '../../services/metricsSource';\nimport type { LogMetricsService } from '../../services/metricsStore/type';\nimport { routes } from '../../types/apiRoutes';\nimport type { IssuesSource } from '../../types/issuesSource';\nimport type { MetricsFilter, MetricsSource } from '../../types/metricsSource';\nimport {\n isMetricsDimension,\n isMetricsPeriod,\n LOG_API_BASE_PATH,\n ISSUE_SAMPLE_LIMIT,\n METRICS_GROUP_LIMIT,\n METRICS_QUERY_PARAMS,\n METRICS_TOOL_LIMIT,\n type HostUsageResponse,\n type HostUsageService,\n type MetricsBucket,\n type MetricsDimension,\n type MetricsGroup,\n type MetricsPeriod,\n type MetricsReport,\n type MetricsTool,\n type MetricsUnavailable,\n type IssuesView,\n} from '../../types/webMetrics';\n\n/**\n * The cockpit's half of this package's metrics access.\n *\n * Hub-scoped rather than session-scoped: the questions this answers, where the\n * tokens went and which agents failed, are about the machine over time, and a\n * session server can only see itself. The sink is already machine-wide, so the\n * hub is the only place the two agree.\n *\n * The query path is not reimplemented here. `createMetricsSource` already owns\n * the sink's two transports and its fallback order, and the TUI overlay reads\n * through the same source, so both surfaces answer from one implementation.\n */\n\nconst DEFAULT_DIMENSION: MetricsDimension = 'model';\nconst DEFAULT_PERIOD: MetricsPeriod = 'week';\n/** A client batch is a few dozen truncated records; the sink's own 5 MiB cap is for local exporters. */\nconst MAX_INGEST_BYTES = 1024 * 1024;\nconst FORWARD_TIMEOUT_MS = 5000;\n\n/** The sink groups sessions under a different name than the page's dimension. */\nconst SINK_GROUP_BY = {\n session: 'session',\n agent: 'agent',\n model: 'model',\n provider: 'provider',\n} as const;\n\nfunction toBucket(bucket: LogMetricsReport['timeline'][number]): MetricsBucket {\n return {\n label: bucket.label,\n totalTokens: bucket.totalTokens,\n inputTokens: bucket.inputTokens,\n outputTokens: bucket.outputTokens,\n };\n}\n\nfunction toGroup(row: LogMetricGroupRow): MetricsGroup {\n return {\n key: row.key,\n totalTokens: row.totalTokens,\n inputTokens: row.inputTokens,\n outputTokens: row.outputTokens,\n issueCount: row.issueCount,\n failed: row.failed,\n };\n}\n\n/**\n * The turn's p90 rather than a sum: the sink attributes a whole turn's tokens\n * to every tool that ran in it, so adding them across calls would multiply the\n * same tokens by however many tools shared the turn.\n */\nfunction toTool(row: ToolMetricRow): MetricsTool {\n return {\n name: row.toolName,\n calls: row.invocationCount,\n p90TotalTokens: row.toolCallTurn.p90TotalTokens,\n };\n}\n\n/** Which filter field carries a focus value, per dimension. */\nconst FOCUS_FIELD: Record<MetricsDimension, keyof MetricsFilter> = {\n session: 'sessionId',\n agent: 'agentName',\n model: 'model',\n provider: 'provider',\n};\n\n/**\n * The focus the sink actually applied, read from its own echo.\n *\n * A daemon that predates a filter ignores it and answers with everything. If\n * the page trusted the request instead of this echo, it would label the whole\n * machine's numbers as one model's.\n */\nfunction appliedFocus(report: LogMetricsReport, dimension: MetricsDimension): string | undefined {\n // The daemon is a separate process on its own release cadence, so its\n // response is parsed defensively rather than trusted to carry every field.\n const filters = report.filters as LogMetricsReport['filters'] | undefined;\n if (filters === undefined) return undefined;\n if (dimension === 'session') return filters.sessionId;\n if (dimension === 'agent') return filters.agentName;\n const applied = dimension === 'model' ? filters.model : filters.provider;\n if (applied === undefined) return undefined;\n return Array.isArray(applied) ? applied[0] : applied;\n}\n\n/**\n * The sink's own type says Date, but both transports parse JSON, so what\n * arrives is an ISO string. Trusting the declared type here throws on every\n * real response, which no test using a hand-built Date would ever catch.\n */\nfunction generatedAtIso(value: Date | string): string {\n if (value instanceof Date) return value.toISOString();\n const parsed = new Date(value);\n return Number.isNaN(parsed.getTime()) ? new Date(0).toISOString() : parsed.toISOString();\n}\n\nfunction toReport(report: LogMetricsReport, source: MetricsSource, dimension: MetricsDimension): MetricsReport {\n const focus = appliedFocus(report, dimension);\n return {\n generatedAt: generatedAtIso(report.generatedAt),\n ...(report.filters?.startTime === undefined ? {} : { startTime: generatedAtIso(report.filters.startTime) }),\n endTime: generatedAtIso(report.filters?.endTime ?? report.generatedAt),\n dimension: report.groupBy as MetricsDimension,\n period: report.period as MetricsPeriod,\n bucketUnit: String(report.bucket),\n transport: source.lastTransport(),\n ...(focus === undefined ? {} : { focus }),\n totals: {\n usageEventCount: report.totals.usageEventCount,\n totalRecords: report.totals.totalRecords,\n totalTokens: report.totals.totalTokens,\n inputTokens: report.totals.inputTokens,\n outputTokens: report.totals.outputTokens,\n cachedTokens: report.totals.cachedInputTokens,\n reasoningTokens: report.totals.reasoningOutputTokens,\n groupCount: report.totals.groupCount,\n failedGroups: report.totals.failedGroups,\n issueCount: report.totals.issueCount,\n },\n timeline: report.timeline.map(toBucket),\n groups: report.groups.map(toGroup),\n tools: report.tools.rows.map(toTool),\n };\n}\n\n/**\n * A report with nothing in it reads as \"no data\", not as an empty chart. The\n * reader may have used the HTTP sink or a worker against an empty history, so\n * the empty-state detail must not claim the sink is running.\n */\nfunction isEmpty(report: MetricsReport): boolean {\n return report.totals.totalTokens === 0 && report.groups.length === 0 && report.tools.length === 0;\n}\n\n/**\n * A bound store answers before any sink is looked for. It claims no transport: it is neither the sink's HTTP\n * API nor its worker. The store is looked up on every query, because a host binds it after this API starts.\n */\nfunction preferBound(bound: () => LogMetricsService | undefined, sink: MetricsSource): MetricsSource {\n let answeredByStore = false;\n return {\n async query(params) {\n const store = bound();\n answeredByStore = store !== undefined;\n return store === undefined ? sink.query(params) : store.query(params);\n },\n lastTransport: () => (answeredByStore ? undefined : sink.lastTransport()),\n instance: () => sink.instance?.(),\n close: async () => {\n await sink.close?.();\n },\n };\n}\n\nexport interface HubApiOptions {\n /** Injected by tests; production resolves the machine's sink. */\n source?: MetricsSource;\n /** The metrics a host keeps itself, such as a hosted organization's. When one is bound it answers instead of a sink. */\n metrics?: () => LogMetricsService | undefined;\n /** The resources a host meters for its account. A host that binds none reports none. */\n usage?: () => HostUsageService | undefined;\n issues?: IssuesSource;\n env?: NodeJS.ProcessEnv;\n /** Injected by tests; production resolves the running sink's HTTP endpoint. */\n sinkEndpoint?: () => Promise<string | undefined>;\n fetchImpl?: typeof fetch;\n}\n\nexport function createLogHubApi(options: HubApiOptions = {}): Hono {\n const app = new Hono();\n // One source for the life of the hub: it caches the resolved sink endpoint,\n // and rebuilding it per request would re-probe the daemon every time.\n const identity = {\n packageName: PACKAGE_NAME,\n serviceName: SERVICE_NAME,\n ...(options.env === undefined ? {} : { env: options.env }),\n };\n const sink = options.source ?? createMetricsSource(identity);\n const source = options.metrics === undefined ? sink : preferBound(options.metrics, sink);\n const issues = options.issues ?? createIssuesSource(identity);\n const fetchImpl = options.fetchImpl ?? globalThis.fetch;\n // resolveLogSinkPort caches with a TTL, so asking per batch does not re-probe the daemon each time.\n const sinkEndpoint = options.sinkEndpoint ?? (() => resolveMetricsEndpoint(identity));\n app.get(routes.metrics.path, async (context) => {\n const requestedDimension = context.req.query(METRICS_QUERY_PARAMS.dimension) ?? DEFAULT_DIMENSION;\n const requestedPeriod = context.req.query(METRICS_QUERY_PARAMS.period) ?? DEFAULT_PERIOD;\n if (!isMetricsDimension(requestedDimension)) {\n return context.json({ error: `Unknown dimension '${requestedDimension}'.` }, 400);\n }\n if (!isMetricsPeriod(requestedPeriod)) {\n return context.json({ error: `Unknown period '${requestedPeriod}'.` }, 400);\n }\n\n const focus = context.req.query(METRICS_QUERY_PARAMS.focus);\n const filter: MetricsFilter | undefined =\n focus === undefined || focus === '' ? undefined : { [FOCUS_FIELD[requestedDimension]]: focus };\n\n let report: LogMetricsReport;\n try {\n report = await source.query({\n groupBy: SINK_GROUP_BY[requestedDimension],\n period: requestedPeriod,\n limit: METRICS_GROUP_LIMIT,\n toolLimit: METRICS_TOOL_LIMIT,\n ...(filter === undefined ? {} : { filter }),\n });\n } catch (error) {\n // A missing daemon can still be read through its database. Failure of both\n // transports is a query fault, including a broken worker dependency graph.\n const unavailable: MetricsUnavailable = {\n unavailable: 'query-error',\n detail: error instanceof Error ? error.message : 'The metrics query failed.',\n };\n return context.json(unavailable);\n }\n\n const body = toReport(report, source, requestedDimension);\n if (isEmpty(body)) {\n const unavailable: MetricsUnavailable = {\n unavailable: 'no-data',\n detail: 'No recorded usage was found for this period.',\n };\n return context.json(unavailable);\n }\n return context.json(body);\n });\n\n /**\n * The detail behind the count the report carries. Separate from /metrics\n * because it costs a subprocess: the running daemon has no issues route, so\n * folding it into every report would make the whole page as slow as its\n * slowest transport.\n */\n app.get(routes.issues.path, async (context) => {\n const focus = context.req.query(METRICS_QUERY_PARAMS.focus);\n const startTime = context.req.query('startTime');\n const endTime = context.req.query('endTime');\n // Only ISO instants are accepted at this boundary, not locale-dependent dates.\n const validTime = (value: string | undefined): boolean =>\n value === undefined ||\n (/^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(?:\\.\\d+)?(?:Z|[+-]\\d{2}:\\d{2})$/.test(value) &&\n Number.isFinite(Date.parse(value)));\n if (\n !validTime(startTime) ||\n !validTime(endTime) ||\n (startTime !== undefined && endTime !== undefined && Date.parse(startTime) > Date.parse(endTime))\n ) {\n return context.json({ error: 'Issue time bounds must be valid ISO instants in chronological order.' }, 400);\n }\n try {\n const report = await issues.query({\n limit: ISSUE_SAMPLE_LIMIT,\n ...(startTime === undefined ? {} : { startTime }),\n ...(endTime === undefined ? {} : { endTime }),\n ...(focus === undefined || focus === '' ? {} : { sessionId: focus }),\n });\n return context.json(report satisfies IssuesView);\n } catch (error) {\n const unavailable: MetricsUnavailable = {\n unavailable: 'query-error',\n detail: error instanceof Error ? error.message : 'The issues query failed.',\n };\n return context.json(unavailable);\n }\n });\n\n app.get(routes.usage.path, async (context) => {\n try {\n const rows = (await options.usage?.()?.read()) ?? [];\n return context.json({ rows } satisfies HostUsageResponse);\n } catch (error) {\n return context.json({ error: error instanceof Error ? error.message : 'The usage read failed.' }, 502);\n }\n });\n\n /**\n * Logs from clients with no collector of their own. The sink validates,\n * redacts and rate-limits OTLP itself, so this only bounds the size and\n * forwards; it never parses or rewrites records.\n */\n app.post(routes.ingestLogs.path, async (context) => {\n const declared = Number(context.req.header('content-length') ?? 0);\n if (declared > MAX_INGEST_BYTES) return context.json({ error: 'Log batch is too large.' }, 413);\n const body = await context.req.text();\n if (new TextEncoder().encode(body).byteLength > MAX_INGEST_BYTES) {\n return context.json({ error: 'Log batch is too large.' }, 413);\n }\n let response: Response;\n try {\n const endpoint = await sinkEndpoint();\n if (endpoint === undefined) return context.json({ error: 'The log sink is not running.' }, 503);\n response = await fetchImpl(`${endpoint}/v1/logs`, {\n method: 'POST',\n headers: { 'content-type': 'application/json' },\n body,\n signal: AbortSignal.timeout(FORWARD_TIMEOUT_MS),\n });\n } catch (error) {\n return context.json({ error: error instanceof Error ? error.message : 'The log sink did not answer.' }, 503);\n }\n if (response.ok) return context.json({ ok: true as const });\n const error = `The log sink refused the batch (${response.status}).`;\n if (response.status === 413) return context.json({ error }, 413);\n return context.json({ error }, response.status >= 500 ? 502 : 400);\n });\n\n return app;\n}\n\n/**\n * The package's API for a host. `metrics` resolves the store the host bound, if any, so a host that keeps its\n * own metrics answers from them and every other host keeps answering from the log sink.\n */\nexport function createLogApi(\n metrics?: () => LogMetricsService | undefined,\n usage?: () => HostUsageService | undefined,\n): PoApi {\n return {\n basePath: LOG_API_BASE_PATH,\n start(context: PoApiContext): PoApiHandler {\n const env = { ...context.environment };\n const source = createMetricsSource({ env, packageName: PACKAGE_NAME, serviceName: SERVICE_NAME });\n const app = createLogHubApi({\n source,\n env,\n ...(metrics === undefined ? {} : { metrics }),\n ...(usage === undefined ? {} : { usage }),\n });\n return {\n fetch: (request) => app.fetch(request),\n close: () => source.close?.(),\n };\n },\n };\n}\n\n/** The named export a host imports from this package's built hub entry. */\nexport const api: PoApi = createLogApi();\n","import { defineRoute } from '@agimon-ai/po-core/extensionFile';\nimport { readPoServerScope, type PoServerPluginContext } from '@agimon-ai/po-core/serverPlugin';\n\nimport { PO_LOG_HOST_USAGE_CONTRACT, PO_LOG_METRICS_CONTRACT } from '../../../../schemas/metricsContract';\nimport { createLogApi } from '../../../../services/hubApi';\n\n/** The store is resolved per request: a host that keeps its own metrics binds it after this API mounts. */\nexport default defineRoute(({ context }: PoServerPluginContext) =>\n createLogApi(\n () => readPoServerScope(context)?.resolve(PO_LOG_METRICS_CONTRACT),\n () => readPoServerScope(context)?.resolve(PO_LOG_HOST_USAGE_CONTRACT),\n ),\n);\n","import { defineServerCommand, type WithRoot } from '@agimon-ai/po-core/extensionFile';\nimport type { PoServerPluginContext } from '@agimon-ai/po-core/serverPlugin';\n\nimport type { LogServerScope } from '../_lib/serverRoot';\nexport default defineServerCommand(\n (context: WithRoot<PoServerPluginContext, LogServerScope>) => context.root.commands[0]!,\n);\n","import { defineHook, type WithRoot } from '@agimon-ai/po-core/extensionFile';\nimport type { PoServerPluginContext } from '@agimon-ai/po-core/serverPlugin';\n\nimport type { LogServerScope } from '../_lib/serverRoot';\nexport default defineHook((context: WithRoot<PoServerPluginContext, LogServerScope>) => ({\n ...context.root.hooks[9]!,\n name: 'trace-agent-completion',\n description:\n 'While telemetry is active, record agent duration and message count in a queued trace span, then flush telemetry.',\n}));\n","import { defineHook, type WithRoot } from '@agimon-ai/po-core/extensionFile';\nimport type { PoServerPluginContext } from '@agimon-ai/po-core/serverPlugin';\n\nimport type { LogServerScope } from '../_lib/serverRoot';\nexport default defineHook((context: WithRoot<PoServerPluginContext, LogServerScope>) => ({\n ...context.root.hooks[1]!,\n name: 'trace-agent-settlement',\n description: 'While telemetry is active, record agent settlement debug telemetry in a queued trace span.',\n}));\n","import { defineHook, type WithRoot } from '@agimon-ai/po-core/extensionFile';\nimport type { PoServerPluginContext } from '@agimon-ai/po-core/serverPlugin';\n\nimport type { LogServerScope } from '../_lib/serverRoot';\nexport default defineHook((context: WithRoot<PoServerPluginContext, LogServerScope>) => ({\n ...context.root.hooks[7]!,\n name: 'trace-agent-start',\n description: 'While telemetry is active, reset turn timing and record agent startup in a queued trace span.',\n}));\n","import { defineHook, type WithRoot } from '@agimon-ai/po-core/extensionFile';\nimport type { PoServerPluginContext } from '@agimon-ai/po-core/serverPlugin';\n\nimport type { LogServerScope } from '../_lib/serverRoot';\nexport default defineHook((context: WithRoot<PoServerPluginContext, LogServerScope>) => ({\n ...context.root.hooks[10]!,\n name: 'trace-provider-request',\n description:\n 'When active with an object payload, snapshot the provider request and queue shape telemetry without delaying the request.',\n}));\n","import { defineHook, type WithRoot } from '@agimon-ai/po-core/extensionFile';\nimport type { PoServerPluginContext } from '@agimon-ai/po-core/serverPlugin';\n\nimport type { LogServerScope } from '../_lib/serverRoot';\nexport default defineHook((context: WithRoot<PoServerPluginContext, LogServerScope>) => ({\n ...context.root.hooks[8]!,\n name: 'trace-model-selection',\n description: 'While telemetry is active, record the selected provider and model in a queued trace span.',\n}));\n","import { defineHook, type WithRoot } from '@agimon-ai/po-core/extensionFile';\nimport type { PoServerPluginContext } from '@agimon-ai/po-core/serverPlugin';\n\nimport type { LogServerScope } from '../_lib/serverRoot';\nexport default defineHook((context: WithRoot<PoServerPluginContext, LogServerScope>) => ({\n ...context.root.hooks[2]!,\n name: 'trace-session-shutdown',\n description: 'While telemetry is active, record session completion once and clear the telemetry status.',\n}));\n","import { defineHook, type WithRoot } from '@agimon-ai/po-core/extensionFile';\nimport type { PoServerPluginContext } from '@agimon-ai/po-core/serverPlugin';\n\nimport type { LogServerScope } from '../_lib/serverRoot';\nexport default defineHook((context: WithRoot<PoServerPluginContext, LogServerScope>) => ({\n ...context.root.hooks[0]!,\n name: 'trace-session-start',\n description:\n 'While telemetry is active, refresh thinking settings and record session startup in a queued trace span.',\n}));\n","import { defineHook, type WithRoot } from '@agimon-ai/po-core/extensionFile';\nimport type { PoServerPluginContext } from '@agimon-ai/po-core/serverPlugin';\n\nimport type { LogServerScope } from '../_lib/serverRoot';\nexport default defineHook((context: WithRoot<PoServerPluginContext, LogServerScope>) => ({\n ...context.root.hooks[6]!,\n name: 'trace-tool-result',\n description:\n 'While telemetry is active, record tool outcome and duration in a queued trace span and flush external tool results.',\n}));\n","import { defineHook, type WithRoot } from '@agimon-ai/po-core/extensionFile';\nimport type { PoServerPluginContext } from '@agimon-ai/po-core/serverPlugin';\n\nimport type { LogServerScope } from '../_lib/serverRoot';\nexport default defineHook((context: WithRoot<PoServerPluginContext, LogServerScope>) => ({\n ...context.root.hooks[5]!,\n name: 'trace-tool-start',\n description:\n 'While telemetry is active, capture tool timing and record tool-call debug telemetry in a queued trace span.',\n}));\n","import { defineHook, type WithRoot } from '@agimon-ai/po-core/extensionFile';\nimport type { PoServerPluginContext } from '@agimon-ai/po-core/serverPlugin';\n\nimport type { LogServerScope } from '../_lib/serverRoot';\nexport default defineHook((context: WithRoot<PoServerPluginContext, LogServerScope>) => ({\n ...context.root.hooks[4]!,\n name: 'trace-turn-results',\n description:\n 'While telemetry is active, record turn duration, usage, failures, and tool token samples in a queued trace span.',\n}));\n","import { defineHook, type WithRoot } from '@agimon-ai/po-core/extensionFile';\nimport type { PoServerPluginContext } from '@agimon-ai/po-core/serverPlugin';\n\nimport type { LogServerScope } from '../_lib/serverRoot';\nexport default defineHook((context: WithRoot<PoServerPluginContext, LogServerScope>) => ({\n ...context.root.hooks[3]!,\n name: 'trace-turn-start',\n description:\n 'While telemetry is active, capture turn timing and record turn-start debug telemetry in a queued trace span.',\n}));\n","import { defineResource } from '@agimon-ai/po-core/extensionFile';\nimport { packageResourcePath, readPackageResource } from '@agimon-ai/po-core/serverPlugin';\n\nexport default defineResource({\n name: 'codemode-how-to-logsink',\n description:\n '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.',\n kind: 'skill' as const,\n pinned: true,\n path: packageResourcePath(import.meta.url, 'src/prompts/codemode-how-to-logsink/SKILL.md'),\n read: () => readPackageResource(import.meta.url, 'src/prompts/codemode-how-to-logsink/SKILL.md'),\n});\n","export const AGENT_DIAGNOSTIC_SKILL = {\n name: 'help-how-to-log',\n description:\n '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.',\n} as const;\n","import { defineResource } from '@agimon-ai/po-core/extensionFile';\nimport { PO_HELP_WHEN as HELP_WHEN } from '@agimon-ai/po-core/help';\nimport { packageResourcePath, readPackageResource } from '@agimon-ai/po-core/serverPlugin';\n\nimport { AGENT_DIAGNOSTIC_SKILL } from '../../../../../constants/diagnostics';\n\nexport default defineResource({\n ...AGENT_DIAGNOSTIC_SKILL,\n when: HELP_WHEN,\n kind: 'skill' as const,\n path: packageResourcePath(import.meta.url, 'src/prompts/help-how-to-log/SKILL.md'),\n read: () => readPackageResource(import.meta.url, 'src/prompts/help-how-to-log/SKILL.md'),\n});\n","import { defineTool, type WithRoot } from '@agimon-ai/po-core/extensionFile';\nimport type { PoServerPluginContext } from '@agimon-ai/po-core/serverPlugin';\n\nimport { createLogsinkTool } from '../../../../../services/logsink';\nimport type { LogServerScope } from '../_lib/serverRoot';\n\nexport default defineTool((context: WithRoot<PoServerPluginContext, LogServerScope>) =>\n createLogsinkTool('agentIssues', context.root.logQueries),\n);\n","import { defineTool, type WithRoot } from '@agimon-ai/po-core/extensionFile';\nimport type { PoServerPluginContext } from '@agimon-ai/po-core/serverPlugin';\n\nimport { createLogsinkTool } from '../../../../../services/logsink';\nimport type { LogServerScope } from '../_lib/serverRoot';\n\nexport default defineTool((context: WithRoot<PoServerPluginContext, LogServerScope>) =>\n createLogsinkTool('metrics', context.root.logQueries),\n);\n","import { defineTool, type WithRoot } from '@agimon-ai/po-core/extensionFile';\nimport type { PoServerPluginContext } from '@agimon-ai/po-core/serverPlugin';\n\nimport { createLogsinkTool } from '../../../../../services/logsink';\nimport type { LogServerScope } from '../_lib/serverRoot';\n\nexport default defineTool((context: WithRoot<PoServerPluginContext, LogServerScope>) =>\n createLogsinkTool('search', context.root.logQueries),\n);\n","import { defineTool, type WithRoot } from '@agimon-ai/po-core/extensionFile';\nimport type { PoServerPluginContext } from '@agimon-ai/po-core/serverPlugin';\n\nimport { createLogsinkTool } from '../../../../../services/logsink';\nimport type { LogServerScope } from '../_lib/serverRoot';\n\nexport default defineTool((context: WithRoot<PoServerPluginContext, LogServerScope>) =>\n createLogsinkTool('services', context.root.logQueries),\n);\n","import { defineTool, type WithRoot } from '@agimon-ai/po-core/extensionFile';\nimport type { PoServerPluginContext } from '@agimon-ai/po-core/serverPlugin';\n\nimport { createLogsinkTool } from '../../../../../services/logsink';\nimport type { LogServerScope } from '../_lib/serverRoot';\n\nexport default defineTool((context: WithRoot<PoServerPluginContext, LogServerScope>) =>\n createLogsinkTool('stats', context.root.logQueries),\n);\n","import { defineTool, type WithRoot } from '@agimon-ai/po-core/extensionFile';\nimport type { PoServerPluginContext } from '@agimon-ai/po-core/serverPlugin';\n\nimport { createLogsinkTool } from '../../../../../services/logsink';\nimport type { LogServerScope } from '../_lib/serverRoot';\n\nexport default defineTool((context: WithRoot<PoServerPluginContext, LogServerScope>) =>\n createLogsinkTool('status', context.root.logQueries),\n);\n","import { defineTool, type WithRoot } from '@agimon-ai/po-core/extensionFile';\nimport type { PoServerPluginContext } from '@agimon-ai/po-core/serverPlugin';\n\nimport { createLogsinkTool } from '../../../../../services/logsink';\nimport type { LogServerScope } from '../_lib/serverRoot';\n\nexport default defineTool((context: WithRoot<PoServerPluginContext, LogServerScope>) =>\n createLogsinkTool('trace', context.root.logQueries),\n);\n","// Generated by @agimon-ai/po-build. Do not edit by hand.\nimport { defineServerPlugin, type PoServerSessionPlugin } from '@agimon-ai/po-core/serverPlugin';\nimport { composeServerProviderOverrides } from '@agimon-ai/po-core/serverPlugin';\nimport { composeRootHooks, composeRootInjects } from '@agimon-ai/po-core/extensionFile';\n\nimport rootSession from '../src/extensions/workspaces/sessions/(backend)/root.server';\nimport apiRoute from '../src/extensions/(backend)/api/log/route.server';\nimport commandLogMetrics from '../src/extensions/workspaces/sessions/(backend)/command/log-metrics.server';\nimport hookAgentEnd from '../src/extensions/workspaces/sessions/(backend)/hook/agent-end.server';\nimport hookAgentSettled from '../src/extensions/workspaces/sessions/(backend)/hook/agent-settled.server';\nimport hookAgentStart from '../src/extensions/workspaces/sessions/(backend)/hook/agent-start.server';\nimport hookBeforeProviderRequest from '../src/extensions/workspaces/sessions/(backend)/hook/before-provider-request.server';\nimport hookModelSelect from '../src/extensions/workspaces/sessions/(backend)/hook/model-select.server';\nimport hookSessionShutdown from '../src/extensions/workspaces/sessions/(backend)/hook/session-shutdown.server';\nimport hookSessionStart from '../src/extensions/workspaces/sessions/(backend)/hook/session-start.server';\nimport hookToolExecutionEnd from '../src/extensions/workspaces/sessions/(backend)/hook/tool-execution-end.server';\nimport hookToolExecutionStart from '../src/extensions/workspaces/sessions/(backend)/hook/tool-execution-start.server';\nimport hookTurnEnd from '../src/extensions/workspaces/sessions/(backend)/hook/turn-end.server';\nimport hookTurnStart from '../src/extensions/workspaces/sessions/(backend)/hook/turn-start.server';\nimport resourceCodemodeHowToLogsink from '../src/extensions/workspaces/sessions/(backend)/resource/codemode-how-to-logsink.server';\nimport resourceHelpHowToLog from '../src/extensions/workspaces/sessions/(backend)/resource/help-how-to-log.server';\nimport toolLogsinkAgentIssues from '../src/extensions/workspaces/sessions/(backend)/tool/logsink_agent_issues.server';\nimport toolLogsinkMetrics from '../src/extensions/workspaces/sessions/(backend)/tool/logsink_metrics.server';\nimport toolLogsinkSearch from '../src/extensions/workspaces/sessions/(backend)/tool/logsink_search.server';\nimport toolLogsinkServices from '../src/extensions/workspaces/sessions/(backend)/tool/logsink_services.server';\nimport toolLogsinkStats from '../src/extensions/workspaces/sessions/(backend)/tool/logsink_stats.server';\nimport toolLogsinkStatus from '../src/extensions/workspaces/sessions/(backend)/tool/logsink_status.server';\nimport toolLogsinkTrace from '../src/extensions/workspaces/sessions/(backend)/tool/logsink_trace.server';\n\ntype Factory<T, C> = (context: C) => T;\nconst at = <T, C>(value: T | Factory<T, C>, context: C): T =>\n typeof value === 'function' ? (value as Factory<T, C>)(context) : value;\nconst via = <T>(identity: Record<string, unknown>, value: unknown): T => {\n if (value === undefined) return undefined as T;\n const declaration = value as { relations?: readonly Record<string, unknown>[] };\n return { ...identity, ...declaration, ...(declaration.relations === undefined ? {} : {\n relations: declaration.relations.map((relation) => ({ evidence: 'declared', ...relation })),\n }) } as T;\n};\n\nexport const serverPlugin = defineServerPlugin({\n name: '@agimon-ai/po-log',\n providerOverrides: composeServerProviderOverrides(rootSession),\n injects: composeRootInjects({ session: [rootSession] }),\n host: (context) => ({\n get api(): PoServerSessionPlugin['api'] { return [at(apiRoute, context)]; },\n }),\n workspace: (context) => ({\n get api(): PoServerSessionPlugin['api'] { return [at(apiRoute, context)]; },\n }),\n session: async (context) => {\n const scopeSession = await context.scopeRoot('session', rootSession, context);\n const contextSession = { ...context, root: scopeSession.value };\n return {\n ...composeRootHooks(scopeSession),\n get api(): PoServerSessionPlugin['api'] { return [at(apiRoute, context)]; },\n get commands(): PoServerSessionPlugin['commands'] { return [via({ name: 'log-metrics' }, at(commandLogMetrics, contextSession))]; },\n get hooks(): PoServerSessionPlugin['hooks'] { return [via({ event: 'agent_end' }, at(hookAgentEnd, contextSession)), via({ event: 'agent_settled' }, at(hookAgentSettled, contextSession)), via({ event: 'agent_start' }, at(hookAgentStart, contextSession)), via({ event: 'before_provider_request' }, at(hookBeforeProviderRequest, contextSession)), via({ event: 'model_select' }, at(hookModelSelect, contextSession)), via({ event: 'session_shutdown' }, at(hookSessionShutdown, contextSession)), via({ event: 'session_start' }, at(hookSessionStart, contextSession)), via({ event: 'tool_execution_end' }, at(hookToolExecutionEnd, contextSession)), via({ event: 'tool_execution_start' }, at(hookToolExecutionStart, contextSession)), via({ event: 'turn_end' }, at(hookTurnEnd, contextSession)), via({ event: 'turn_start' }, at(hookTurnStart, contextSession))]; },\n get resources(): PoServerSessionPlugin['resources'] { return [at(resourceCodemodeHowToLogsink, contextSession), at(resourceHelpHowToLog, contextSession)]; },\n get tools(): PoServerSessionPlugin['tools'] { return [via({ name: 'logsink_agent_issues' }, at(toolLogsinkAgentIssues, contextSession)), via({ name: 'logsink_metrics' }, at(toolLogsinkMetrics, contextSession)), via({ name: 'logsink_search' }, at(toolLogsinkSearch, contextSession)), via({ name: 'logsink_services' }, at(toolLogsinkServices, contextSession)), via({ name: 'logsink_stats' }, at(toolLogsinkStats, contextSession)), via({ name: 'logsink_status' }, at(toolLogsinkStatus, contextSession)), via({ name: 'logsink_trace' }, at(toolLogsinkTrace, contextSession))]; },\n services: [...(scopeSession.services ?? [])],\n get activities(): PoServerSessionPlugin['activities'] { return [...(scopeSession.activities ?? [])]; },\n };\n },\n});\n\nexport default serverPlugin;\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AACA,MAAaA,iBAAe;;;ACS5B,MAAa,kBAAkB;CAC7B;CACA;CACA;CACA;CACA;CACA;CACA;AACF;AACA,MAAa,qBAAqB,gBAAgB,KAC/C,WAAW,WAAW,OAAO,QAAQ,WAAW,WAAW,IAAI,OAAO,YAAY,GAAG,GACxF;;AAeA,SAAgB,kBAAkB,QAAwB;CACxD,MAAM,SAAS,wBAAwB;CACvC,OAAO,KAAK,OAAgC;EAC1C,GAAG;EACH,YAAY;GACV,GAAI,OAAO;GACX,GAAI,WAAW,WACX,CAAC,IACD,EACE,OAAO;IACL,MAAM;IACN,MAAM,CAAC,WAAW,SAA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