Luigit
repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by admin

extensions/klaus/src/debug.ts

Raw
import { defineDebug } from "./pi-ext-debug.ts";

const schema = {
	events: [
		"index.module",
		"index.extension.start",
		"index.oauth.model",
		"index.oauth.kind",
		"index.oauth.resolved",
		"index.oauth.fableWarning",
		"index.currentCwd",
		"index.currentSession",
		"index.promptDriftWarning",
		"index.register",
		"index.streamSimple",
		"index.session_start",
		"index.turn_end",
		"index.session_before_switch",
		"index.session_before_fork",
		"index.session_before_compact",
		"index.session_shutdown",
		"bridge.settle.truncated",
		"bridge.create",
		"bridge.listTools",
		"bridge.callTool.start",
		"bridge.callTool.park",
		"bridge.allow",
		"bridge.toolNames",
		"bridge.replaceTools",
		"bridge.hasSchemaChange",
		"bridge.pendingIds",
		"bridge.waitForPending.start",
		"bridge.waitForPending.end",
		"bridge.settle.start",
		"bridge.settle.end",
		"bridge.close.start",
		"bridge.close.end",
		"bridge.errorResult",
		"subscriptionPrompt.rewrite",
		"replay.visibleMessage",
		"replay.contentImages",
		"replay.images.start",
		"replay.images.end",
		"replay.prompt.start",
		"replay.prompt.end",
		"setupToken.exchange.start",
		"setupToken.exchange.response",
		"setupToken.command.start",
		"setupToken.command.cancelled",
		"setupToken.command.minted",
		"setupToken.command.denied",
		"runtime.standard.platformKey.start",
		"runtime.standard.resolve.start",
		"runtime.standard.resolve.end",
		"runtime.standard.resolveCached",
		"runtime.standard.resolve.error",
		"runtime.customHeaders.start",
		"runtime.customHeaders.end",
		"runtime.create.start",
		"runtime.create.configDir",
		"runtime.cleanup.start",
		"runtime.cleanup.end",
		"runtime.create.ready",
		"runtime.create.error",
		"runtime.android.resolve",
		"runtime.android.resolve.error",
		"runtime.android.prepare.start",
		"sdk.prompt.yield",
		"sdk.toolSchemaError",
		"sdk.prompt.build",
		"sdk.start",
		"sdk.runtime.ready",
		"sdk.bridge.ready",
		"sdk.interrupt.start",
		"sdk.interrupt.end",
		"sdk.cleanup.request",
		"sdk.cleanup.start",
		"sdk.cleanup.end",
		"sdk.close.request",
		"sdk.close.abort",
		"sdk.query.call",
		"sdk.stderr",
		"sdk.hook.preToolUse",
		"sdk.canUseTool",
		"sdk.query.returned",
		"sdk.query.error",
		"sdk.pump.start",
		"sdk.pump.message",
		"sdk.position.candidate",
		"sdk.pump.error",
		"sdk.pump.finally",
		"sdk.handle.ready",
		"sdk.setTools",
		"sdk.send",
		"sdk.handleMessage",
		"sdk.message.init",
		"sdk.message.assistant",
		"sdk.message.mirror_error",
		"sdk.message.apiRetry",
		"sdk.message.permissionDenied",
		"sdk.message.workerShuttingDown",
		"sdk.message.informational",
		"sdk.message.rateLimitRejected",
		"sdk.message.result",
		"sdk.message.resultError",
		"sdk.streamEvent",
		"sdk.contentBlock.stop",
		"sdk.messageDelta",
		"coordinator.sink.create",
		"coordinator.sink.content",
		"coordinator.sink.toolUse",
		"coordinator.sink.done",
		"coordinator.sink.error",
		"coordinator.create",
		"coordinator.stream",
		"coordinator.preparePrimaryCache",
		"coordinator.persistCheckpoint.start",
		"coordinator.persistCheckpoint.skip",
		"coordinator.persistCheckpoint.position",
		"coordinator.persistCheckpoint.end",
		"coordinator.closeAll.start",
		"coordinator.closeAll.end",
		"coordinator.invoke.start",
		"coordinator.invoke.batch",
		"coordinator.invoke.continuation",
		"coordinator.invoke.compatibility",
		"coordinator.invoke.error",
		"coordinator.start.begin",
		"coordinator.start.cacheReady",
		"coordinator.start.memoryCandidate",
		"coordinator.start.checkpointLoadError",
		"coordinator.start.candidates",
		"coordinator.start.completed",
		"coordinator.start.reuseFit",
		"coordinator.start.resumePlan",
		"coordinator.start.request",
		"coordinator.start.payloadHook",
		"coordinator.start.payloadTransformed",
		"coordinator.start.scope",
		"coordinator.start.reuseRejectedByHook",
		"coordinator.start.stateAdded",
		"coordinator.callback.ready",
		"coordinator.callback.activity",
		"coordinator.callback.notice",
		"coordinator.callback.content",
		"coordinator.callback.toolBoundary",
		"coordinator.callback.result",
		"coordinator.checkpoint.published",
		"coordinator.callback.error",
		"coordinator.reuse.swapTools",
		"coordinator.reuse.send",
		"coordinator.reuse.error",
		"coordinator.oauth.resolve.start",
		"coordinator.oauth.resolve.end",
		"coordinator.sdk.start",
		"coordinator.sdk.started",
		"coordinator.handle.attached",
		"coordinator.start.error",
		"coordinator.keepForReuse",
		"coordinator.findReusable",
		"coordinator.findContinuation",
		"coordinator.addState",
		"coordinator.replaceAbort",
		"coordinator.touchState",
		"coordinator.checkpointRoot",
		"coordinator.storeFor",
		"coordinator.armTimeout",
		"coordinator.closeState.start",
		"coordinator.closeState.end",
		"coordinator.thinkingBudget",
		"coordinator.finalUserPrompt",
		"coordinator.recentToolResults.start",
		"coordinator.recentToolResults.end",
		"coordinator.isRequest",
		"cache.validateEntry",
		"cache.memory.append.start",
		"cache.memory.append.end",
		"cache.memory.load",
		"cache.memory.listSubkeys",
		"cache.checkpoints.load.start",
		"cache.checkpoints.load.end",
		"cache.checkpoint.load",
		"cache.checkpoint.save.start",
		"cache.checkpoint.save.end",
		"cache.staging.create",
		"cache.staging.append",
		"cache.staging.load",
		"cache.staging.listSubkeys",
		"cache.staging.commit.start",
		"cache.staging.commit.batch",
		"cache.staging.commit.end",
		"cache.file.create",
		"cache.file.ensureManifest",
		"cache.file.prepare.start",
		"cache.file.prepare.end",
		"cache.file.append.start",
		"cache.file.append.end",
		"cache.file.load.start",
		"cache.file.listSubkeys",
		"models.clamp",
		"models.projectModel",
		"models.projectModels",
		"models.klausModels",
		"protocol.isKlausModelId",
		"protocol.toKlausTools",
		"protocol.requiredConstrainedTool",
		"protocol.emptyUsage",
		"protocol.createAssistant",
		"protocol.modelFacingContent",
		"protocol.contextFingerprint.start",
		"protocol.contextFingerprint.end",
		"test.event",
		"test.env",
		"test.disabled",
		"test.failure",
	],
	spans: ["test.operation", "index.oauth", "index.flush"],
	fields: {
		found: "boolean",
		usingOAuth: "boolean",
		hasAuth: "boolean",
		hasScope: "boolean",
		hasLeaf: "boolean",
		persisted: "boolean",
		alreadyWarned: "boolean",
		copied: "boolean",
		closed: "boolean",
		finished: "boolean",
		aborted: "boolean",
		hasCheckpoint: "boolean",
		hasRoot: "boolean",
		hasHandle: "boolean",
		linearResume: "boolean",
		enabled: "boolean",
		transformed: "boolean",
		hadSignal: "boolean",
		isPiSystemPrompt: "boolean",
		existing: "boolean",
		changed: "boolean",
		incompatible: "boolean",
		cached: "boolean",
		count: "number",
		length: "number",
		index: "number",
		toolCount: "number",
		resultCount: "number",
		stateCount: "number",
		batchCount: "number",
		storedCount: "number",
		entryCount: "number",
		imageCount: "number",
		imageIndex: "number",
		originalLength: "number",
		forwardedCount: "number",
		messageCount: "number",
		promptLength: "number",
		outputBytes: "number",
		retries: "number",
		timeoutMs: "number",
		attempt: "number",
		mode: ["tui", "rpc", "json", "print"],
		source: ["registry", "builtin"],
		kind: [
			"missing-resume-uuid",
			"revoked-oauth",
			"redacted",
			"nu",
			"mcp",
			"aborted",
			"failure",
			"host",
			"oauth",
			"flush",
		],
		type: ["system", "assistant", "user", "result", "stream_event"],
		subtype: [
			"init",
			"success",
			"error",
			"api_error",
			"rate_limit",
			"tool_use",
			"tool_result",
		],
	},
} as const;

export const {
	dbg,
	span: debugSpan,
	closeDebug,
}: ReturnType<typeof defineDebug<typeof schema>> = defineDebug(schema);

export function diagnosticKind(
	value: unknown,
): "missing-resume-uuid" | "revoked-oauth" | "redacted" {
	try {
		const text = value instanceof Error ? value.message : String(value);
		if (/No message found with message\.uuid of:/i.test(text))
			return "missing-resume-uuid";
		if (/OAuth access token has been revoked/i.test(text))
			return "revoked-oauth";
	} catch {
		// Debugging must not surface hostile values.
	}
	return "redacted";
}