@ai-ecoverse/slicc-agent 3.50.2 → 3.52.0

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.
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../src/spectrum/messages.ts"],
4
- "sourcesContent": ["import type {\n AssistantMessage,\n AssistantStatus,\n ErrorAction,\n LickMessage,\n Message,\n MessagePart,\n SystemMessage,\n ToolCall,\n ToolStatus,\n Usage,\n UserMessage,\n} from '@ai-ecoverse/slicc-spectrum/ui';\nimport type { ConversationView, EntryRecord } from '@earendil-works/pi-durable';\nimport { splitUser } from '../attachments.ts';\nimport { parseLick } from '../licks/lick.ts';\nimport { entryLick, LICK_TOOLS, type LickDecision, lickDecisions } from '../licks/state.ts';\nimport { mcpLabel } from '../mcp/label.ts';\nimport { FROM_KIND, type From } from '../scoops/from.ts';\nimport type { SecretName } from '../secrets/names.ts';\nimport { listedLine, SECRETS_KIND } from '../secrets/view.ts';\nimport type { Delivered } from '../services.ts';\nimport { SPRINKLE_KIND } from '../sprinkles/kind.ts';\n\ntype Json = Record<string, unknown>;\n\ninterface Block {\n type: string;\n text?: string;\n thinking?: string;\n id?: string;\n name?: string;\n arguments?: Json;\n}\n\ninterface ModelMessage {\n role: string;\n content?: string | Block[];\n timestamp?: number;\n stopReason?: string;\n errorMessage?: string;\n provider?: string;\n model?: string;\n usage?: {\n input?: number;\n output?: number;\n cacheRead?: number;\n cacheWrite?: number;\n cost?: { total?: number };\n };\n toolCallId?: string;\n isError?: boolean;\n details?: { patch?: unknown };\n}\n\ninterface Slot {\n callId: string;\n status: string;\n output?: string;\n}\n\ninterface Live {\n run?: unknown;\n generation?: { message?: ModelMessage; retry?: { at: number; error: string } };\n tools?: Slot[];\n compactions?: { taskId: number; reason: string }[];\n}\n\nexport function textOf(content: ModelMessage['content']): string {\n if (typeof content === 'string') return content;\n return (content ?? []).map((block) => (block.type === 'text' ? (block.text ?? '') : '')).join('');\n}\n\nconst paths = (args: Json | undefined): string[] =>\n typeof args?.path === 'string' ? [args.path] : [];\n\nfunction title(args: Json | undefined): string {\n const subject = args?.command ?? args?.path;\n return typeof subject === 'string' ? subject : '';\n}\n\ninterface Replacement {\n oldText?: string;\n newText?: string;\n}\n\nconst GAP = '\u2026';\n\nfunction seconds(value: unknown): string | undefined {\n return typeof value === 'number' ? `timeout ${value}s` : undefined;\n}\n\nfunction lines(args: Json): string | undefined {\n const { offset, limit } = args as { offset?: number; limit?: number };\n if (typeof offset === 'number' && typeof limit === 'number')\n return `lines ${offset}\u2013${offset + limit - 1}`;\n if (typeof offset === 'number') return `from line ${offset}`;\n return typeof limit === 'number' ? `first ${limit} lines` : undefined;\n}\n\nfunction edits(args: Json): ToolCall['diff'] {\n const list = Array.isArray(args.edits) ? (args.edits as Replacement[]) : [];\n if (list.length === 0) return undefined;\n return {\n before: list.map((edit) => edit.oldText ?? '').join(`\\n${GAP}\\n`),\n after: list.map((edit) => edit.newText ?? '').join(`\\n${GAP}\\n`),\n };\n}\n\nexport function fromPatch(patch: string): ToolCall['diff'] {\n const before: string[] = [];\n const after: string[] = [];\n let hunks = 0;\n for (const line of patch.split('\\n')) {\n if (line.startsWith('@@')) {\n if (hunks++ > 0) {\n before.push(GAP);\n after.push(GAP);\n }\n continue;\n }\n if (hunks === 0 || line === '' || line.startsWith('\\\\')) continue;\n const text = line.slice(1);\n if (line.startsWith('-')) before.push(text);\n else if (line.startsWith('+')) after.push(text);\n else {\n before.push(text);\n after.push(text);\n }\n }\n return hunks ? { before: before.join('\\n'), after: after.join('\\n') } : undefined;\n}\n\nfunction shape(name: string, args: Json): Pick<ToolCall, 'input' | 'meta' | 'diff'> {\n const path = typeof args.path === 'string' ? args.path : '';\n const meta = name === 'bash' ? seconds(args.timeout) : name === 'read' ? lines(args) : undefined;\n const base = meta ? { meta } : {};\n if (name === 'bash' && typeof args.command === 'string') return { input: args.command, ...base };\n if (name === 'read' || name === 'write') return { input: path, ...base };\n if (name === 'edit') {\n const diff = edits(args);\n return { input: path, ...(diff ? { diff } : {}) };\n }\n return { input: JSON.stringify(args, null, 2) };\n}\n\nfunction toolCall(block: Block): ToolCall {\n const args = block.arguments ?? {};\n return {\n id: block.id ?? '',\n name: block.name ?? 'tool',\n title: mcpLabel(block.name ?? '') ?? title(block.arguments),\n ...shape(block.name ?? 'tool', args),\n output: '',\n status: 'running',\n paths: paths(block.arguments),\n };\n}\n\nfunction part(block: Block): MessagePart | undefined {\n if (block.type === 'text') return { type: 'text', text: block.text ?? '' };\n if (block.type === 'thinking') return { type: 'thinking', text: block.thinking ?? '' };\n if (block.type === 'toolCall') return { type: 'tool', tool: toolCall(block) };\n return undefined;\n}\n\nfunction usage(message: ModelMessage): Usage | undefined {\n const used = message.usage;\n if (!used) return undefined;\n return {\n input: used.input ?? 0,\n output: used.output ?? 0,\n cost: used.cost?.total ?? 0,\n cacheRead: used.cacheRead ?? 0,\n cacheWrite: used.cacheWrite ?? 0,\n };\n}\n\nconst statuses: Record<string, AssistantStatus> = { error: 'error', aborted: 'stopped' };\n\nconst credentials =\n /security token|unrecognizedclient|not authori[sz]ed|unauthori[sz]ed|forbidden|\\b40[13]\\b|api key|credential|bearer/i;\nconst models = /model/i;\nconst unavailable =\n /access|invalid|not found|identifier|unsupported|not supported|isn['\u2019]t supported|not available|isn['\u2019]t available/i;\n\nconst providerNames: Record<string, string> = { 'amazon-bedrock': 'Bedrock' };\nconst filtered =\n /Provider (?:stopped with|finish_reason): (?:content_filter(?:ed)?|guardrail_intervened|sensitive)|content[_ ]filter(?:ed|ing)?\\b|guardrail[_ ]intervened/i;\nconst refused =\n /refused to complete the request|Provider (?:stopped with|finish_reason): refusal|\\bstop_?reason\\W+refusal\\b/i;\nconst missing = /no api key|missing|not configured|no credentials/i;\nconst adobeAuth =\n /\\b401\\b|authenticat|unauthori[sz]ed|expired|invalid[_ ]?(?:token|credentials?|api[_ ]key)|token verification|no api key|not configured|no credentials/i;\n\nfunction proxyRefusal(error: string): { message: string; detail: string } {\n try {\n const body = JSON.parse(error.match(/\\{.*\\}/s)?.[0] ?? '') as {\n error?: { type?: unknown; message?: unknown };\n };\n const { type, message } = body.error ?? {};\n const status = error.match(/^\\s*(\\d{3})\\b/)?.[1];\n return {\n message: typeof message === 'string' ? message : error,\n detail: typeof type === 'string' ? [status, type].filter(Boolean).join(' ') : error,\n };\n } catch {\n return { message: error, detail: error };\n }\n}\n\nexport function errorPart(error: string, provider?: string): MessagePart {\n const action = errorAction(error);\n if (action === 'drop-turn') {\n return {\n type: 'error',\n message: filtered.test(error)\n ? \"The model's content filter stopped this reply.\"\n : 'The model refused to answer this turn.',\n detail: error,\n action,\n };\n }\n if (action === 'settings' && provider === 'adobe') {\n return adobeAuth.test(error)\n ? {\n type: 'error',\n message: 'Your Adobe session has expired.',\n detail: error,\n action: 'login',\n }\n : { type: 'error', ...proxyRefusal(error), action: 'retry' };\n }\n const name = providerNames[provider ?? ''] ?? 'The provider';\n const lead =\n action === 'settings'\n ? missing.test(error)\n ? `${name} needs an API key.`\n : `${name} rejected the API key.`\n : action === 'change-model'\n ? \"This model isn't available with the current account.\"\n : null;\n return lead\n ? { type: 'error', message: lead, detail: error, action }\n : { type: 'error', message: error, action };\n}\n\nexport function errorAction(message: string): ErrorAction {\n if (filtered.test(message) || refused.test(message)) return 'drop-turn';\n if (credentials.test(message)) return 'settings';\n if (models.test(message) && unavailable.test(message)) return 'change-model';\n return 'retry';\n}\n\nfunction sprinkleMessage(id: string, entry: EntryRecord): AssistantMessage {\n const data = (entry.data ?? {}) as { sprinkle?: unknown; at?: unknown };\n return {\n id,\n role: 'assistant',\n parts: [{ type: 'sprinkle', sprinkle: String(data.sprinkle ?? '') }],\n status: 'done',\n createdAt: typeof data.at === 'number' ? data.at : 0,\n };\n}\n\nexport function assistant(\n id: string,\n message: ModelMessage,\n status?: AssistantStatus\n): AssistantMessage {\n const blocks = Array.isArray(message.content) ? message.content : [];\n const parts = blocks.map(part).filter((item): item is MessagePart => item !== undefined);\n if (message.errorMessage) parts.push(errorPart(message.errorMessage, message.provider));\n const used = usage(message);\n return {\n id,\n role: 'assistant',\n parts,\n status: status ?? statuses[message.stopReason ?? ''] ?? 'done',\n createdAt: message.timestamp ?? 0,\n ...(message.provider && message.model ? { model: `${message.provider}/${message.model}` } : {}),\n ...(used ? { usage: used } : {}),\n };\n}\n\nfunction user(\n id: string,\n message: ModelMessage,\n delivered: Delivered | undefined,\n from: From | undefined\n): UserMessage {\n return {\n id,\n role: 'user',\n ...shownUser(message.content, `ref:${id.slice(1)}:0`),\n createdAt: message.timestamp ?? 0,\n ...(delivered ? { delivered } : {}),\n ...(from ? { from: from.from } : {}),\n ...(from?.agent ? { origin: 'agent' as const } : {}),\n };\n}\n\nexport function origins(entries: readonly EntryRecord[]): Map<number, From> {\n const out = new Map<number, From>();\n for (const entry of entries)\n if (entry.kind === FROM_KIND) {\n const note = entry.data as From;\n out.set(note.entry, note);\n }\n return out;\n}\n\nfunction lickMessage(\n id: string,\n entry: EntryRecord,\n decisions: ReadonlyMap<string, LickDecision>\n): LickMessage | undefined {\n const lick = entryLick(entry);\n if (!lick) return undefined;\n const state = lick.actions?.length ? (decisions.get(lick.id) ?? 'pending') : undefined;\n return {\n id,\n role: 'lick',\n channel: lick.channel,\n title: lick.title,\n text: lick.text,\n createdAt: lick.at,\n ...(lick.body ? { body: lick.body } : {}),\n ...(lick.count > 1 ? { count: lick.count } : {}),\n ...(state ? { state } : {}),\n ...(lick.severity ? { severity: lick.severity } : {}),\n };\n}\n\nfunction withoutLickTools(message: AssistantMessage): AssistantMessage {\n const parts = message.parts.filter((item) => item.type !== 'tool' || !LICK_TOOLS[item.tool.name]);\n return parts.length === message.parts.length ? message : { ...message, parts };\n}\n\nfunction system(id: string, entry: EntryRecord, text: string): SystemMessage {\n const reason = (entry.data as Json | undefined)?.reason as SystemMessage['trigger'] | undefined;\n return {\n id,\n role: 'system',\n kind: 'compaction',\n text,\n createdAt: 0,\n state: 'summarized',\n ...(reason ? { trigger: reason } : {}),\n };\n}\n\nfunction tools(messages: Message[]): Map<string, ToolCall> {\n const found = new Map<string, ToolCall>();\n for (const message of messages) {\n if (message.role !== 'assistant') continue;\n for (const item of message.parts) if (item.type === 'tool') found.set(item.tool.id, item.tool);\n }\n return found;\n}\n\ninterface Diagnostic {\n severity: string;\n message: string;\n}\n\ninterface Note {\n severity: 'error' | 'warn' | 'info';\n text: string;\n}\n\ntype Card = ToolCall & { notes?: Note[] };\n\nconst RANK: Note['severity'][] = ['error', 'warn', 'info'];\n\nconst LINE = /^\\[(error|warn|info)\\] (.*)$/;\n\nfunction rendered(diagnostics: readonly Diagnostic[]): string {\n return `<harness>\\n${diagnostics.map((item) => `[${item.severity}] ${item.message}`).join('\\n')}\\n</harness>`;\n}\n\nfunction parsed(text: string): Diagnostic[] | undefined {\n const body = /^<harness>\\n([\\s\\S]*)\\n<\\/harness>$/.exec(text)?.[1];\n if (body === undefined) return undefined;\n const found = body.split('\\n').map((line) => LINE.exec(line));\n if (!found.every((match): match is RegExpExecArray => match !== null)) return undefined;\n return found.map(([, severity, message]) => ({ severity, message }) as Diagnostic);\n}\n\nfunction harness(\n content: ModelMessage['content'],\n data: unknown\n): { content: ModelMessage['content']; diagnostics: Diagnostic[] } {\n const last = Array.isArray(content) ? content.at(-1) : undefined;\n const stored = (data as { diagnostics?: unknown } | undefined)?.diagnostics;\n const listed = Array.isArray(stored) ? (stored as Diagnostic[]) : parsed(last?.text ?? '');\n if (!listed?.length || last?.type !== 'text' || last.text !== rendered(listed))\n return { content, diagnostics: [] };\n return { content: (content as Block[]).slice(0, -1), diagnostics: listed };\n}\n\nconst count = (value: string | undefined): string => Number(value).toLocaleString('en');\n\nconst ends: Record<string, string> = { end: ' from the start', beginning: ' from the end' };\n\nconst phrasings: [RegExp, (match: RegExpExecArray) => string][] = [\n [/^Command exited with code (-?\\d+)$/, (match) => `Exited with code ${match[1]}`],\n [/^Command timed out after (.+)$/, (match) => `Timed out after ${match[1]}`],\n [/^Command aborted$/, () => 'Aborted'],\n [/^Full output: (.+)$/, (match) => `Full output in ${match[1]}`],\n [\n /^Output truncated(?: to its (beginning|end))?: (\\d+) lines, (\\d+) bytes dropped$/,\n (match) =>\n `Output truncated: ${count(match[2])} lines and ${count(match[3])} bytes dropped${ends[match[1] ?? ''] ?? ''}`,\n ],\n];\n\nfunction phrased(message: string): string {\n const line = message\n .replace(/\\n[\\s\\S]*$/, '')\n .trim()\n .replace(/\\.$/, '');\n for (const [pattern, phrase] of phrasings) {\n const match = pattern.exec(line);\n if (match) return phrase(match);\n }\n return line;\n}\n\nfunction note(diagnostic: Diagnostic): Note {\n return { severity: diagnostic.severity as Note['severity'], text: phrased(diagnostic.message) };\n}\n\nfunction settle(calls: Map<string, ToolCall>, result: ModelMessage, data?: unknown): void {\n const call = calls.get(result.toolCallId ?? '') as Card | undefined;\n if (!call) return;\n const split = harness(result.content, data);\n call.output = textOf(split.content);\n if (split.diagnostics.length)\n call.notes = split.diagnostics\n .map(note)\n .sort((a, b) => RANK.indexOf(a.severity) - RANK.indexOf(b.severity));\n call.status = result.isError ? 'error' : 'done';\n const image = Array.isArray(result.content)\n ? (result.content as { type: string; data?: string; mimeType?: string }[]).find(\n (part) => part.type === 'image' && part.data && part.mimeType\n )\n : undefined;\n if (image) call.image = `data:${image.mimeType};base64,${image.data}`;\n const patch = result.details?.patch;\n const diff = typeof patch === 'string' ? fromPatch(patch) : undefined;\n if (diff) call.diff = diff;\n else if (result.isError) delete call.diff;\n}\n\nfunction rewound(id: string, entry: EntryRecord): SystemMessage {\n const data = (entry.data ?? {}) as { stopped?: string[]; restored?: string[]; files?: boolean };\n const notes = [\n 'Its prompt is back in the composer.',\n ...(data.stopped?.length\n ? [`Stopped ${data.stopped.map((name) => `scoop ${name}`).join(', ')}.`]\n : []),\n ...(data.restored?.length\n ? [`Restored ${data.restored.map((name) => `scoop ${name}`).join(', ')}.`]\n : []),\n ...(data.files ? ['Changed files stay; use Changes or git to revert them.'] : []),\n ];\n return {\n id,\n role: 'system',\n kind: 'notice',\n title: 'Rewound 1 turn',\n text: notes.join(' '),\n createdAt: 0,\n };\n}\n\nfunction thawed(id: string, entry: EntryRecord): SystemMessage {\n const data = (entry.data ?? {}) as { name?: string; kind?: string };\n const what = data.kind === 'agent' ? 'agent run' : 'scoop';\n return {\n id,\n role: 'system',\n kind: 'notice',\n title: `Thawed from ${what} ${data.name ?? ''}`.trim(),\n text: textOf(entry.model?.[0]?.content ?? ''),\n createdAt: entry.model?.[0]?.timestamp ?? 0,\n };\n}\n\nfunction secrets(id: string, entry: EntryRecord): SystemMessage {\n const data = (entry.data ?? {}) as { names?: SecretName[] };\n return {\n id,\n role: 'system',\n kind: 'notice',\n title: 'Secrets listed',\n text: listedLine(data.names ?? []),\n createdAt: entry.model?.[0]?.timestamp ?? 0,\n };\n}\n\nfunction entryMessage(\n entry: EntryRecord,\n out: Message[],\n calls: Map<string, ToolCall>,\n delivered: Delivered | undefined,\n notes: { decisions: ReadonlyMap<string, LickDecision>; origins: ReadonlyMap<number, From> }\n): void {\n const id = `e${entry.id}`;\n const model = entry.model?.[0] as ModelMessage | undefined;\n if (entry.kind === 'slicc.rewound') out.push(rewound(id, entry));\n if (entry.kind === 'slicc.thawed') out.push(thawed(id, entry));\n else if (entry.kind === SECRETS_KIND) out.push(secrets(id, entry));\n else if (entry.kind === SPRINKLE_KIND) out.push(sprinkleMessage(id, entry));\n else if (entry.kind === 'pi.user' && model)\n out.push(\n lickMessage(id, entry, notes.decisions) ??\n user(id, model, delivered, notes.origins.get(entry.id))\n );\n else if (entry.kind === 'pi.assistant' && model) {\n const message = assistant(id, model);\n out.push(withoutLickTools(message));\n for (const [key, value] of tools([message])) calls.set(key, value);\n } else if (entry.kind === 'pi.tool-result' && model) settle(calls, model, entry.data);\n else if (entry.kind === 'pi.compaction') out.push(system(id, entry, textOf(model?.content)));\n}\n\nconst slotStatus: Record<string, ToolStatus> = {\n pending: 'running',\n running: 'running',\n done: 'done',\n};\n\nfunction live(view: ConversationView, out: Message[], calls: Map<string, ToolCall>): void {\n const state = view.docs['pi.live'] as Live | undefined;\n for (const slot of state?.tools ?? []) {\n const call = calls.get(slot.callId);\n if (call && call.status === 'running') {\n call.status = slotStatus[slot.status] ?? 'running';\n call.output = slot.output ?? call.output;\n }\n }\n const partial = state?.generation?.message;\n if (partial) out.push(assistant('live', partial, 'streaming'));\n for (const compaction of state?.compactions ?? []) {\n out.push({\n id: `compaction-${compaction.taskId}`,\n role: 'system',\n kind: 'compaction',\n text: '',\n createdAt: 0,\n state: 'summarizing',\n trigger: compaction.reason as SystemMessage['trigger'],\n });\n }\n const retry = state?.generation?.retry;\n if (retry)\n out.push({\n id: 'retry',\n role: 'system',\n kind: 'notice',\n text: retry.error,\n createdAt: retry.at,\n });\n}\n\nexport function toMessages(\n view: ConversationView | undefined,\n deliveries: Readonly<Record<string, Delivered>> = {}\n): Message[] {\n const out: Message[] = [];\n if (!view) return out;\n const calls = new Map<string, ToolCall>();\n const notes = { decisions: lickDecisions(view.entries), origins: origins(view.entries) };\n let previous: EntryRecord | undefined;\n for (const entry of view.entries) {\n const steered = previous?.kind === 'pi.tool-result' ? 'steer' : undefined;\n entryMessage(entry, out, calls, deliveries[String(entry.id)] ?? steered, notes);\n previous = entry;\n }\n live(view, out, calls);\n return out;\n}\n\nfunction shownUser(\n content: ModelMessage['content'],\n prefix?: string\n): Pick<UserMessage, 'text' | 'attachments'> {\n const { text, attachments } = splitUser(content, prefix);\n return attachments.length ? { text, attachments } : { text };\n}\n\nexport function isBusy(view: ConversationView | undefined): boolean {\n return Boolean((view?.docs['pi.live'] as Live | undefined)?.run);\n}\n\nexport function queued(view: ConversationView | undefined): UserMessage[] {\n const items = ((view?.docs['pi.inbox'] as { items?: Json[] } | undefined)?.items ?? []) as {\n id: number;\n mode: string;\n content?: ModelMessage['content'];\n }[];\n return items\n .filter((item) => item.mode !== 'write' && !parseLick(textOf(item.content)))\n .map((item) => ({\n id: `q${item.id}`,\n role: 'user'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,GACxC;AACX,QAAM,MAAiB,CAAC;AACxB,MAAI,CAAC,KAAM,QAAO;AAClB,QAAM,QAAQ,oBAAI,IAAsB;AACxC,QAAM,QAAQ,EAAE,WAAW,cAAc,KAAK,OAAO,GAAG,SAAS,QAAQ,KAAK,OAAO,EAAE;AACvF,MAAI;AACJ,aAAW,SAAS,KAAK,SAAS;AAChC,UAAM,UAAU,UAAU,SAAS,mBAAmB,UAAU;AAChE,iBAAa,OAAO,KAAK,OAAO,WAAW,OAAO,MAAM,EAAE,CAAC,KAAK,SAAS,KAAK;AAC9E,eAAW;AAAA,EACb;AACA,OAAK,MAAM,KAAK,KAAK;AACrB,SAAO;AACT;AAEA,SAAS,UACP,SACA,QAC2C;AAC3C,QAAM,EAAE,MAAM,YAAY,IAAI,UAAU,SAAS,MAAM;AACvD,SAAO,YAAY,SAAS,EAAE,MAAM,YAAY,IAAI,EAAE,KAAK;AAC7D;AAEO,SAAS,OAAO,MAA6C;AAClE,SAAO,QAAS,MAAM,KAAK,SAAS,GAAwB,GAAG;AACjE;AAEO,SAAS,OAAO,MAAmD;AACxE,QAAM,QAAU,MAAM,KAAK,UAAU,GAAsC,SAAS,CAAC;AAKrF,SAAO,MACJ,OAAO,CAAC,SAAS,KAAK,SAAS,WAAW,CAAC,UAAU,OAAO,KAAK,OAAO,CAAC,CAAC,EAC1E,IAAI,CAAC,UAAU;AAAA,IACd,IAAI,IAAI,KAAK,EAAE;AAAA,IACf,MAAM;AAAA,IACN,GAAG,UAAU,KAAK,OAAO;AAAA,IACzB,WAAW;AAAA,IACX,QAAQ;AAAA,IACR,MAAM,KAAK,SAAS,UAAU,UAAU;AAAA,EAC1C,EAAE;AACN;",
4
+ "sourcesContent": ["import type {\n AssistantMessage,\n AssistantStatus,\n ErrorAction,\n LickMessage,\n Message,\n MessagePart,\n SystemMessage,\n ToolCall,\n ToolStatus,\n Usage,\n UserMessage,\n} from '@ai-ecoverse/slicc-spectrum/ui';\nimport type { ConversationView, EntryRecord } from '@earendil-works/pi-durable';\nimport { splitUser } from '../attachments.ts';\nimport { parseLick } from '../licks/lick.ts';\nimport { entryLick, LICK_TOOLS, type LickDecision, lickDecisions } from '../licks/state.ts';\nimport { mcpLabel } from '../mcp/label.ts';\nimport { FROM_KIND, type From } from '../scoops/from.ts';\nimport type { SecretName } from '../secrets/names.ts';\nimport { listedLine, SECRETS_KIND } from '../secrets/view.ts';\nimport type { Delivered } from '../services.ts';\nimport { SPRINKLE_KIND } from '../sprinkles/kind.ts';\n\ntype Json = Record<string, unknown>;\n\ninterface Block {\n type: string;\n text?: string;\n thinking?: string;\n id?: string;\n name?: string;\n arguments?: Json;\n}\n\ninterface ModelMessage {\n role: string;\n content?: string | Block[];\n timestamp?: number;\n stopReason?: string;\n errorMessage?: string;\n provider?: string;\n model?: string;\n usage?: {\n input?: number;\n output?: number;\n cacheRead?: number;\n cacheWrite?: number;\n cost?: { total?: number };\n };\n toolCallId?: string;\n isError?: boolean;\n details?: { patch?: unknown };\n}\n\ninterface Slot {\n callId: string;\n status: string;\n output?: string;\n}\n\ninterface Live {\n run?: unknown;\n generation?: { message?: ModelMessage; retry?: { at: number; error: string } };\n tools?: Slot[];\n compactions?: { taskId: number; reason: string }[];\n}\n\nexport function textOf(content: ModelMessage['content']): string {\n if (typeof content === 'string') return content;\n return (content ?? []).map((block) => (block.type === 'text' ? (block.text ?? '') : '')).join('');\n}\n\nconst paths = (args: Json | undefined): string[] =>\n typeof args?.path === 'string' ? [args.path] : [];\n\nfunction title(args: Json | undefined): string {\n const subject = args?.command ?? args?.path;\n return typeof subject === 'string' ? subject : '';\n}\n\ninterface Replacement {\n oldText?: string;\n newText?: string;\n}\n\nconst GAP = '\u2026';\n\nfunction seconds(value: unknown): string | undefined {\n return typeof value === 'number' ? `timeout ${value}s` : undefined;\n}\n\nfunction lines(args: Json): string | undefined {\n const { offset, limit } = args as { offset?: number; limit?: number };\n if (typeof offset === 'number' && typeof limit === 'number')\n return `lines ${offset}\u2013${offset + limit - 1}`;\n if (typeof offset === 'number') return `from line ${offset}`;\n return typeof limit === 'number' ? `first ${limit} lines` : undefined;\n}\n\nfunction edits(args: Json): ToolCall['diff'] {\n const list = Array.isArray(args.edits) ? (args.edits as Replacement[]) : [];\n if (list.length === 0) return undefined;\n return {\n before: list.map((edit) => edit.oldText ?? '').join(`\\n${GAP}\\n`),\n after: list.map((edit) => edit.newText ?? '').join(`\\n${GAP}\\n`),\n };\n}\n\nexport function fromPatch(patch: string): ToolCall['diff'] {\n const before: string[] = [];\n const after: string[] = [];\n let hunks = 0;\n for (const line of patch.split('\\n')) {\n if (line.startsWith('@@')) {\n if (hunks++ > 0) {\n before.push(GAP);\n after.push(GAP);\n }\n continue;\n }\n if (hunks === 0 || line === '' || line.startsWith('\\\\')) continue;\n const text = line.slice(1);\n if (line.startsWith('-')) before.push(text);\n else if (line.startsWith('+')) after.push(text);\n else {\n before.push(text);\n after.push(text);\n }\n }\n return hunks ? { before: before.join('\\n'), after: after.join('\\n') } : undefined;\n}\n\nfunction shape(name: string, args: Json): Pick<ToolCall, 'input' | 'meta' | 'diff'> {\n const path = typeof args.path === 'string' ? args.path : '';\n const meta = name === 'bash' ? seconds(args.timeout) : name === 'read' ? lines(args) : undefined;\n const base = meta ? { meta } : {};\n if (name === 'bash' && typeof args.command === 'string') return { input: args.command, ...base };\n if (name === 'read' || name === 'write') return { input: path, ...base };\n if (name === 'edit') {\n const diff = edits(args);\n return { input: path, ...(diff ? { diff } : {}) };\n }\n return { input: JSON.stringify(args, null, 2) };\n}\n\nfunction toolCall(block: Block): ToolCall {\n const args = block.arguments ?? {};\n return {\n id: block.id ?? '',\n name: block.name ?? 'tool',\n title: mcpLabel(block.name ?? '') ?? title(block.arguments),\n ...shape(block.name ?? 'tool', args),\n output: '',\n status: 'running',\n paths: paths(block.arguments),\n };\n}\n\nfunction part(block: Block): MessagePart | undefined {\n if (block.type === 'text') return { type: 'text', text: block.text ?? '' };\n if (block.type === 'thinking') return { type: 'thinking', text: block.thinking ?? '' };\n if (block.type === 'toolCall') return { type: 'tool', tool: toolCall(block) };\n return undefined;\n}\n\nfunction usage(message: ModelMessage): Usage | undefined {\n const used = message.usage;\n if (!used) return undefined;\n return {\n input: used.input ?? 0,\n output: used.output ?? 0,\n cost: used.cost?.total ?? 0,\n cacheRead: used.cacheRead ?? 0,\n cacheWrite: used.cacheWrite ?? 0,\n };\n}\n\nconst statuses: Record<string, AssistantStatus> = { error: 'error', aborted: 'stopped' };\n\nconst credentials =\n /security token|unrecognizedclient|not authori[sz]ed|unauthori[sz]ed|forbidden|\\b40[13]\\b|api key|credential|bearer/i;\nconst models = /model/i;\nconst unavailable =\n /access|invalid|not found|identifier|unsupported|not supported|isn['\u2019]t supported|not available|isn['\u2019]t available/i;\n\nconst providerNames: Record<string, string> = { 'amazon-bedrock': 'Bedrock' };\nconst filtered =\n /Provider (?:stopped with|finish_reason): (?:content_filter(?:ed)?|guardrail_intervened|sensitive)|content[_ ]filter(?:ed|ing)?\\b|guardrail[_ ]intervened/i;\nconst refused =\n /refused to complete the request|Provider (?:stopped with|finish_reason): refusal|\\bstop_?reason\\W+refusal\\b/i;\nconst missing = /no api key|missing|not configured|no credentials/i;\nconst adobeAuth =\n /\\b401\\b|authenticat|unauthori[sz]ed|expired|invalid[_ ]?(?:token|credentials?|api[_ ]key)|token verification|no api key|not configured|no credentials/i;\n\nfunction proxyRefusal(error: string): { message: string; detail: string } {\n try {\n const body = JSON.parse(error.match(/\\{.*\\}/s)?.[0] ?? '') as {\n error?: { type?: unknown; message?: unknown };\n };\n const { type, message } = body.error ?? {};\n const status = error.match(/^\\s*(\\d{3})\\b/)?.[1];\n return {\n message: typeof message === 'string' ? message : error,\n detail: typeof type === 'string' ? [status, type].filter(Boolean).join(' ') : error,\n };\n } catch {\n return { message: error, detail: error };\n }\n}\n\nexport function errorPart(error: string, provider?: string): MessagePart {\n const action = errorAction(error);\n if (action === 'drop-turn') {\n return {\n type: 'error',\n message: filtered.test(error)\n ? \"The model's content filter stopped this reply.\"\n : 'The model refused to answer this turn.',\n detail: error,\n action,\n };\n }\n if (action === 'settings' && provider === 'adobe') {\n return adobeAuth.test(error)\n ? {\n type: 'error',\n message: 'Your Adobe session has expired.',\n detail: error,\n action: 'login',\n }\n : { type: 'error', ...proxyRefusal(error), action: 'retry' };\n }\n const name = providerNames[provider ?? ''] ?? 'The provider';\n const lead =\n action === 'settings'\n ? missing.test(error)\n ? `${name} needs an API key.`\n : `${name} rejected the API key.`\n : action === 'change-model'\n ? \"This model isn't available with the current account.\"\n : null;\n return lead\n ? { type: 'error', message: lead, detail: error, action }\n : { type: 'error', message: error, action };\n}\n\nexport function errorAction(message: string): ErrorAction {\n if (filtered.test(message) || refused.test(message)) return 'drop-turn';\n if (credentials.test(message)) return 'settings';\n if (models.test(message) && unavailable.test(message)) return 'change-model';\n return 'retry';\n}\n\nfunction sprinkleMessage(id: string, entry: EntryRecord): AssistantMessage {\n const data = (entry.data ?? {}) as { sprinkle?: unknown; at?: unknown };\n return {\n id,\n role: 'assistant',\n parts: [{ type: 'sprinkle', sprinkle: String(data.sprinkle ?? '') }],\n status: 'done',\n createdAt: typeof data.at === 'number' ? data.at : 0,\n };\n}\n\nexport function assistant(\n id: string,\n message: ModelMessage,\n status?: AssistantStatus\n): AssistantMessage {\n const blocks = Array.isArray(message.content) ? message.content : [];\n const parts = blocks.map(part).filter((item): item is MessagePart => item !== undefined);\n if (message.errorMessage) parts.push(errorPart(message.errorMessage, message.provider));\n const used = usage(message);\n return {\n id,\n role: 'assistant',\n parts,\n status: status ?? statuses[message.stopReason ?? ''] ?? 'done',\n createdAt: message.timestamp ?? 0,\n ...(message.provider && message.model ? { model: `${message.provider}/${message.model}` } : {}),\n ...(used ? { usage: used } : {}),\n };\n}\n\nfunction user(\n id: string,\n message: ModelMessage,\n delivered: Delivered | undefined,\n from: From | undefined\n): UserMessage {\n return {\n id,\n role: 'user',\n ...shownUser(message.content, `ref:${id.slice(1)}:0`),\n createdAt: message.timestamp ?? 0,\n ...(delivered ? { delivered } : {}),\n ...(from ? { from: from.from } : {}),\n ...(from?.agent ? { origin: 'agent' as const } : {}),\n };\n}\n\nexport function origins(entries: readonly EntryRecord[]): Map<number, From> {\n const out = new Map<number, From>();\n for (const entry of entries)\n if (entry.kind === FROM_KIND) {\n const note = entry.data as From;\n out.set(note.entry, note);\n }\n return out;\n}\n\nfunction lickMessage(\n id: string,\n entry: EntryRecord,\n decisions: ReadonlyMap<string, LickDecision>\n): LickMessage | undefined {\n const lick = entryLick(entry);\n if (!lick) return undefined;\n const state = lick.actions?.length ? (decisions.get(lick.id) ?? 'pending') : undefined;\n return {\n id,\n role: 'lick',\n channel: lick.channel,\n title: lick.title,\n text: lick.text,\n createdAt: lick.at,\n ...(lick.body ? { body: lick.body } : {}),\n ...(lick.count > 1 ? { count: lick.count } : {}),\n ...(state ? { state } : {}),\n ...(lick.severity ? { severity: lick.severity } : {}),\n };\n}\n\nfunction withoutLickTools(message: AssistantMessage): AssistantMessage {\n const parts = message.parts.filter((item) => item.type !== 'tool' || !LICK_TOOLS[item.tool.name]);\n return parts.length === message.parts.length ? message : { ...message, parts };\n}\n\nfunction system(id: string, entry: EntryRecord, text: string): SystemMessage {\n const reason = (entry.data as Json | undefined)?.reason as SystemMessage['trigger'] | undefined;\n return {\n id,\n role: 'system',\n kind: 'compaction',\n text,\n createdAt: 0,\n state: 'summarized',\n ...(reason ? { trigger: reason } : {}),\n };\n}\n\nfunction tools(messages: Message[]): Map<string, ToolCall> {\n const found = new Map<string, ToolCall>();\n for (const message of messages) {\n if (message.role !== 'assistant') continue;\n for (const item of message.parts) if (item.type === 'tool') found.set(item.tool.id, item.tool);\n }\n return found;\n}\n\ninterface Diagnostic {\n severity: string;\n message: string;\n}\n\ninterface Note {\n severity: 'error' | 'warn' | 'info';\n text: string;\n}\n\ntype Card = ToolCall & { notes?: Note[] };\n\nconst RANK: Note['severity'][] = ['error', 'warn', 'info'];\n\nconst LINE = /^\\[(error|warn|info)\\] (.*)$/;\n\nfunction rendered(diagnostics: readonly Diagnostic[]): string {\n return `<harness>\\n${diagnostics.map((item) => `[${item.severity}] ${item.message}`).join('\\n')}\\n</harness>`;\n}\n\nfunction parsed(text: string): Diagnostic[] | undefined {\n const body = /^<harness>\\n([\\s\\S]*)\\n<\\/harness>$/.exec(text)?.[1];\n if (body === undefined) return undefined;\n const found = body.split('\\n').map((line) => LINE.exec(line));\n if (!found.every((match): match is RegExpExecArray => match !== null)) return undefined;\n return found.map(([, severity, message]) => ({ severity, message }) as Diagnostic);\n}\n\nfunction harness(\n content: ModelMessage['content'],\n data: unknown\n): { content: ModelMessage['content']; diagnostics: Diagnostic[] } {\n const last = Array.isArray(content) ? content.at(-1) : undefined;\n const stored = (data as { diagnostics?: unknown } | undefined)?.diagnostics;\n const listed = Array.isArray(stored) ? (stored as Diagnostic[]) : parsed(last?.text ?? '');\n if (!listed?.length || last?.type !== 'text' || last.text !== rendered(listed))\n return { content, diagnostics: [] };\n return { content: (content as Block[]).slice(0, -1), diagnostics: listed };\n}\n\nconst count = (value: string | undefined): string => Number(value).toLocaleString('en');\n\nconst ends: Record<string, string> = { end: ' from the start', beginning: ' from the end' };\n\nconst phrasings: [RegExp, (match: RegExpExecArray) => string][] = [\n [/^Command exited with code (-?\\d+)$/, (match) => `Exited with code ${match[1]}`],\n [/^Command timed out after (.+)$/, (match) => `Timed out after ${match[1]}`],\n [/^Command aborted$/, () => 'Aborted'],\n [/^Full output: (.+)$/, (match) => `Full output in ${match[1]}`],\n [\n /^Output truncated(?: to its (beginning|end))?: (\\d+) lines, (\\d+) bytes dropped$/,\n (match) =>\n `Output truncated: ${count(match[2])} lines and ${count(match[3])} bytes dropped${ends[match[1] ?? ''] ?? ''}`,\n ],\n];\n\nfunction phrased(message: string): string {\n const line = message\n .replace(/\\n[\\s\\S]*$/, '')\n .trim()\n .replace(/\\.$/, '');\n for (const [pattern, phrase] of phrasings) {\n const match = pattern.exec(line);\n if (match) return phrase(match);\n }\n return line;\n}\n\nfunction note(diagnostic: Diagnostic): Note {\n return { severity: diagnostic.severity as Note['severity'], text: phrased(diagnostic.message) };\n}\n\nfunction settle(calls: Map<string, ToolCall>, result: ModelMessage, data?: unknown): void {\n const call = calls.get(result.toolCallId ?? '') as Card | undefined;\n if (!call) return;\n const split = harness(result.content, data);\n call.output = textOf(split.content);\n if (split.diagnostics.length)\n call.notes = split.diagnostics\n .map(note)\n .sort((a, b) => RANK.indexOf(a.severity) - RANK.indexOf(b.severity));\n call.status = result.isError ? 'error' : 'done';\n const image = Array.isArray(result.content)\n ? (result.content as { type: string; data?: string; mimeType?: string }[]).find(\n (part) => part.type === 'image' && part.data && part.mimeType\n )\n : undefined;\n if (image) call.image = `data:${image.mimeType};base64,${image.data}`;\n const patch = result.details?.patch;\n const diff = typeof patch === 'string' ? fromPatch(patch) : undefined;\n if (diff) call.diff = diff;\n else if (result.isError) delete call.diff;\n}\n\nfunction rewound(id: string, entry: EntryRecord): SystemMessage {\n const data = (entry.data ?? {}) as { stopped?: string[]; restored?: string[]; files?: boolean };\n const notes = [\n 'Its prompt is back in the composer.',\n ...(data.stopped?.length\n ? [`Stopped ${data.stopped.map((name) => `scoop ${name}`).join(', ')}.`]\n : []),\n ...(data.restored?.length\n ? [`Restored ${data.restored.map((name) => `scoop ${name}`).join(', ')}.`]\n : []),\n ...(data.files ? ['Changed files stay; use Changes or git to revert them.'] : []),\n ];\n return {\n id,\n role: 'system',\n kind: 'notice',\n title: 'Rewound 1 turn',\n text: notes.join(' '),\n createdAt: 0,\n };\n}\n\nfunction thawed(id: string, entry: EntryRecord): SystemMessage {\n const data = (entry.data ?? {}) as { name?: string; kind?: string };\n const what = data.kind === 'agent' ? 'agent run' : 'scoop';\n return {\n id,\n role: 'system',\n kind: 'notice',\n title: `Thawed from ${what} ${data.name ?? ''}`.trim(),\n text: textOf(entry.model?.[0]?.content ?? ''),\n createdAt: entry.model?.[0]?.timestamp ?? 0,\n };\n}\n\nfunction secrets(id: string, entry: EntryRecord): SystemMessage {\n const data = (entry.data ?? {}) as { names?: SecretName[] };\n return {\n id,\n role: 'system',\n kind: 'notice',\n title: 'Secrets listed',\n text: listedLine(data.names ?? []),\n createdAt: entry.model?.[0]?.timestamp ?? 0,\n };\n}\n\nfunction entryMessage(\n entry: EntryRecord,\n out: Message[],\n calls: Map<string, ToolCall>,\n delivered: Delivered | undefined,\n notes: { decisions: ReadonlyMap<string, LickDecision>; origins: ReadonlyMap<number, From> }\n): void {\n const id = `e${entry.id}`;\n const model = entry.model?.[0] as ModelMessage | undefined;\n if (entry.kind === 'slicc.rewound') out.push(rewound(id, entry));\n if (entry.kind === 'slicc.thawed') out.push(thawed(id, entry));\n else if (entry.kind === SECRETS_KIND) out.push(secrets(id, entry));\n else if (entry.kind === SPRINKLE_KIND) out.push(sprinkleMessage(id, entry));\n else if (entry.kind === 'pi.user' && model)\n out.push(\n lickMessage(id, entry, notes.decisions) ??\n user(id, model, delivered, notes.origins.get(entry.id))\n );\n else if (entry.kind === 'pi.assistant' && model) {\n const message = assistant(id, model);\n out.push(withoutLickTools(message));\n for (const [key, value] of tools([message])) calls.set(key, value);\n } else if (entry.kind === 'pi.tool-result' && model) settle(calls, model, entry.data);\n else if (entry.kind === 'pi.compaction') out.push(system(id, entry, textOf(model?.content)));\n}\n\nconst slotStatus: Record<string, ToolStatus> = {\n pending: 'running',\n running: 'running',\n done: 'done',\n};\n\nfunction live(view: ConversationView, out: Message[], calls: Map<string, ToolCall>): void {\n const state = view.docs['pi.live'] as Live | undefined;\n for (const slot of state?.tools ?? []) {\n const call = calls.get(slot.callId);\n if (call && call.status === 'running') {\n call.status = slotStatus[slot.status] ?? 'running';\n call.output = slot.output ?? call.output;\n }\n }\n const partial = state?.generation?.message;\n if (partial) out.push(assistant('live', partial, 'streaming'));\n for (const compaction of state?.compactions ?? []) {\n out.push({\n id: `compaction-${compaction.taskId}`,\n role: 'system',\n kind: 'compaction',\n text: '',\n createdAt: 0,\n state: 'summarizing',\n trigger: compaction.reason as SystemMessage['trigger'],\n });\n }\n const retry = state?.generation?.retry;\n if (retry)\n out.push({\n id: 'retry',\n role: 'system',\n kind: 'notice',\n text: retry.error,\n createdAt: retry.at,\n });\n}\n\nexport function toMessages(\n view: ConversationView | undefined,\n deliveries: Readonly<Record<string, Delivered>> = {}\n): Message[] {\n const out: Message[] = [];\n if (!view) return out;\n const calls = new Map<string, ToolCall>();\n const notes = { decisions: lickDecisions(view.entries), origins: origins(view.entries) };\n let previous: EntryRecord | undefined;\n for (const entry of view.entries) {\n const steered = previous?.kind === 'pi.tool-result' ? 'steer' : undefined;\n entryMessage(entry, out, calls, deliveries[String(entry.id)] ?? steered, notes);\n previous = entry;\n }\n live(view, out, calls);\n return out;\n}\n\nfunction shownUser(\n content: ModelMessage['content'],\n prefix?: string\n): Pick<UserMessage, 'text' | 'attachments'> {\n const { text, attachments } = splitUser(content, prefix);\n return attachments.length ? { text, attachments } : { text };\n}\n\nexport function isBusy(view: ConversationView | undefined): boolean {\n return Boolean((view?.docs['pi.live'] as Live | undefined)?.run);\n}\n\nexport function queued(\n view: ConversationView | undefined,\n at: (id: string) => number = () => 0\n): UserMessage[] {\n const items = ((view?.docs['pi.inbox'] as { items?: Json[] } | undefined)?.items ?? []) as {\n id: number;\n mode: string;\n content?: ModelMessage['content'];\n }[];\n return items\n .filter((item) => item.mode !== 'write' && !parseLick(textOf(item.content)))\n .map((item) => ({\n id: `q${item.id}`,\n role: 'user' as const,\n ...shownUser(item.content),\n createdAt: at(`q${item.id}`),\n queued: true,\n mode: item.mode === 'steer' ? 'steer' : 'queue',\n }));\n}\n"],
5
+ "mappings": "AAcA,SAAS,iBAAiB;AAC1B,SAAS,iBAAiB;AAC1B,SAAS,WAAW,YAA+B,qBAAqB;AACxE,SAAS,gBAAgB;AACzB,SAAS,iBAA4B;AAErC,SAAS,YAAY,oBAAoB;AAEzC,SAAS,qBAAqB;AA8CvB,SAAS,OAAO,SAA0C;AAC/D,MAAI,OAAO,YAAY,SAAU,QAAO;AACxC,UAAQ,WAAW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AAC9E,eAAW;AAAA,EACb;AACA,OAAK,MAAM,KAAK,KAAK;AACrB,SAAO;AACT;AAEA,SAAS,UACP,SACA,QAC2C;AAC3C,QAAM,EAAE,MAAM,YAAY,IAAI,UAAU,SAAS,MAAM;AACvD,SAAO,YAAY,SAAS,EAAE,MAAM,YAAY,IAAI,EAAE,KAAK;AAC7D;AAEO,SAAS,OAAO,MAA6C;AAClE,SAAO,QAAS,MAAM,KAAK,SAAS,GAAwB,GAAG;AACjE;AAEO,SAAS,OACd,MACA,KAA6B,MAAM,GACpB;AACf,QAAM,QAAU,MAAM,KAAK,UAAU,GAAsC,SAAS,CAAC;AAKrF,SAAO,MACJ,OAAO,CAAC,SAAS,KAAK,SAAS,WAAW,CAAC,UAAU,OAAO,KAAK,OAAO,CAAC,CAAC,EAC1E,IAAI,CAAC,UAAU;AAAA,IACd,IAAI,IAAI,KAAK,EAAE;AAAA,IACf,MAAM;AAAA,IACN,GAAG,UAAU,KAAK,OAAO;AAAA,IACzB,WAAW,GAAG,IAAI,KAAK,EAAE,EAAE;AAAA,IAC3B,QAAQ;AAAA,IACR,MAAM,KAAK,SAAS,UAAU,UAAU;AAAA,EAC1C,EAAE;AACN;",
6
6
  "names": ["note", "part"]
7
7
  }
@@ -2,6 +2,7 @@ import { BACKGROUND_CONTEXT } from "@earendil-works/chord/context";
2
2
  import { contextRatio } from "../context.js";
3
3
  import { Emitter } from "./emitter.js";
4
4
  const RENEW_MS = 1e4;
5
+ const SAMPLE_MS = 2e3;
5
6
  const ROWS_MAX = 200;
6
7
  const HISTORY = 24;
7
8
  const CPU_HISTORY = 30;
@@ -24,6 +25,13 @@ const CONTEXT_WARN = 0.8;
24
25
  const DEPTH_MAX = 6;
25
26
  const MINUTE = 6e4;
26
27
  const HOUR = 36e5;
28
+ function record(list, value, max) {
29
+ list.push(value);
30
+ if (list.length > max) list.shift();
31
+ }
32
+ function trend(series) {
33
+ return series && series.length > 1 ? { series: [...series] } : {};
34
+ }
27
35
  const KINDS = {
28
36
  "pi.generation": "generating",
29
37
  "pi.compaction": "compacting",
@@ -75,21 +83,29 @@ function cpuVital(feed, history) {
75
83
  label: "CPU",
76
84
  value: `${Math.round(share * 100)}%`,
77
85
  unit: "of one core",
78
- ...history.length > 1 ? { series: history.map((value) => Math.round(value * 100)) } : {}
86
+ ...trend(history.map((value) => Math.round(value * 100)))
79
87
  }
80
88
  ];
81
89
  }
82
- function memoryVital(processes) {
83
- const measured = processes.filter((row) => typeof row.rss === "number");
84
- if (!measured.length) return [];
85
- const total = measured.reduce((sum, row) => sum + row.rss, 0);
90
+ function measuredOf(processes) {
91
+ return processes.filter((row) => typeof row.rss === "number");
92
+ }
93
+ function memoryTotal(processes) {
94
+ const measured = measuredOf(processes);
95
+ return measured.length ? measured.reduce((sum, row) => sum + row.rss, 0) : null;
96
+ }
97
+ function memoryVital(processes, history) {
98
+ const total = memoryTotal(processes);
99
+ if (total === null) return [];
100
+ const measured = measuredOf(processes);
86
101
  const agents = measured.filter((row) => row.agentId).reduce((sum, row) => sum + row.rss, 0);
87
102
  return [
88
103
  {
89
104
  id: "memory",
90
105
  label: "Process memory",
91
106
  value: bytes(total),
92
- unit: `${bytes(agents)} by agents`
107
+ unit: `${bytes(agents)} by agents`,
108
+ ...trend(history)
93
109
  }
94
110
  ];
95
111
  }
@@ -188,17 +204,16 @@ function vitals(input, feed) {
188
204
  value: free ? count(feed.usage.tokens) : money(feed.usage.cost),
189
205
  unit: free ? "tokens" : `${count(feed.usage.tokens)} tokens`,
190
206
  ...perHour === null ? {} : { delta: `${free ? count(perHour) : money(perHour)}/h` },
191
- ...series.length > 1 ? { series } : {}
207
+ ...trend(series)
192
208
  });
193
209
  }
194
210
  const active = feed.agents.filter((agent) => agent.running).length;
195
- const actives = input.history.map((sample) => sample.active);
196
211
  out.push({
197
212
  id: "agents",
198
213
  label: "Active agents",
199
214
  value: String(active),
200
215
  unit: `of ${feed.agents.length}`,
201
- ...actives.length > 1 ? { series: actives } : {}
216
+ ...trend(input.history.map((sample) => sample.active))
202
217
  });
203
218
  const tools = feed.tasks.filter(
204
219
  (task) => task.kind === "pi.tool" && task.status === "running"
@@ -214,10 +229,11 @@ function vitals(input, feed) {
214
229
  id: "processes",
215
230
  label: "Processes",
216
231
  value: String(feed.processes.length),
217
- unit: `${feed.processes.filter((row) => row.agentId).length} by agents`
232
+ unit: `${feed.processes.filter((row) => row.agentId).length} by agents`,
233
+ ...trend(input.processes)
218
234
  } : feed.kernel === "checking" ? { id: "processes", label: "Processes", value: "\u2026", unit: "checking" } : { id: "processes", label: "Processes", value: "\u2014", unit: "kernel not reachable" }
219
235
  );
220
- out.push(...memoryVital(feed.processes ?? []));
236
+ out.push(...memoryVital(feed.processes ?? [], input.memory));
221
237
  out.push(...cpuVital(feed, input.cpu ?? []));
222
238
  const ratios = feed.agents.map((agent) => agentContext(agent, input.models)).filter((ratio) => ratio !== null);
223
239
  if (ratios.length) {
@@ -237,6 +253,9 @@ function stale(process, agents, now) {
237
253
  if (agents.get(process.agentId)?.tool === "bash") return false;
238
254
  return now - process.started > STALE_MS;
239
255
  }
256
+ function zombied(process, now) {
257
+ return process.zombie !== null && now - process.zombie > ZOMBIE_MS;
258
+ }
240
259
  function groups(processes) {
241
260
  const out = /* @__PURE__ */ new Map();
242
261
  for (const process of processes) {
@@ -380,7 +399,7 @@ function processAlerts(input, feed, nameOf) {
380
399
  const agents = new Map(feed.agents.map((agent) => [agent.id, agent]));
381
400
  const out = [...crowdAlerts(processes, nameOf), ...cpuAlerts(input, processes, nameOf)];
382
401
  for (const process of processes) {
383
- if (process.zombie !== null && input.now - process.zombie > ZOMBIE_MS)
402
+ if (zombied(process, input.now))
384
403
  out.push({
385
404
  id: `zombie-${process.pid}`,
386
405
  title: `Process ${process.pid} is a zombie`,
@@ -432,31 +451,6 @@ function alerts(input, feed) {
432
451
  ...contextAlerts(input, feed)
433
452
  ];
434
453
  }
435
- function agentRow(agent, depth, models) {
436
- const ratio = agentContext(agent, models);
437
- const word = agent.retry ? "retrying" : agent.running ? "running" : agent.failed ? "failed" : "idle";
438
- const status = agent.retry ? "warn" : agent.running ? "active" : agent.failed ? "error" : "idle";
439
- const model = models.find((choice) => choice.id === agent.model)?.label ?? agent.model;
440
- const meta = [
441
- word,
442
- model,
443
- ratio === null ? null : `${Math.round(ratio * 100)}% context`,
444
- cpuText(agent.cpu)
445
- ].filter(Boolean).join(" \xB7 ");
446
- const badges = [
447
- ...agent.queued ? [`${agent.queued} queued`] : [],
448
- ...agent.tool ? [agent.tool] : [],
449
- ...agent.retry ? [`retry ${agent.retry.attempt}`] : []
450
- ];
451
- return {
452
- id: agent.id,
453
- name: agent.name,
454
- meta,
455
- status,
456
- depth,
457
- ...badges.length ? { badges } : {}
458
- };
459
- }
460
454
  function taskRow(task, depth, nameOf, now) {
461
455
  const aborting = task.aborting !== null && now - task.aborting > ABORT_ROW_MS;
462
456
  const status = aborting ? "warn" : task.status === "running" || task.status === "completing" ? "active" : "idle";
@@ -474,17 +468,26 @@ function taskRow(task, depth, nameOf, now) {
474
468
  ...badges.length ? { badges } : {}
475
469
  };
476
470
  }
471
+ function drivers(members) {
472
+ const hot = members.filter((row) => (row.cpu ?? 0) >= CPU_SHARE);
473
+ if (hot.length) return hot;
474
+ const top = members.reduce((best, row) => (row.cpu ?? 0) > (best.cpu ?? 0) ? row : best);
475
+ return [top];
476
+ }
477
477
  function processRows(input, feed) {
478
478
  const agents = new Map(feed.agents.map((agent) => [agent.id, agent]));
479
+ const members = groups(feed.processes ?? []);
479
480
  const flagged = /* @__PURE__ */ new Map();
480
- for (const [pgid, members] of groups(feed.processes ?? []))
481
- if (members.length > GROUP_MAX) flagged.set(pgid, crowdSeverity(members));
482
481
  for (const group of busy(input, feed.processes ?? []))
483
- flagged.set(group.pgid, worse(flagged.get(group.pgid), cpuSeverity(group)));
482
+ for (const row of drivers(members.get(group.pgid)))
483
+ flagged.set(row.pid, cpuSeverity(group));
484
484
  return (feed.processes ?? []).map((process) => {
485
485
  const runaway = worse(
486
- flagged.get(process.pgid),
487
- stale(process, agents, input.now) ? staleSeverity(process, input.now) : void 0
486
+ worse(
487
+ flagged.get(process.pid),
488
+ stale(process, agents, input.now) ? staleSeverity(process, input.now) : void 0
489
+ ),
490
+ zombied(process, input.now) ? "warn" : void 0
488
491
  );
489
492
  const badges = [
490
493
  ...process.agentId ? [agents.get(process.agentId)?.name ?? process.agentId] : [],
@@ -500,36 +503,16 @@ function processRows(input, feed) {
500
503
  cpuText(process.cpu),
501
504
  process.started ? age(input.now - process.started) : null
502
505
  ].filter(Boolean).join(" \xB7 "),
503
- status: runaway ?? (process.state === "Z" ? "warn" : "idle"),
506
+ status: runaway ?? "idle",
504
507
  ...badges.length ? { badges } : {}
505
508
  };
506
509
  });
507
510
  }
508
511
  const PROBLEM_KINDS = { task: "task failed", retry: "retry", turn: "turn failed" };
509
- function depthOf(agents, agent) {
510
- const visited = /* @__PURE__ */ new Set();
511
- let depth = 0;
512
- let current = agent;
513
- while (current.parentId && !visited.has(current.id)) {
514
- visited.add(current.id);
515
- const parent = agents.get(current.parentId);
516
- if (!parent) break;
517
- depth++;
518
- current = parent;
519
- }
520
- return depth;
521
- }
522
512
  function sections(input, feed) {
523
513
  const agents = new Map(feed.agents.map((agent) => [agent.id, agent]));
524
514
  const nameOf = (id) => id ? agents.get(id)?.name ?? id : "session";
525
515
  return [
526
- {
527
- id: "agents",
528
- label: "Cones and scoops",
529
- rows: ordered(feed).map(
530
- (agent) => agentRow(agent, Math.min(depthOf(agents, agent), DEPTH_MAX), input.models)
531
- )
532
- },
533
516
  {
534
517
  id: "tasks",
535
518
  label: "Tasks",
@@ -562,15 +545,6 @@ function pageSections(input) {
562
545
  status: "warn"
563
546
  }))
564
547
  },
565
- {
566
- id: "sprinkles",
567
- label: "Sprinkles",
568
- rows: input.sprinkles.map((sprinkle) => ({
569
- name: sprinkle.title,
570
- meta: sprinkle.name,
571
- status: "idle"
572
- }))
573
- },
574
548
  ...input.extra
575
549
  ];
576
550
  }
@@ -600,6 +574,7 @@ class MonitorAdapter {
600
574
  #emitter = new Emitter();
601
575
  #extra;
602
576
  #renewMs;
577
+ #sampleMs;
603
578
  #intervals;
604
579
  #now;
605
580
  #listeners = 0;
@@ -608,16 +583,18 @@ class MonitorAdapter {
608
583
  #hot = /* @__PURE__ */ new Map();
609
584
  #hotAt = -1;
610
585
  #cpu = [];
586
+ #processes = [];
587
+ #memory = [];
611
588
  constructor(connection, options = {}) {
612
589
  this.#connection = connection;
613
590
  this.#extra = options.extra ?? (() => []);
614
591
  this.#renewMs = options.renewMs ?? RENEW_MS;
592
+ this.#sampleMs = options.sampleMs ?? SAMPLE_MS;
615
593
  this.#intervals = options.intervals ?? globalIntervals;
616
594
  this.#now = options.now ?? Date.now;
617
595
  connection.monitor?.subscribe(() => this.#update());
618
596
  connection.settings.state.subscribe(() => this.#update());
619
597
  connection.changes?.subscribe(() => this.#update());
620
- connection.sprinkles?.subscribe(() => this.#update());
621
598
  }
622
599
  on(type, listener) {
623
600
  const off = this.#emitter.on(type, listener);
@@ -639,12 +616,13 @@ class MonitorAdapter {
639
616
  budget: settings?.budget,
640
617
  models: settings?.models ?? [],
641
618
  changes: this.#connection.changes?.value?.changes ?? [],
642
- sprinkles: this.#connection.sprinkles?.value ?? [],
643
619
  extra: this.#extra(),
644
620
  history: this.#history,
645
621
  now: this.#now(),
646
622
  hot: this.#hot,
647
- cpu: this.#cpu
623
+ cpu: this.#cpu,
624
+ processes: this.#processes,
625
+ memory: this.#memory
648
626
  });
649
627
  }
650
628
  resync() {
@@ -660,32 +638,42 @@ class MonitorAdapter {
660
638
  this.#hot = /* @__PURE__ */ new Map();
661
639
  this.#hotAt = -1;
662
640
  this.#cpu = [];
641
+ this.#processes = [];
642
+ this.#memory = [];
663
643
  void control.changesOpen(BACKGROUND_CONTEXT).catch(() => void 0);
664
644
  const lease = control.monitorOpen(null, true, BACKGROUND_CONTEXT).then(
665
645
  (opened) => opened.lease || null,
666
646
  () => null
667
647
  );
668
648
  const renew = () => void lease.then((held) => held ? control.monitorOpen(held, false, BACKGROUND_CONTEXT) : void 0).catch(() => void 0);
669
- this.#open = { lease, timer: this.#intervals.every(renew, this.#renewMs) };
649
+ this.#open = {
650
+ lease,
651
+ timer: this.#intervals.every(renew, this.#renewMs),
652
+ sampler: this.#intervals.every(() => this.#poll(), this.#sampleMs)
653
+ };
670
654
  }
671
655
  #stop() {
672
656
  const open = this.#open;
673
657
  if (!open) return;
674
658
  this.#open = void 0;
675
659
  this.#intervals.stop(open.timer);
660
+ this.#intervals.stop(open.sampler);
676
661
  const control = this.#connection.control;
677
662
  void open.lease.then((held) => held ? control.monitorClose(held, BACKGROUND_CONTEXT) : void 0).catch(() => void 0);
678
663
  }
679
664
  #sample() {
680
665
  const feed = this.#connection.monitor?.value;
681
666
  if (!feed?.open || !feed.usage || this.#history.at(-1)?.at === feed.at) return;
682
- this.#history.push({
683
- at: feed.at,
684
- cost: feed.usage.cost,
685
- tokens: feed.usage.tokens,
686
- active: feed.agents.filter((agent) => agent.running).length
687
- });
688
- if (this.#history.length > HISTORY) this.#history.shift();
667
+ record(
668
+ this.#history,
669
+ {
670
+ at: feed.at,
671
+ cost: feed.usage.cost,
672
+ tokens: feed.usage.tokens,
673
+ active: feed.agents.filter((agent) => agent.running).length
674
+ },
675
+ HISTORY
676
+ );
689
677
  }
690
678
  #track() {
691
679
  const feed = this.#connection.monitor?.value;
@@ -693,9 +681,15 @@ class MonitorAdapter {
693
681
  this.#hotAt = feed.at;
694
682
  this.#hot = hotGroups(feed.processes ?? [], feed.at, this.#hot);
695
683
  const share = agentsCpu(feed);
696
- if (share === null) return;
697
- this.#cpu.push(share);
698
- if (this.#cpu.length > CPU_HISTORY) this.#cpu.shift();
684
+ if (share !== null) record(this.#cpu, share, CPU_HISTORY);
685
+ }
686
+ #poll() {
687
+ const feed = this.#connection.monitor?.value;
688
+ if (!feed?.open || !feed.processes) return;
689
+ record(this.#processes, feed.processes.length, CPU_HISTORY);
690
+ const memory = memoryTotal(feed.processes);
691
+ if (memory !== null) record(this.#memory, memory, CPU_HISTORY);
692
+ this.#emitter.emit("snapshot", this.snapshot());
699
693
  }
700
694
  #update() {
701
695
  if (!this.#listeners) return;
@@ -724,6 +718,7 @@ export {
724
718
  RETRY_SLOW_MS,
725
719
  RETRY_WARN,
726
720
  ROWS_MAX,
721
+ SAMPLE_MS,
727
722
  STALE_MS,
728
723
  TOTAL_MAX,
729
724
  ZOMBIE_MS,
@@ -735,8 +730,10 @@ export {
735
730
  globalIntervals,
736
731
  groupCpu,
737
732
  hotGroups,
733
+ memoryTotal,
738
734
  money,
739
735
  monitorSnapshot,
736
+ record,
740
737
  taskLabel,
741
738
  taskTree
742
739
  };