@xopcai/xopc 0.0.141 → 0.0.142
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/browser-ext/manifest.json +1 -1
- package/dist/extensions/telegram/xopc.extension.json +1 -1
- package/dist/gateway/static/root/assets/{agent-avatar-dicebear-BRTCpm3t.js → agent-avatar-dicebear-BawPxiu5.js} +1 -1
- package/dist/gateway/static/root/assets/agents-CyvCIHnB.js +2 -0
- package/dist/gateway/static/root/assets/{app-management-settings-panel-DaMMZBAT.js → app-management-settings-panel-81xd1p9R.js} +1 -1
- package/dist/gateway/static/root/assets/{appearance-settings-BXHThPyM.js → appearance-settings-DYeQsYU8.js} +1 -1
- package/dist/gateway/static/root/assets/{apps-page-B4omjLxa.js → apps-page-DK_Vx6nl.js} +1 -1
- package/dist/gateway/static/root/assets/{archive-plugin-izB-4N4L.js → archive-plugin-D_oa7oti.js} +1 -1
- package/dist/gateway/static/root/assets/{attachment-load-CJihXa5y.js → attachment-load-Cd-bwI2N.js} +1 -1
- package/dist/gateway/static/root/assets/{automation-suggestion-card-fgtj5Gek.js → automation-suggestion-card-B1LV3YYv.js} +1 -1
- package/dist/gateway/static/root/assets/automations-page-fzrovqhv.js +4 -0
- package/dist/gateway/static/root/assets/{binary-plugins-D3VUeG8s.js → binary-plugins-O8svLKWw.js} +1 -1
- package/dist/gateway/static/root/assets/{block-editor-KnA0sLI3.js → block-editor-Dhj5f4Bx.js} +47 -47
- package/dist/gateway/static/root/assets/browser-settings-page-BDn-n-UB.js +8 -0
- package/dist/gateway/static/root/assets/{capability-presets-api-D8rRNhc6.js → capability-presets-api-dJy1Eqgx.js} +1 -1
- package/dist/gateway/static/root/assets/{capability-presets-settings-panel-sCHojZr4.js → capability-presets-settings-panel-Co5ipo_Q.js} +1 -1
- package/dist/gateway/static/root/assets/{channel-recipient-api-BWgqwC5h.js → channel-recipient-api-Bfuhp2ty.js} +1 -1
- package/dist/gateway/static/root/assets/channels-settings-BWlpaxg9.js +1 -0
- package/dist/gateway/static/root/assets/channels-status-swr-D_jkIZLV.js +1 -0
- package/dist/gateway/static/root/assets/connectors-page-BcekbW4q.js +2 -0
- package/dist/gateway/static/root/assets/{desktop-pet-CzdqX001.js → desktop-pet-DFMfIb5F.js} +1 -1
- package/dist/gateway/static/root/assets/{desktop-pet-settings-DqqUPC7G.js → desktop-pet-settings-BJCUuL8Y.js} +1 -1
- package/dist/gateway/static/root/assets/{directory-picker-path-field-PzlO5tSM.js → directory-picker-path-field-BrYt1gAr.js} +1 -1
- package/dist/gateway/static/root/assets/{dreaming-settings-BmL54kQq.js → dreaming-settings-BN1Z2mIo.js} +3 -3
- package/dist/gateway/static/root/assets/{extension-debug-page-DcW8Ie3r.js → extension-debug-page-Bh630pLD.js} +1 -1
- package/dist/gateway/static/root/assets/{extension-page-DT5cpace.js → extension-page-B-1KxvVy.js} +1 -1
- package/dist/gateway/static/root/assets/{extension-settings-page-CbMk4GhQ.js → extension-settings-page-BF9NACI3.js} +1 -1
- package/dist/gateway/static/root/assets/{fetch-06q5eCMA.js → fetch-B1WtuprY.js} +1 -1
- package/dist/gateway/static/root/assets/{gateway-config-api-4VXUJtLz.js → gateway-config-api-De2N821l.js} +1 -1
- package/dist/gateway/static/root/assets/{gateway-settings-CdghmKHJ.js → gateway-settings-DN9sNREz.js} +1 -1
- package/dist/gateway/static/root/assets/{gateway-startup-retry-2f7_vsv7.js → gateway-startup-retry-nEujFSDj.js} +1 -1
- package/dist/gateway/static/root/assets/goal-create-dialog-BpoQW8cD.js +1 -0
- package/dist/gateway/static/root/assets/goal-detail-page-CBRSPd0b.js +4 -0
- package/dist/gateway/static/root/assets/{goals-config-api-BpuQTufF.js → goals-config-api-DUy3eEse.js} +1 -1
- package/dist/gateway/static/root/assets/goals-page-BCcBi407.js +2 -0
- package/dist/gateway/static/root/assets/{goals-settings-CW1NwxvV.js → goals-settings-pkTXzXkh.js} +1 -1
- package/dist/gateway/static/root/assets/{heartbeat-settings-C86k5tff.js → heartbeat-settings-ezsufgLQ.js} +1 -1
- package/dist/gateway/static/root/assets/{index-ehajXmqL.js → index-DcUaXYeb.js} +65 -65
- package/dist/gateway/static/root/assets/keyboard-shortcuts-settings-CVIwwM15.js +1 -0
- package/dist/gateway/static/root/assets/logs-page-DQtTRXtj.js +7 -0
- package/dist/gateway/static/root/assets/{markdown-split-zS4KLNAf.js → markdown-split-B_6us9j7.js} +1 -1
- package/dist/gateway/static/root/assets/{media-plugins-_BgNJ9_7.js → media-plugins-D_fryIyj.js} +1 -1
- package/dist/gateway/static/root/assets/messages-BXNELNBa.js +3 -0
- package/dist/gateway/static/root/assets/models-hub-panel-BP2M9n6Q.js +2 -0
- package/dist/gateway/static/root/assets/notes-page-CspveYaO.js +1 -0
- package/dist/gateway/static/root/assets/notes-workbench-BHwzJ0OC.js +2 -0
- package/dist/gateway/static/root/assets/{page-tabs-B7sGQkgU.js → page-tabs-D_8jGlqx.js} +1 -1
- package/dist/gateway/static/root/assets/{preview-open-alternatives-D1ri4s_O.js → preview-open-alternatives-BBLMK8Mp.js} +1 -1
- package/dist/gateway/static/root/assets/project-detail-page-Dy3rsobs.js +1 -0
- package/dist/gateway/static/root/assets/projects-page-CWKpPE0L.js +1 -0
- package/dist/gateway/static/root/assets/remote-access-hub-CqNRyXEo.js +1 -0
- package/dist/gateway/static/root/assets/{save-bar-controls-BClrOinh.js → save-bar-controls-DVS3FR5r.js} +1 -1
- package/dist/gateway/static/root/assets/{schedule-field-CL7YTwLV.js → schedule-field-D6vKd6-T.js} +1 -1
- package/dist/gateway/static/root/assets/{schema-form-ww4PiIje.js → schema-form-BPy4lbIh.js} +1 -1
- package/dist/gateway/static/root/assets/sessions-page-MEME7ivF.js +1 -0
- package/dist/gateway/static/root/assets/settings-advanced-gate-JVd0qaSF.js +1 -0
- package/dist/gateway/static/root/assets/{settings-collapsible-section-D9gEEVm2.js → settings-collapsible-section-WzdikxPt.js} +1 -1
- package/dist/gateway/static/root/assets/{settings-form-section-DGeEoBkb.js → settings-form-section-CvfzhBV-.js} +1 -1
- package/dist/gateway/static/root/assets/{settings-loading-skeleton-BXUeMR37.js → settings-loading-skeleton-BxR-Ulhi.js} +1 -1
- package/dist/gateway/static/root/assets/{settings-page-C5G2klUB.js → settings-page-DYEbB1EV.js} +1 -1
- package/dist/gateway/static/root/assets/{settings-page-layout-CEepfbCa.js → settings-page-layout-CKefvbYi.js} +1 -1
- package/dist/gateway/static/root/assets/{setup-status-panel-oQ8OLnw3.js → setup-status-panel-dWN8BJ3z.js} +1 -1
- package/dist/gateway/static/root/assets/{share-preview-page-CXtDHMSi.js → share-preview-page-D8foINzP.js} +1 -1
- package/dist/gateway/static/root/assets/shares-settings-Tgbv1s7G.js +1 -0
- package/dist/gateway/static/root/assets/skill-reload-api-D_YK0b_Z.js +1 -0
- package/dist/gateway/static/root/assets/skills-page-DGytfoZK.js +2 -0
- package/dist/gateway/static/root/assets/{system-settings-panel-W6MBJXrr.js → system-settings-panel-BokgAgf7.js} +1 -1
- package/dist/gateway/static/root/assets/{typed-models-lib-BkODXN7T.js → typed-models-lib-BwHlNL3L.js} +1 -1
- package/dist/gateway/static/root/assets/{use-channel-catalog-CTbwLZXc.js → use-channel-catalog-DR11ap3A.js} +1 -1
- package/dist/gateway/static/root/assets/{user-profile-settings-panel-CeC308-E.js → user-profile-settings-panel-8YtygcJp.js} +1 -1
- package/dist/gateway/static/root/assets/{utils-ZxrKHxyb.js → utils-BKUWB-TT.js} +1 -1
- package/dist/gateway/static/root/assets/voice-api-key-field-BVH71EFf.js +1 -0
- package/dist/gateway/static/root/assets/work-item-detail-page-JeTE7XNM.js +1 -0
- package/dist/gateway/static/root/assets/workflow-run-setup-panel-CL_rnAUB.js +3 -0
- package/dist/gateway/static/root/assets/{workflow-start-dialog-CtLTtNUB.js → workflow-start-dialog-_u8Uc1ze.js} +1 -1
- package/dist/gateway/static/root/assets/workflows-page-ixgk_y1l.js +18 -0
- package/dist/gateway/static/root/index.html +4 -4
- package/dist/package.js +1 -1
- package/dist/src/agent/embedded/session-runner.js +5 -5
- package/dist/src/agent/embedded/session-runner.js.map +1 -1
- package/dist/src/agent/embedded/xopc-auth-storage.d.ts +4 -3
- package/dist/src/agent/embedded/xopc-auth-storage.js +6 -6
- package/dist/src/agent/embedded/xopc-auth-storage.js.map +1 -1
- package/dist/src/agent/embedded/xopc-stream-bridge.js +1 -0
- package/dist/src/agent/embedded/xopc-stream-bridge.js.map +1 -1
- package/dist/src/agent/goals/checklist-judge.js +3 -3
- package/dist/src/agent/goals/checklist-judge.js.map +1 -1
- package/dist/src/agent/goals/judge.js +2 -2
- package/dist/src/agent/goals/judge.js.map +1 -1
- package/dist/src/agent/image/understanding/pi-ai-provider.js +2 -2
- package/dist/src/agent/image/understanding/pi-ai-provider.js.map +1 -1
- package/dist/src/agent/memory/compaction.js +2 -2
- package/dist/src/agent/memory/compaction.js.map +1 -1
- package/dist/src/agent/service/btw-query.d.ts +4 -0
- package/dist/src/agent/service/btw-query.js +94 -13
- package/dist/src/agent/service/btw-query.js.map +1 -1
- package/dist/src/agent/session/session-inspector.js +9 -1
- package/dist/src/agent/session/session-inspector.js.map +1 -1
- package/dist/src/agent/tools/session-search-tool.js +2 -2
- package/dist/src/agent/tools/session-search-tool.js.map +1 -1
- package/dist/src/agent/tools/web-extract.js +2 -2
- package/dist/src/agent/tools/web-extract.js.map +1 -1
- package/dist/src/ai-assist/text-assist.d.ts +2 -1
- package/dist/src/ai-assist/text-assist.js +10 -23
- package/dist/src/ai-assist/text-assist.js.map +1 -1
- package/dist/src/auth/credentials.js +5 -2
- package/dist/src/auth/credentials.js.map +1 -1
- package/dist/src/auth/oauth/github-copilot.d.ts +3 -4
- package/dist/src/auth/oauth/github-copilot.js +66 -2
- package/dist/src/auth/oauth/github-copilot.js.map +1 -0
- package/dist/src/auth/oauth/index.js +2 -2
- package/dist/src/automations/draft/automation-draft-service.js +3 -3
- package/dist/src/automations/draft/automation-draft-service.js.map +1 -1
- package/dist/src/chat-commands/builtins/review.js +22 -5
- package/dist/src/chat-commands/builtins/review.js.map +1 -1
- package/dist/src/chat-commands/types.d.ts +4 -0
- package/dist/src/gateway/hono/routes/models.js +1 -0
- package/dist/src/gateway/hono/routes/models.js.map +1 -1
- package/dist/src/gateway/hono/routes/voice.js +2 -2
- package/dist/src/gateway/hono/routes/voice.js.map +1 -1
- package/dist/src/goals/goal-contract-draft.js +2 -2
- package/dist/src/goals/goal-contract-draft.js.map +1 -1
- package/dist/src/goals/goal-evidence-review.js +2 -2
- package/dist/src/goals/goal-evidence-review.js.map +1 -1
- package/dist/src/notes/service.js +2 -2
- package/dist/src/notes/service.js.map +1 -1
- package/dist/src/providers/constants.d.ts +2 -0
- package/dist/src/providers/constants.js +11 -0
- package/dist/src/providers/constants.js.map +1 -0
- package/dist/src/providers/extension-stream-bridge.js +1 -0
- package/dist/src/providers/extension-stream-bridge.js.map +1 -1
- package/dist/src/providers/index.d.ts +3 -3
- package/dist/src/providers/index.js +5 -4
- package/dist/src/providers/index.js.map +1 -1
- package/dist/src/providers/model-call.d.ts +17 -0
- package/dist/src/providers/model-call.js +60 -0
- package/dist/src/providers/model-call.js.map +1 -0
- package/dist/src/session/session-title.js +2 -2
- package/dist/src/session/session-title.js.map +1 -1
- package/dist/src/voice/tts/summarize.js +2 -2
- package/dist/src/voice/tts/summarize.js.map +1 -1
- package/dist/src/workflows/draft/workflow-draft-service.js +2 -2
- package/dist/src/workflows/draft/workflow-draft-service.js.map +1 -1
- package/package.json +5 -5
- package/dist/gateway/static/root/assets/agents-Bd863Akz.js +0 -2
- package/dist/gateway/static/root/assets/automations-page-Dz2mgjIR.js +0 -4
- package/dist/gateway/static/root/assets/browser-settings-page-DZZz5v_i.js +0 -8
- package/dist/gateway/static/root/assets/channels-settings-UyVSnf9s.js +0 -1
- package/dist/gateway/static/root/assets/channels-status-swr-CB5FzcLf.js +0 -1
- package/dist/gateway/static/root/assets/connectors-page-BzhHiUO4.js +0 -2
- package/dist/gateway/static/root/assets/goal-create-dialog-CAlsM9MP.js +0 -1
- package/dist/gateway/static/root/assets/goal-detail-page-CLPa4F2y.js +0 -4
- package/dist/gateway/static/root/assets/goals-page-B2VpdzfH.js +0 -2
- package/dist/gateway/static/root/assets/keyboard-shortcuts-settings-8xwKEhui.js +0 -1
- package/dist/gateway/static/root/assets/logs-page-C_BMONOO.js +0 -7
- package/dist/gateway/static/root/assets/messages-B-8CqAeX.js +0 -3
- package/dist/gateway/static/root/assets/models-hub-panel-Do_cwNjF.js +0 -2
- package/dist/gateway/static/root/assets/notes-page-5IdlPHaX.js +0 -1
- package/dist/gateway/static/root/assets/notes-workbench-0KsRZJIZ.js +0 -2
- package/dist/gateway/static/root/assets/project-detail-page-Dk2zB1gy.js +0 -1
- package/dist/gateway/static/root/assets/projects-page-CJQntm2G.js +0 -1
- package/dist/gateway/static/root/assets/remote-access-hub-CHeZZg7O.js +0 -1
- package/dist/gateway/static/root/assets/sessions-page-9Hb_r0AG.js +0 -1
- package/dist/gateway/static/root/assets/settings-advanced-gate-PmzVFvAv.js +0 -1
- package/dist/gateway/static/root/assets/shares-settings-BlNoairj.js +0 -1
- package/dist/gateway/static/root/assets/skill-reload-api-BYV5x1KO.js +0 -1
- package/dist/gateway/static/root/assets/skills-page-ClBcKQZP.js +0 -2
- package/dist/gateway/static/root/assets/voice-api-key-field-BE57S-nS.js +0 -1
- package/dist/gateway/static/root/assets/work-item-detail-page-Di1ww5Aa.js +0 -1
- package/dist/gateway/static/root/assets/workflow-run-setup-panel-CzK84i-B.js +0 -3
- package/dist/gateway/static/root/assets/workflows-page-CZFZdua9.js +0 -18
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"service.js","names":[],"sources":["../../../src/notes/service.ts"],"sourcesContent":["import { randomUUID } from 'node:crypto';\n\nimport { complete, type UserMessage } from '@earendil-works/pi-ai/compat';\n\nimport { changedFieldsFromPatch, emitActivity, previewText, systemActivityActor, systemActivitySource } from '../activity/emitter.js';\nimport { publishAutomationProductEvent } from '../automations/product-events.js';\nimport type { Config } from '../config/schema.js';\nimport { getDefaultModelSync, resolveModel } from '../providers/index.js';\nimport { createLogger } from '../utils/logger.js';\nimport { buildNoteAttachmentRef } from './attachment-ref.js';\nimport { partitionAttachmentsByReference } from './note-attachment-sync.js';\nimport { parseNoteMarkdown } from './note-markdown.js';\nimport { buildNoteAgentContextArtifact, getCachedNoteAgentContextArtifact } from './agent-context.js';\nimport { NotesStore } from './store.js';\nimport type {\n CaptureSource,\n CreateNoteParams,\n Note,\n NoteAiPatch,\n NoteAttachment,\n NoteCatalysisAction,\n NoteCatalysisMeta,\n NoteCatalysisReport,\n NoteIndexEntry,\n NoteKind,\n NoteSnapshot,\n NoteSnapshotEntry,\n NotesListQuery,\n SnapshotTrigger,\n} from './types.js';\n\nconst log = createLogger('NotesService');\nconst MAX_SNAPSHOTS_PER_NOTE = 50;\nconst SNAPSHOT_THROTTLE_MS = 60_000;\n\nfunction inferKind(markdown?: string, hasAttachments?: boolean, attachments?: NoteAttachment[]): NoteKind {\n if (hasAttachments && attachments?.length && attachments.every((item) => item.type === 'audio')) return 'voice';\n if (hasAttachments) return 'media';\n if (!markdown) return 'thought';\n const lower = markdown.toLowerCase();\n if (/^(todo|task|remind|buy|call|email|meet|finish|submit|send)\\b/i.test(lower) || /\\b(明天|今天|记得|别忘|待办|提醒)\\b/.test(markdown)) return 'todo';\n if (/^https?:\\/\\//.test(markdown.trim())) return 'bookmark';\n return 'thought';\n}\n\nfunction deriveDefaultTitle(markdown?: string): string | undefined {\n const normalized = parseNoteMarkdown(markdown ?? '').plainText.trim().replace(/\\s+/g, ' ');\n return normalized ? Array.from(normalized).slice(0, 10).join('') : undefined;\n}\n\nfunction splitMeaningfulLines(markdown?: string): string[] {\n return parseNoteMarkdown(markdown ?? '').plainText.split(/\\n|。|;|;/).map((line) => line.trim()).filter(Boolean);\n}\n\nfunction summarizeIdea(markdown?: string): string {\n const lines = splitMeaningfulLines(markdown);\n return lines.slice(0, 3).join(';').slice(0, 140);\n}\n\nfunction publishNoteEvent(\n type: 'note.created' | 'note.updated',\n note: Note,\n extra?: Record<string, unknown>,\n): void {\n publishAutomationProductEvent({\n type,\n source: 'notes',\n payload: {\n noteId: note.id,\n kind: note.kind,\n status: note.status,\n title: note.title,\n capturedVia: note.capturedVia,\n tagCount: note.tags?.length ?? 0,\n hasAttachments: Boolean(note.attachments?.length),\n ...extra,\n },\n });\n}\n\nfunction inferCatalysisStage(note: Note): NonNullable<NoteCatalysisMeta['stage']> {\n const text = `${note.title ?? ''}\\n${note.markdown}`;\n if (/上线|发布|launch|ship/i.test(text)) return 'shipped';\n if (/验证|访谈|用户|测试|validate/i.test(text)) return 'validating';\n if (/开发|实现|构建|build|mvp/i.test(text)) return 'developing';\n if (/想法|机会|问题|idea|seed/i.test(text)) return 'seed';\n return 'incubating';\n}\n\nfunction buildCatalysisReport(note: Note): NoteCatalysisReport {\n const summary = summarizeIdea(note.markdown || note.title);\n const title = note.title?.trim() || summary.slice(0, 28) || '未命名想法';\n const actions: NoteCatalysisAction[] = [\n { kind: 'research', text: `验证「${title}」的真实需求和目标用户` },\n { kind: 'task', text: `拆解「${title}」的最小可行下一步` },\n { kind: 'chat', text: `继续和 AI 讨论「${title}」的方案` },\n ];\n return {\n originalNoteId: note.id,\n generatedAt: Date.now(),\n title,\n valueHypothesis: summary || '这条笔记可能包含一个待澄清的想法。',\n targetUsers: ['待确认的核心用户'],\n keyQuestions: ['用户为什么现在需要它?', '最小可验证版本是什么?', '如何判断它值得继续投入?'],\n mvpPath: ['定义目标用户', '写出最小场景', '完成一次验证'],\n risks: ['需求不够明确', '执行路径过大'],\n nextActions: actions,\n confidence: summary ? 0.58 : 0.35,\n };\n}\n\nfunction normalizeAiCatalysisReport(note: Note, data: Record<string, unknown>): NoteCatalysisReport {\n const fallback = buildCatalysisReport(note);\n const stringArray = (value: unknown, fallbackValue: string[]) => Array.isArray(value) ? value.filter((item): item is string => typeof item === 'string').slice(0, 12) : fallbackValue;\n const actions = Array.isArray(data.nextActions)\n ? data.nextActions.map((item): NoteCatalysisAction | null => {\n if (!item || typeof item !== 'object') return null;\n const row = item as { kind?: unknown; text?: unknown };\n const kind = row.kind === 'task' || row.kind === 'workflow' || row.kind === 'research' || row.kind === 'share' || row.kind === 'chat' ? row.kind : 'task';\n return typeof row.text === 'string' && row.text.trim() ? { kind, text: row.text.trim() } : null;\n }).filter((item): item is NoteCatalysisAction => Boolean(item)).slice(0, 12)\n : fallback.nextActions;\n return {\n originalNoteId: note.id,\n generatedAt: Date.now(),\n title: typeof data.title === 'string' && data.title.trim() ? data.title.trim() : fallback.title,\n valueHypothesis: typeof data.valueHypothesis === 'string' && data.valueHypothesis.trim() ? data.valueHypothesis.trim() : fallback.valueHypothesis,\n targetUsers: stringArray(data.targetUsers, fallback.targetUsers),\n keyQuestions: stringArray(data.keyQuestions, fallback.keyQuestions),\n mvpPath: stringArray(data.mvpPath, fallback.mvpPath),\n risks: stringArray(data.risks, fallback.risks),\n nextActions: actions,\n confidence: typeof data.confidence === 'number' ? Math.max(0, Math.min(1, data.confidence)) : fallback.confidence,\n };\n}\n\nfunction buildCatalysisPrompt(note: Note): string {\n const title = note.title?.trim() || '未命名笔记';\n const markdown = note.markdown.trim() || '(无正文)';\n return `请把下面的 Markdown 笔记催化成可执行的想法报告,输出 JSON:\\n{\\n \"title\": string,\\n \"valueHypothesis\": string,\\n \"targetUsers\": string[],\\n \"keyQuestions\": string[],\\n \"mvpPath\": string[],\\n \"risks\": string[],\\n \"nextActions\": [{\"text\": string, \"kind\": \"task\"|\"workflow\"|\"research\"|\"share\"|\"chat\"}],\\n \"confidence\": number\\n}\\n\\n标题:${title}\\n\\nMarkdown:\\n${markdown}`;\n}\n\nasync function buildAiCatalysisReport(note: Note, config?: Config): Promise<NoteCatalysisReport> {\n const modelRef = getDefaultModelSync(config);\n if (!modelRef) {\n throw new Error('No global default model configured');\n }\n const resolved = resolveModel(modelRef);\n const messages: UserMessage[] = [{ role: 'user', content: buildCatalysisPrompt(note), timestamp: Date.now() }];\n const response = await complete(resolved, { messages }, { temperature: 0.2 });\n let responseText = '';\n if (Array.isArray(response.content)) {\n for (const part of response.content) {\n if (part && typeof part === 'object' && (part as { type?: string }).type === 'text') {\n responseText += String((part as { text?: string }).text || '');\n }\n }\n }\n const raw = responseText.trim().replace(/^```json\\s*/i, '').replace(/```$/i, '').trim();\n return normalizeAiCatalysisReport(note, JSON.parse(raw) as Record<string, unknown>);\n}\n\nexport class NotesService {\n private lastSnapshotAt = new Map<string, number>();\n\n constructor(private readonly store = new NotesStore()) {}\n\n async initialize(): Promise<void> {\n await this.store.initialize();\n }\n\n async quickCapture(markdown: string, source: CaptureSource): Promise<Note> {\n const id = randomUUID();\n const now = Date.now();\n const note: Note = {\n id,\n title: deriveDefaultTitle(markdown),\n kind: inferKind(markdown),\n status: 'inbox',\n markdown,\n createdAt: now,\n updatedAt: now,\n capturedVia: source,\n remoteVersion: 1,\n localVersion: 1,\n };\n await this.store.addNote(note);\n emitActivity({\n type: 'note.created',\n primaryObject: { kind: 'note', id: note.id, title: note.title },\n actor: systemActivityActor(),\n source: systemActivitySource(),\n payload: {\n title: note.title,\n kind: note.kind,\n tags: note.tags,\n contentPreview: previewText(note.markdown),\n contentLength: note.markdown.length,\n },\n nowMs: note.createdAt,\n });\n log.debug({ id: note.id, kind: note.kind }, 'Quick capture');\n return note;\n }\n\n async createNote(params: CreateNoteParams): Promise<Note> {\n const id = randomUUID();\n const now = Date.now();\n const markdown = params.markdown ?? '';\n const note: Note = {\n id,\n title: params.title ?? deriveDefaultTitle(markdown),\n kind: params.kind ?? inferKind(markdown),\n status: 'inbox',\n markdown,\n attachments: [],\n createdAt: now,\n updatedAt: now,\n capturedVia: params.capturedVia,\n tags: params.tags,\n pinned: params.pinned,\n groupId: params.groupId,\n taskMeta: params.taskMeta,\n remoteVersion: 1,\n localVersion: 1,\n };\n await this.store.addNote(note);\n emitActivity({\n type: 'note.created',\n primaryObject: { kind: 'note', id: note.id, title: note.title },\n actor: systemActivityActor(),\n source: systemActivitySource(),\n payload: {\n title: note.title,\n kind: note.kind,\n tags: note.tags,\n contentPreview: previewText(note.markdown),\n contentLength: note.markdown.length,\n },\n nowMs: note.createdAt,\n });\n publishNoteEvent('note.created', note);\n log.debug({ id: note.id, kind: note.kind }, 'Note created');\n return note;\n }\n\n async getNote(id: string): Promise<Note | null> {\n return this.store.getNote(id);\n }\n\n async updateNote(id: string, patch: Partial<Note>, trigger: SnapshotTrigger = 'edit'): Promise<Note | null> {\n const existing = await this.store.getNote(id);\n if (!existing) return null;\n const contentTouched = patch.markdown !== undefined || patch.title !== undefined;\n if (contentTouched) await this.maybeSaveSnapshot(existing, trigger);\n\n const normalizedPatch: Partial<Note> = { ...patch };\n if (patch.markdown !== undefined) {\n normalizedPatch.kind = patch.kind ?? inferKind(patch.markdown, Boolean(existing.attachments?.length), existing.attachments);\n }\n if (contentTouched || patch.attachments) {\n normalizedPatch.remoteVersion = (existing.remoteVersion ?? 1) + 1;\n normalizedPatch.localVersion = patch.localVersion ?? (existing.localVersion ?? 1) + 1;\n }\n\n const updatedRaw = await this.store.updateNote(id, normalizedPatch);\n const updated = updatedRaw ? await this.reconcileAttachments(updatedRaw) : null;\n if (updated) {\n const changes = changedFieldsFromPatch(patch as Record<string, unknown>);\n emitActivity({\n type: existing.status !== updated.status ? 'note.status_changed' : 'note.updated',\n primaryObject: { kind: 'note', id: updated.id, title: updated.title },\n actor: systemActivityActor(),\n source: systemActivitySource(),\n payload: {\n changes,\n contentTouched,\n ...(existing.status !== updated.status ? { from: existing.status, to: updated.status } : {}),\n },\n nowMs: updated.updatedAt,\n });\n publishNoteEvent('note.updated', updated, {\n contentTouched,\n trigger,\n });\n }\n return updated;\n }\n\n private async reconcileAttachments(note: Note): Promise<Note> {\n const { kept, removed } = partitionAttachmentsByReference(note);\n if (removed.length === 0) return note;\n for (const attachment of removed) await this.store.deleteAttachmentFile(note.id, attachment.relativePath);\n log.debug({ noteId: note.id, removedIds: removed.map((attachment) => attachment.id) }, 'Pruned orphan note attachments');\n const hasAttachments = kept.length > 0;\n const updated = await this.store.updateNote(note.id, { attachments: kept, kind: inferKind(note.markdown, hasAttachments, kept) });\n return updated ?? { ...note, attachments: kept };\n }\n\n async syncNote(id: string, patch: Partial<Note>, baseRemoteVersion?: number): Promise<{ note: Note | null; conflict: boolean }> {\n const existing = await this.store.getNote(id);\n if (!existing) return { note: null, conflict: false };\n if (baseRemoteVersion !== undefined && existing.remoteVersion !== undefined && baseRemoteVersion < existing.remoteVersion) {\n return { note: existing, conflict: true };\n }\n const updated = await this.updateNote(id, patch, 'sync');\n return { note: updated, conflict: false };\n }\n\n async createAiEditPatch(id: string, instruction: string, markdownOverride?: string): Promise<{ message: string; patch: NoteAiPatch } | null> {\n const note = await this.store.getNote(id);\n if (!note) return null;\n const source = markdownOverride ?? note.markdown;\n const parsed = parseNoteMarkdown(source, id);\n const wantsTodos = /待办|todo|task|行动|提醒/i.test(instruction);\n const wantsSummary = /摘要|总结|summary|压缩/i.test(instruction);\n let generated = '';\n if (wantsTodos) {\n const lines = source.split(/\\n|。|;|;/).map((line) => line.trim()).filter(Boolean);\n generated = (lines.length ? lines : [parsed.plainText]).slice(0, 12).map((line) => `- [ ] ${line.replace(/^[-*\\d.\\s\\[\\]x]+/i, '').trim()}`).join('\\n');\n } else if (wantsSummary) {\n generated = `> [!SUMMARY]\\n> ${parsed.plainText.slice(0, 220)}`;\n } else {\n generated = `${source.trimEnd()}\\n\\n## AI 整理\\n\\n${instruction.trim()}`;\n }\n return {\n message: 'AI edit patch generated',\n patch: {\n id: randomUUID(),\n summary: instruction,\n operations: [{ type: 'replaceRange', from: 0, to: source.length, markdown: generated || source }],\n },\n };\n }\n\n async catalyzeNote(id: string, config?: Config): Promise<{ note: Note; report: NoteCatalysisReport } | null> {\n const note = await this.store.getNote(id);\n if (!note) return null;\n let report: NoteCatalysisReport;\n try {\n report = await buildAiCatalysisReport(note, config);\n } catch (err) {\n log.warn({ err, noteId: id }, 'AI note catalysis failed; using local fallback report');\n report = buildCatalysisReport(note);\n }\n const updated = await this.updateNote(id, {\n aiDeep: {\n ...note.aiDeep,\n processedAt: Date.now(),\n catalysis: {\n status: 'catalyzed',\n stage: inferCatalysisStage(note),\n lastCatalyzedAt: Date.now(),\n confidence: report.confidence,\n report,\n ...note.aiDeep?.catalysis,\n },\n },\n ai: { ...note.ai, intent: note.ai?.intent ?? 'idea', summary: note.ai?.summary ?? report.valueHypothesis },\n status: note.status === 'inbox' ? 'processed' : note.status,\n }, 'ai_edit');\n return updated ? { note: updated, report } : null;\n }\n\n async recordCatalysisFeedback(id: string, feedback: 'helpful' | 'not_helpful' | 'neutral'): Promise<Note | null> {\n const note = await this.store.getNote(id);\n if (!note) return null;\n return this.updateNote(id, { aiDeep: { ...note.aiDeep, processedAt: Date.now(), catalysis: { status: note.aiDeep?.catalysis?.status ?? 'catalyzed', ...note.aiDeep?.catalysis, feedback } } });\n }\n\n async linkNoteThread(id: string, sessionKey: string): Promise<Note | null> {\n const note = await this.store.getNote(id);\n if (!note) return null;\n const existingKeys = note.aiDeep?.catalysis?.linkedSessionKeys ?? [];\n return this.updateNote(id, {\n aiDeep: {\n ...note.aiDeep,\n processedAt: Date.now(),\n catalysis: {\n status: note.aiDeep?.catalysis?.status ?? 'none',\n ...note.aiDeep?.catalysis,\n sourceSessionKey: note.aiDeep?.catalysis?.sourceSessionKey ?? sessionKey,\n linkedSessionKeys: Array.from(new Set([...existingKeys, sessionKey])),\n },\n },\n }, 'sync');\n }\n\n async listNoteThreads(id: string): Promise<string[] | null> {\n const note = await this.store.getNote(id);\n if (!note) return null;\n return Array.from(new Set([note.aiDeep?.catalysis?.sourceSessionKey, ...(note.aiDeep?.catalysis?.linkedSessionKeys ?? [])].filter((key): key is string => Boolean(key))));\n }\n\n async getAgentContextStatus(id: string, config?: Config, force = false): Promise<{ noteUpdatedAt: number; artifact: import('./agent-context.js').NoteAgentContextArtifact | null; stale: boolean } | null> {\n const note = await this.store.getNote(id);\n if (!note) return null;\n const cached = getCachedNoteAgentContextArtifact(id);\n if (!force && cached && cached.noteUpdatedAt === note.updatedAt) {\n return { noteUpdatedAt: note.updatedAt, artifact: cached, stale: false };\n }\n const artifact = await buildNoteAgentContextArtifact({ note, notesService: this, config, force });\n return { noteUpdatedAt: note.updatedAt, artifact, stale: false };\n }\n\n async appendTextToNote(id: string, content: string, heading = 'AI 讨论沉淀'): Promise<Note | null> {\n const note = await this.store.getNote(id);\n if (!note) return null;\n const trimmed = content.trim();\n if (!trimmed) return note;\n const current = note.markdown.trimEnd();\n const nextMarkdown = `${current}${current ? '\\n\\n' : ''}## ${heading}\\n\\n${trimmed}\\n`;\n return this.updateNote(id, { markdown: nextMarkdown }, 'ai_edit');\n }\n\n async deleteNote(id: string): Promise<boolean> {\n const removed = await this.store.deleteNote(id);\n if (removed) await this.store.deleteAllSnapshots(id);\n return removed;\n }\n\n async listNotes(query: NotesListQuery = {}): Promise<{ items: NoteIndexEntry[]; total: number; limit: number; offset: number; hasMore: boolean }> {\n return this.store.listNotes(query);\n }\n\n async addAttachment(noteId: string, file: { name: string; buffer: Buffer; mimeType: string; duration?: number }): Promise<NoteAttachment | null> {\n const note = await this.store.getNote(noteId);\n if (!note) return null;\n const { relativePath, size } = await this.store.saveAttachment(noteId, file.name, file.buffer);\n const attachment: NoteAttachment = {\n id: randomUUID(),\n type: file.mimeType.startsWith('image/') ? 'image' : file.mimeType.startsWith('audio/') ? 'audio' : file.mimeType.startsWith('video/') ? 'video' : 'file',\n mimeType: file.mimeType,\n fileName: file.name,\n size,\n relativePath,\n duration: file.duration,\n };\n const attachments = [...(note.attachments || []), attachment];\n const kind = note.kind === 'thought' && attachment.type === 'audio' ? 'voice' : note.kind === 'thought' ? 'media' : note.kind;\n await this.store.updateNote(noteId, { attachments, kind });\n return attachment;\n }\n\n async getAttachmentPath(noteId: string, attachmentId: string): Promise<{ filePath: string; mimeType: string; fileName: string } | null> {\n const note = await this.store.getNote(noteId);\n if (!note) return null;\n const attachment = note.attachments?.find((a) => a.id === attachmentId);\n if (!attachment) return null;\n return { filePath: this.store.resolveAttachmentPath(noteId, attachment.relativePath), mimeType: attachment.mimeType, fileName: attachment.fileName };\n }\n\n async listNoteHistory(noteId: string): Promise<NoteSnapshotEntry[]> { return this.store.listSnapshots(noteId); }\n async getNoteSnapshot(noteId: string, timestamp: number): Promise<NoteSnapshot | null> { return this.store.getSnapshot(noteId, timestamp); }\n\n async restoreNoteSnapshot(noteId: string, timestamp: number): Promise<Note | null> {\n const snapshot = await this.store.getSnapshot(noteId, timestamp);\n const existing = await this.store.getNote(noteId);\n if (!snapshot || !existing) return null;\n await this.maybeSaveSnapshot(existing, 'restore');\n this.lastSnapshotAt.set(noteId, Date.now());\n await this.store.pruneSnapshots(noteId, MAX_SNAPSHOTS_PER_NOTE);\n return this.store.updateNote(noteId, { title: snapshot.title, markdown: snapshot.markdown, tags: snapshot.tags, kind: snapshot.kind, status: snapshot.status });\n }\n\n async flush(): Promise<void> { await this.store.flush(); }\n async moveToGroup(noteId: string, groupId: string | null): Promise<Note | null> { return this.updateNote(noteId, { groupId: groupId ?? undefined }); }\n\n async createTask(title: string, source: CaptureSource, opts: { dueAt?: number; priority?: 'high' | 'medium' | 'low'; sourceSessionKey?: string; sourceNoteId?: string; groupId?: string } = {}): Promise<Note> {\n return this.createNote({\n title,\n markdown: `- [ ] ${title}`,\n kind: 'task',\n capturedVia: source,\n groupId: opts.groupId,\n taskMeta: { done: false, dueAt: opts.dueAt, priority: opts.priority, sourceSessionKey: opts.sourceSessionKey, sourceNoteId: opts.sourceNoteId },\n });\n }\n\n async toggleTaskDone(noteId: string): Promise<Note | null> {\n const note = await this.store.getNote(noteId);\n if (!note || note.kind !== 'task') return null;\n const done = !note.taskMeta?.done;\n const markdown = note.markdown.replace(/^- \\[[ xX]\\]/m, `- [${done ? 'x' : ' '}]`);\n return this.updateNote(noteId, { markdown, taskMeta: { ...note.taskMeta, done } });\n }\n\n async updateTaskMeta(noteId: string, patch: Partial<import('./types.js').NoteTaskMeta>): Promise<Note | null> {\n const note = await this.store.getNote(noteId);\n if (!note || note.kind !== 'task') return null;\n return this.updateNote(noteId, { taskMeta: { ...note.taskMeta, done: note.taskMeta?.done ?? false, ...patch } });\n }\n\n async recordOpen(noteId: string): Promise<Note | null> {\n return this.updateNote(noteId, { lastOpenedAt: Date.now() } as Partial<Note>);\n }\n\n private async maybeSaveSnapshot(note: Note, trigger: SnapshotTrigger): Promise<void> {\n if (trigger !== 'edit') {\n await this.store.saveSnapshot(note, trigger);\n this.lastSnapshotAt.set(note.id, Date.now());\n await this.store.pruneSnapshots(note.id, MAX_SNAPSHOTS_PER_NOTE);\n return;\n }\n const last = this.lastSnapshotAt.get(note.id) ?? 0;\n if (Date.now() - last < SNAPSHOT_THROTTLE_MS) return;\n await this.store.saveSnapshot(note, trigger);\n this.lastSnapshotAt.set(note.id, Date.now());\n await this.store.pruneSnapshots(note.id, MAX_SNAPSHOTS_PER_NOTE);\n }\n}\n\nexport { buildNoteAttachmentRef };\n"],"mappings":";;;;;;;;;;;;;gBAO0E;aACxB;AAuBlD,MAAM,MAAM,aAAa,eAAe;AACxC,MAAM,yBAAyB;AAC/B,MAAM,uBAAuB;AAE7B,SAAS,UAAU,UAAmB,gBAA0B,aAA0C;AACxG,KAAI,kBAAkB,aAAa,UAAU,YAAY,OAAO,SAAS,KAAK,SAAS,QAAQ,CAAE,QAAO;AACxG,KAAI,eAAgB,QAAO;AAC3B,KAAI,CAAC,SAAU,QAAO;CACtB,MAAM,QAAQ,SAAS,aAAa;AACpC,KAAI,gEAAgE,KAAK,MAAM,IAAI,0BAA0B,KAAK,SAAS,CAAE,QAAO;AACpI,KAAI,eAAe,KAAK,SAAS,MAAM,CAAC,CAAE,QAAO;AACjD,QAAO;;AAGT,SAAS,mBAAmB,UAAuC;CACjE,MAAM,aAAa,kBAAkB,YAAY,GAAG,CAAC,UAAU,MAAM,CAAC,QAAQ,QAAQ,IAAI;AAC1F,QAAO,aAAa,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AO,KAAK,eAAe,IAAI,KAAK,GAAG,IAAI;AACjD,MAAI,KAAK,KAAK,GAAG,OAAO,qBAAsB;AAC9C,QAAM,KAAK,MAAM,aAAa,MAAM,QAAQ;AAC5C,OAAK,eAAe,IAAI,KAAK,IAAI,KAAK,KAAK,CAAC;AAC5C,QAAM,KAAK,MAAM,eAAe,KAAK,IAAI,uBAAuB"}
|
|
1
|
+
{"version":3,"file":"service.js","names":[],"sources":["../../../src/notes/service.ts"],"sourcesContent":["import { randomUUID } from 'node:crypto';\n\nimport { type UserMessage } from '@earendil-works/pi-ai/compat';\n\nimport { changedFieldsFromPatch, emitActivity, previewText, systemActivityActor, systemActivitySource } from '../activity/emitter.js';\nimport { publishAutomationProductEvent } from '../automations/product-events.js';\nimport type { Config } from '../config/schema.js';\nimport { getDefaultModelSync, resolveModel } from '../providers/index.js';\nimport { completeWithResolvedCredentials } from '../providers/model-call.js';\nimport { createLogger } from '../utils/logger.js';\nimport { buildNoteAttachmentRef } from './attachment-ref.js';\nimport { partitionAttachmentsByReference } from './note-attachment-sync.js';\nimport { parseNoteMarkdown } from './note-markdown.js';\nimport { buildNoteAgentContextArtifact, getCachedNoteAgentContextArtifact } from './agent-context.js';\nimport { NotesStore } from './store.js';\nimport type {\n CaptureSource,\n CreateNoteParams,\n Note,\n NoteAiPatch,\n NoteAttachment,\n NoteCatalysisAction,\n NoteCatalysisMeta,\n NoteCatalysisReport,\n NoteIndexEntry,\n NoteKind,\n NoteSnapshot,\n NoteSnapshotEntry,\n NotesListQuery,\n SnapshotTrigger,\n} from './types.js';\n\nconst log = createLogger('NotesService');\nconst MAX_SNAPSHOTS_PER_NOTE = 50;\nconst SNAPSHOT_THROTTLE_MS = 60_000;\n\nfunction inferKind(markdown?: string, hasAttachments?: boolean, attachments?: NoteAttachment[]): NoteKind {\n if (hasAttachments && attachments?.length && attachments.every((item) => item.type === 'audio')) return 'voice';\n if (hasAttachments) return 'media';\n if (!markdown) return 'thought';\n const lower = markdown.toLowerCase();\n if (/^(todo|task|remind|buy|call|email|meet|finish|submit|send)\\b/i.test(lower) || /\\b(明天|今天|记得|别忘|待办|提醒)\\b/.test(markdown)) return 'todo';\n if (/^https?:\\/\\//.test(markdown.trim())) return 'bookmark';\n return 'thought';\n}\n\nfunction deriveDefaultTitle(markdown?: string): string | undefined {\n const normalized = parseNoteMarkdown(markdown ?? '').plainText.trim().replace(/\\s+/g, ' ');\n return normalized ? Array.from(normalized).slice(0, 10).join('') : undefined;\n}\n\nfunction splitMeaningfulLines(markdown?: string): string[] {\n return parseNoteMarkdown(markdown ?? '').plainText.split(/\\n|。|;|;/).map((line) => line.trim()).filter(Boolean);\n}\n\nfunction summarizeIdea(markdown?: string): string {\n const lines = splitMeaningfulLines(markdown);\n return lines.slice(0, 3).join(';').slice(0, 140);\n}\n\nfunction publishNoteEvent(\n type: 'note.created' | 'note.updated',\n note: Note,\n extra?: Record<string, unknown>,\n): void {\n publishAutomationProductEvent({\n type,\n source: 'notes',\n payload: {\n noteId: note.id,\n kind: note.kind,\n status: note.status,\n title: note.title,\n capturedVia: note.capturedVia,\n tagCount: note.tags?.length ?? 0,\n hasAttachments: Boolean(note.attachments?.length),\n ...extra,\n },\n });\n}\n\nfunction inferCatalysisStage(note: Note): NonNullable<NoteCatalysisMeta['stage']> {\n const text = `${note.title ?? ''}\\n${note.markdown}`;\n if (/上线|发布|launch|ship/i.test(text)) return 'shipped';\n if (/验证|访谈|用户|测试|validate/i.test(text)) return 'validating';\n if (/开发|实现|构建|build|mvp/i.test(text)) return 'developing';\n if (/想法|机会|问题|idea|seed/i.test(text)) return 'seed';\n return 'incubating';\n}\n\nfunction buildCatalysisReport(note: Note): NoteCatalysisReport {\n const summary = summarizeIdea(note.markdown || note.title);\n const title = note.title?.trim() || summary.slice(0, 28) || '未命名想法';\n const actions: NoteCatalysisAction[] = [\n { kind: 'research', text: `验证「${title}」的真实需求和目标用户` },\n { kind: 'task', text: `拆解「${title}」的最小可行下一步` },\n { kind: 'chat', text: `继续和 AI 讨论「${title}」的方案` },\n ];\n return {\n originalNoteId: note.id,\n generatedAt: Date.now(),\n title,\n valueHypothesis: summary || '这条笔记可能包含一个待澄清的想法。',\n targetUsers: ['待确认的核心用户'],\n keyQuestions: ['用户为什么现在需要它?', '最小可验证版本是什么?', '如何判断它值得继续投入?'],\n mvpPath: ['定义目标用户', '写出最小场景', '完成一次验证'],\n risks: ['需求不够明确', '执行路径过大'],\n nextActions: actions,\n confidence: summary ? 0.58 : 0.35,\n };\n}\n\nfunction normalizeAiCatalysisReport(note: Note, data: Record<string, unknown>): NoteCatalysisReport {\n const fallback = buildCatalysisReport(note);\n const stringArray = (value: unknown, fallbackValue: string[]) => Array.isArray(value) ? value.filter((item): item is string => typeof item === 'string').slice(0, 12) : fallbackValue;\n const actions = Array.isArray(data.nextActions)\n ? data.nextActions.map((item): NoteCatalysisAction | null => {\n if (!item || typeof item !== 'object') return null;\n const row = item as { kind?: unknown; text?: unknown };\n const kind = row.kind === 'task' || row.kind === 'workflow' || row.kind === 'research' || row.kind === 'share' || row.kind === 'chat' ? row.kind : 'task';\n return typeof row.text === 'string' && row.text.trim() ? { kind, text: row.text.trim() } : null;\n }).filter((item): item is NoteCatalysisAction => Boolean(item)).slice(0, 12)\n : fallback.nextActions;\n return {\n originalNoteId: note.id,\n generatedAt: Date.now(),\n title: typeof data.title === 'string' && data.title.trim() ? data.title.trim() : fallback.title,\n valueHypothesis: typeof data.valueHypothesis === 'string' && data.valueHypothesis.trim() ? data.valueHypothesis.trim() : fallback.valueHypothesis,\n targetUsers: stringArray(data.targetUsers, fallback.targetUsers),\n keyQuestions: stringArray(data.keyQuestions, fallback.keyQuestions),\n mvpPath: stringArray(data.mvpPath, fallback.mvpPath),\n risks: stringArray(data.risks, fallback.risks),\n nextActions: actions,\n confidence: typeof data.confidence === 'number' ? Math.max(0, Math.min(1, data.confidence)) : fallback.confidence,\n };\n}\n\nfunction buildCatalysisPrompt(note: Note): string {\n const title = note.title?.trim() || '未命名笔记';\n const markdown = note.markdown.trim() || '(无正文)';\n return `请把下面的 Markdown 笔记催化成可执行的想法报告,输出 JSON:\\n{\\n \"title\": string,\\n \"valueHypothesis\": string,\\n \"targetUsers\": string[],\\n \"keyQuestions\": string[],\\n \"mvpPath\": string[],\\n \"risks\": string[],\\n \"nextActions\": [{\"text\": string, \"kind\": \"task\"|\"workflow\"|\"research\"|\"share\"|\"chat\"}],\\n \"confidence\": number\\n}\\n\\n标题:${title}\\n\\nMarkdown:\\n${markdown}`;\n}\n\nasync function buildAiCatalysisReport(note: Note, config?: Config): Promise<NoteCatalysisReport> {\n const modelRef = getDefaultModelSync(config);\n if (!modelRef) {\n throw new Error('No global default model configured');\n }\n const resolved = resolveModel(modelRef);\n const messages: UserMessage[] = [{ role: 'user', content: buildCatalysisPrompt(note), timestamp: Date.now() }];\n const response = await completeWithResolvedCredentials(resolved, { messages }, { temperature: 0.2 });\n let responseText = '';\n if (Array.isArray(response.content)) {\n for (const part of response.content) {\n if (part && typeof part === 'object' && (part as { type?: string }).type === 'text') {\n responseText += String((part as { text?: string }).text || '');\n }\n }\n }\n const raw = responseText.trim().replace(/^```json\\s*/i, '').replace(/```$/i, '').trim();\n return normalizeAiCatalysisReport(note, JSON.parse(raw) as Record<string, unknown>);\n}\n\nexport class NotesService {\n private lastSnapshotAt = new Map<string, number>();\n\n constructor(private readonly store = new NotesStore()) {}\n\n async initialize(): Promise<void> {\n await this.store.initialize();\n }\n\n async quickCapture(markdown: string, source: CaptureSource): Promise<Note> {\n const id = randomUUID();\n const now = Date.now();\n const note: Note = {\n id,\n title: deriveDefaultTitle(markdown),\n kind: inferKind(markdown),\n status: 'inbox',\n markdown,\n createdAt: now,\n updatedAt: now,\n capturedVia: source,\n remoteVersion: 1,\n localVersion: 1,\n };\n await this.store.addNote(note);\n emitActivity({\n type: 'note.created',\n primaryObject: { kind: 'note', id: note.id, title: note.title },\n actor: systemActivityActor(),\n source: systemActivitySource(),\n payload: {\n title: note.title,\n kind: note.kind,\n tags: note.tags,\n contentPreview: previewText(note.markdown),\n contentLength: note.markdown.length,\n },\n nowMs: note.createdAt,\n });\n log.debug({ id: note.id, kind: note.kind }, 'Quick capture');\n return note;\n }\n\n async createNote(params: CreateNoteParams): Promise<Note> {\n const id = randomUUID();\n const now = Date.now();\n const markdown = params.markdown ?? '';\n const note: Note = {\n id,\n title: params.title ?? deriveDefaultTitle(markdown),\n kind: params.kind ?? inferKind(markdown),\n status: 'inbox',\n markdown,\n attachments: [],\n createdAt: now,\n updatedAt: now,\n capturedVia: params.capturedVia,\n tags: params.tags,\n pinned: params.pinned,\n groupId: params.groupId,\n taskMeta: params.taskMeta,\n remoteVersion: 1,\n localVersion: 1,\n };\n await this.store.addNote(note);\n emitActivity({\n type: 'note.created',\n primaryObject: { kind: 'note', id: note.id, title: note.title },\n actor: systemActivityActor(),\n source: systemActivitySource(),\n payload: {\n title: note.title,\n kind: note.kind,\n tags: note.tags,\n contentPreview: previewText(note.markdown),\n contentLength: note.markdown.length,\n },\n nowMs: note.createdAt,\n });\n publishNoteEvent('note.created', note);\n log.debug({ id: note.id, kind: note.kind }, 'Note created');\n return note;\n }\n\n async getNote(id: string): Promise<Note | null> {\n return this.store.getNote(id);\n }\n\n async updateNote(id: string, patch: Partial<Note>, trigger: SnapshotTrigger = 'edit'): Promise<Note | null> {\n const existing = await this.store.getNote(id);\n if (!existing) return null;\n const contentTouched = patch.markdown !== undefined || patch.title !== undefined;\n if (contentTouched) await this.maybeSaveSnapshot(existing, trigger);\n\n const normalizedPatch: Partial<Note> = { ...patch };\n if (patch.markdown !== undefined) {\n normalizedPatch.kind = patch.kind ?? inferKind(patch.markdown, Boolean(existing.attachments?.length), existing.attachments);\n }\n if (contentTouched || patch.attachments) {\n normalizedPatch.remoteVersion = (existing.remoteVersion ?? 1) + 1;\n normalizedPatch.localVersion = patch.localVersion ?? (existing.localVersion ?? 1) + 1;\n }\n\n const updatedRaw = await this.store.updateNote(id, normalizedPatch);\n const updated = updatedRaw ? await this.reconcileAttachments(updatedRaw) : null;\n if (updated) {\n const changes = changedFieldsFromPatch(patch as Record<string, unknown>);\n emitActivity({\n type: existing.status !== updated.status ? 'note.status_changed' : 'note.updated',\n primaryObject: { kind: 'note', id: updated.id, title: updated.title },\n actor: systemActivityActor(),\n source: systemActivitySource(),\n payload: {\n changes,\n contentTouched,\n ...(existing.status !== updated.status ? { from: existing.status, to: updated.status } : {}),\n },\n nowMs: updated.updatedAt,\n });\n publishNoteEvent('note.updated', updated, {\n contentTouched,\n trigger,\n });\n }\n return updated;\n }\n\n private async reconcileAttachments(note: Note): Promise<Note> {\n const { kept, removed } = partitionAttachmentsByReference(note);\n if (removed.length === 0) return note;\n for (const attachment of removed) await this.store.deleteAttachmentFile(note.id, attachment.relativePath);\n log.debug({ noteId: note.id, removedIds: removed.map((attachment) => attachment.id) }, 'Pruned orphan note attachments');\n const hasAttachments = kept.length > 0;\n const updated = await this.store.updateNote(note.id, { attachments: kept, kind: inferKind(note.markdown, hasAttachments, kept) });\n return updated ?? { ...note, attachments: kept };\n }\n\n async syncNote(id: string, patch: Partial<Note>, baseRemoteVersion?: number): Promise<{ note: Note | null; conflict: boolean }> {\n const existing = await this.store.getNote(id);\n if (!existing) return { note: null, conflict: false };\n if (baseRemoteVersion !== undefined && existing.remoteVersion !== undefined && baseRemoteVersion < existing.remoteVersion) {\n return { note: existing, conflict: true };\n }\n const updated = await this.updateNote(id, patch, 'sync');\n return { note: updated, conflict: false };\n }\n\n async createAiEditPatch(id: string, instruction: string, markdownOverride?: string): Promise<{ message: string; patch: NoteAiPatch } | null> {\n const note = await this.store.getNote(id);\n if (!note) return null;\n const source = markdownOverride ?? note.markdown;\n const parsed = parseNoteMarkdown(source, id);\n const wantsTodos = /待办|todo|task|行动|提醒/i.test(instruction);\n const wantsSummary = /摘要|总结|summary|压缩/i.test(instruction);\n let generated = '';\n if (wantsTodos) {\n const lines = source.split(/\\n|。|;|;/).map((line) => line.trim()).filter(Boolean);\n generated = (lines.length ? lines : [parsed.plainText]).slice(0, 12).map((line) => `- [ ] ${line.replace(/^[-*\\d.\\s\\[\\]x]+/i, '').trim()}`).join('\\n');\n } else if (wantsSummary) {\n generated = `> [!SUMMARY]\\n> ${parsed.plainText.slice(0, 220)}`;\n } else {\n generated = `${source.trimEnd()}\\n\\n## AI 整理\\n\\n${instruction.trim()}`;\n }\n return {\n message: 'AI edit patch generated',\n patch: {\n id: randomUUID(),\n summary: instruction,\n operations: [{ type: 'replaceRange', from: 0, to: source.length, markdown: generated || source }],\n },\n };\n }\n\n async catalyzeNote(id: string, config?: Config): Promise<{ note: Note; report: NoteCatalysisReport } | null> {\n const note = await this.store.getNote(id);\n if (!note) return null;\n let report: NoteCatalysisReport;\n try {\n report = await buildAiCatalysisReport(note, config);\n } catch (err) {\n log.warn({ err, noteId: id }, 'AI note catalysis failed; using local fallback report');\n report = buildCatalysisReport(note);\n }\n const updated = await this.updateNote(id, {\n aiDeep: {\n ...note.aiDeep,\n processedAt: Date.now(),\n catalysis: {\n status: 'catalyzed',\n stage: inferCatalysisStage(note),\n lastCatalyzedAt: Date.now(),\n confidence: report.confidence,\n report,\n ...note.aiDeep?.catalysis,\n },\n },\n ai: { ...note.ai, intent: note.ai?.intent ?? 'idea', summary: note.ai?.summary ?? report.valueHypothesis },\n status: note.status === 'inbox' ? 'processed' : note.status,\n }, 'ai_edit');\n return updated ? { note: updated, report } : null;\n }\n\n async recordCatalysisFeedback(id: string, feedback: 'helpful' | 'not_helpful' | 'neutral'): Promise<Note | null> {\n const note = await this.store.getNote(id);\n if (!note) return null;\n return this.updateNote(id, { aiDeep: { ...note.aiDeep, processedAt: Date.now(), catalysis: { status: note.aiDeep?.catalysis?.status ?? 'catalyzed', ...note.aiDeep?.catalysis, feedback } } });\n }\n\n async linkNoteThread(id: string, sessionKey: string): Promise<Note | null> {\n const note = await this.store.getNote(id);\n if (!note) return null;\n const existingKeys = note.aiDeep?.catalysis?.linkedSessionKeys ?? [];\n return this.updateNote(id, {\n aiDeep: {\n ...note.aiDeep,\n processedAt: Date.now(),\n catalysis: {\n status: note.aiDeep?.catalysis?.status ?? 'none',\n ...note.aiDeep?.catalysis,\n sourceSessionKey: note.aiDeep?.catalysis?.sourceSessionKey ?? sessionKey,\n linkedSessionKeys: Array.from(new Set([...existingKeys, sessionKey])),\n },\n },\n }, 'sync');\n }\n\n async listNoteThreads(id: string): Promise<string[] | null> {\n const note = await this.store.getNote(id);\n if (!note) return null;\n return Array.from(new Set([note.aiDeep?.catalysis?.sourceSessionKey, ...(note.aiDeep?.catalysis?.linkedSessionKeys ?? [])].filter((key): key is string => Boolean(key))));\n }\n\n async getAgentContextStatus(id: string, config?: Config, force = false): Promise<{ noteUpdatedAt: number; artifact: import('./agent-context.js').NoteAgentContextArtifact | null; stale: boolean } | null> {\n const note = await this.store.getNote(id);\n if (!note) return null;\n const cached = getCachedNoteAgentContextArtifact(id);\n if (!force && cached && cached.noteUpdatedAt === note.updatedAt) {\n return { noteUpdatedAt: note.updatedAt, artifact: cached, stale: false };\n }\n const artifact = await buildNoteAgentContextArtifact({ note, notesService: this, config, force });\n return { noteUpdatedAt: note.updatedAt, artifact, stale: false };\n }\n\n async appendTextToNote(id: string, content: string, heading = 'AI 讨论沉淀'): Promise<Note | null> {\n const note = await this.store.getNote(id);\n if (!note) return null;\n const trimmed = content.trim();\n if (!trimmed) return note;\n const current = note.markdown.trimEnd();\n const nextMarkdown = `${current}${current ? '\\n\\n' : ''}## ${heading}\\n\\n${trimmed}\\n`;\n return this.updateNote(id, { markdown: nextMarkdown }, 'ai_edit');\n }\n\n async deleteNote(id: string): Promise<boolean> {\n const removed = await this.store.deleteNote(id);\n if (removed) await this.store.deleteAllSnapshots(id);\n return removed;\n }\n\n async listNotes(query: NotesListQuery = {}): Promise<{ items: NoteIndexEntry[]; total: number; limit: number; offset: number; hasMore: boolean }> {\n return this.store.listNotes(query);\n }\n\n async addAttachment(noteId: string, file: { name: string; buffer: Buffer; mimeType: string; duration?: number }): Promise<NoteAttachment | null> {\n const note = await this.store.getNote(noteId);\n if (!note) return null;\n const { relativePath, size } = await this.store.saveAttachment(noteId, file.name, file.buffer);\n const attachment: NoteAttachment = {\n id: randomUUID(),\n type: file.mimeType.startsWith('image/') ? 'image' : file.mimeType.startsWith('audio/') ? 'audio' : file.mimeType.startsWith('video/') ? 'video' : 'file',\n mimeType: file.mimeType,\n fileName: file.name,\n size,\n relativePath,\n duration: file.duration,\n };\n const attachments = [...(note.attachments || []), attachment];\n const kind = note.kind === 'thought' && attachment.type === 'audio' ? 'voice' : note.kind === 'thought' ? 'media' : note.kind;\n await this.store.updateNote(noteId, { attachments, kind });\n return attachment;\n }\n\n async getAttachmentPath(noteId: string, attachmentId: string): Promise<{ filePath: string; mimeType: string; fileName: string } | null> {\n const note = await this.store.getNote(noteId);\n if (!note) return null;\n const attachment = note.attachments?.find((a) => a.id === attachmentId);\n if (!attachment) return null;\n return { filePath: this.store.resolveAttachmentPath(noteId, attachment.relativePath), mimeType: attachment.mimeType, fileName: attachment.fileName };\n }\n\n async listNoteHistory(noteId: string): Promise<NoteSnapshotEntry[]> { return this.store.listSnapshots(noteId); }\n async getNoteSnapshot(noteId: string, timestamp: number): Promise<NoteSnapshot | null> { return this.store.getSnapshot(noteId, timestamp); }\n\n async restoreNoteSnapshot(noteId: string, timestamp: number): Promise<Note | null> {\n const snapshot = await this.store.getSnapshot(noteId, timestamp);\n const existing = await this.store.getNote(noteId);\n if (!snapshot || !existing) return null;\n await this.maybeSaveSnapshot(existing, 'restore');\n this.lastSnapshotAt.set(noteId, Date.now());\n await this.store.pruneSnapshots(noteId, MAX_SNAPSHOTS_PER_NOTE);\n return this.store.updateNote(noteId, { title: snapshot.title, markdown: snapshot.markdown, tags: snapshot.tags, kind: snapshot.kind, status: snapshot.status });\n }\n\n async flush(): Promise<void> { await this.store.flush(); }\n async moveToGroup(noteId: string, groupId: string | null): Promise<Note | null> { return this.updateNote(noteId, { groupId: groupId ?? undefined }); }\n\n async createTask(title: string, source: CaptureSource, opts: { dueAt?: number; priority?: 'high' | 'medium' | 'low'; sourceSessionKey?: string; sourceNoteId?: string; groupId?: string } = {}): Promise<Note> {\n return this.createNote({\n title,\n markdown: `- [ ] ${title}`,\n kind: 'task',\n capturedVia: source,\n groupId: opts.groupId,\n taskMeta: { done: false, dueAt: opts.dueAt, priority: opts.priority, sourceSessionKey: opts.sourceSessionKey, sourceNoteId: opts.sourceNoteId },\n });\n }\n\n async toggleTaskDone(noteId: string): Promise<Note | null> {\n const note = await this.store.getNote(noteId);\n if (!note || note.kind !== 'task') return null;\n const done = !note.taskMeta?.done;\n const markdown = note.markdown.replace(/^- \\[[ xX]\\]/m, `- [${done ? 'x' : ' '}]`);\n return this.updateNote(noteId, { markdown, taskMeta: { ...note.taskMeta, done } });\n }\n\n async updateTaskMeta(noteId: string, patch: Partial<import('./types.js').NoteTaskMeta>): Promise<Note | null> {\n const note = await this.store.getNote(noteId);\n if (!note || note.kind !== 'task') return null;\n return this.updateNote(noteId, { taskMeta: { ...note.taskMeta, done: note.taskMeta?.done ?? false, ...patch } });\n }\n\n async recordOpen(noteId: string): Promise<Note | null> {\n return this.updateNote(noteId, { lastOpenedAt: Date.now() } as Partial<Note>);\n }\n\n private async maybeSaveSnapshot(note: Note, trigger: SnapshotTrigger): Promise<void> {\n if (trigger !== 'edit') {\n await this.store.saveSnapshot(note, trigger);\n this.lastSnapshotAt.set(note.id, Date.now());\n await this.store.pruneSnapshots(note.id, MAX_SNAPSHOTS_PER_NOTE);\n return;\n }\n const last = this.lastSnapshotAt.get(note.id) ?? 0;\n if (Date.now() - last < SNAPSHOT_THROTTLE_MS) return;\n await this.store.saveSnapshot(note, trigger);\n this.lastSnapshotAt.set(note.id, Date.now());\n await this.store.pruneSnapshots(note.id, MAX_SNAPSHOTS_PER_NOTE);\n }\n}\n\nexport { buildNoteAttachmentRef };\n"],"mappings":";;;;;;;;;;;;;gBAO0E;aAExB;AAuBlD,MAAM,MAAM,aAAa,eAAe;AACxC,MAAM,yBAAyB;AA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7C,MAAI,CAAC,QAAQ,KAAK,SAAS,OAAQ,QAAO;AAC1C,SAAO,KAAK,WAAW,QAAQ,EAAE,UAAU;GAAE,GAAG,KAAK;GAAU,MAAM,KAAK,UAAU,QAAQ;GAAO,GAAG;GAAO,EAAE,CAAC;;CAGlH,MAAM,WAAW,QAAsC;AACrD,SAAO,KAAK,WAAW,QAAQ,EAAE,cAAc,KAAK,KAAK,EAAE,CAAkB;;CAG/E,MAAc,kBAAkB,MAAY,SAAyC;AACnF,MAAI,YAAY,QAAQ;AACtB,SAAM,KAAK,MAAM,aAAa,MAAM,QAAQ;AAC5C,QAAK,eAAe,IAAI,KAAK,IAAI,KAAK,KAAK,CAAC;AAC5C,SAAM,KAAK,MAAM,eAAe,KAAK,IAAI,uBAAuB;AAChE;;EAEF,MAAM,OAAO,KAAK,eAAe,IAAI,KAAK,GAAG,IAAI;AACjD,MAAI,KAAK,KAAK,GAAG,OAAO,qBAAsB;AAC9C,QAAM,KAAK,MAAM,aAAa,MAAM,QAAQ;AAC5C,OAAK,eAAe,IAAI,KAAK,IAAI,KAAK,KAAK,CAAC;AAC5C,QAAM,KAAK,MAAM,eAAe,KAAK,IAAI,uBAAuB"}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import { __esmMin } from "../../_virtual/_rolldown/runtime.js";
|
|
2
|
+
//#region src/providers/constants.ts
|
|
3
|
+
var EXTENSION_PROVIDER_BASE_URL;
|
|
4
|
+
var init_constants = __esmMin((() => {
|
|
5
|
+
EXTENSION_PROVIDER_BASE_URL = "extension://provider-plugin";
|
|
6
|
+
}));
|
|
7
|
+
//#endregion
|
|
8
|
+
init_constants();
|
|
9
|
+
export { EXTENSION_PROVIDER_BASE_URL, init_constants };
|
|
10
|
+
|
|
11
|
+
//# sourceMappingURL=constants.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"constants.js","names":[],"sources":["../../../src/providers/constants.ts"],"sourcesContent":["/** Sentinel base URL: model is served by an extension {@link ProviderPluginRegistry} provider. */\nexport const EXTENSION_PROVIDER_BASE_URL = 'extension://provider-plugin';\n"],"mappings":";;;;AACa,+BAA8B"}
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { createLogger } from "../utils/logger/index.js";
|
|
2
2
|
import { init_logger } from "../utils/logger.js";
|
|
3
|
+
import "./constants.js";
|
|
3
4
|
import { getProviderRegistry, init_plugin_registry } from "./plugin-registry.js";
|
|
4
5
|
import { init_providers } from "./index.js";
|
|
5
6
|
import { createAssistantMessageEventStream, streamSimple } from "@earendil-works/pi-ai/compat";
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"extension-stream-bridge.js","names":[],"sources":["../../../src/providers/extension-stream-bridge.ts"],"sourcesContent":["import {\n\tstreamSimple,\n\tcreateAssistantMessageEventStream,\n\ttype AssistantMessage,\n\ttype Model,\n\ttype Api,\n\ttype Context,\n\ttype SimpleStreamOptions,\n} from '@earendil-works/pi-ai/compat';\nimport type { StreamFn } from '@earendil-works/pi-agent-core';\nimport type { ProviderStreamParams } from '../extensions/types/providers.js';\nimport { getProviderRegistry } from './plugin-registry.js';\nimport { EXTENSION_PROVIDER_BASE_URL } from './index.js';\nimport { createLogger } from '../utils/logger.js';\n\nconst log = createLogger('ExtensionStreamBridge');\n\nfunction createPartialMessage(model: Model<Api>): AssistantMessage {\n\treturn {\n\t\trole: 'assistant',\n\t\tcontent: [],\n\t\tapi: model.api,\n\t\tprovider: model.provider,\n\t\tmodel: model.id,\n\t\tusage: {\n\t\t\tinput: 0,\n\t\t\toutput: 0,\n\t\t\tcacheRead: 0,\n\t\t\tcacheWrite: 0,\n\t\t\ttotalTokens: 0,\n\t\t\tcost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },\n\t\t},\n\t\tstopReason: 'stop',\n\t\ttimestamp: Date.now(),\n\t};\n}\n\nfunction parseToolArguments(raw: string | undefined): Record<string, unknown> {\n\tif (!raw?.trim()) return {};\n\ttry {\n\t\treturn JSON.parse(raw) as Record<string, unknown>;\n\t} catch {\n\t\treturn {};\n\t}\n}\n\nfunction collectExtraStreamOptions(options?: SimpleStreamOptions): Record<string, unknown> | undefined {\n\tif (!options) return undefined;\n\tconst knownOptionKeys = new Set([\n\t\t'temperature',\n\t\t'maxTokens',\n\t\t'signal',\n\t\t'apiKey',\n\t\t'transport',\n\t\t'cacheRetention',\n\t\t'sessionId',\n\t\t'onPayload',\n\t\t'onResponse',\n\t\t'headers',\n\t\t'timeoutMs',\n\t\t'maxRetries',\n\t\t'maxRetryDelayMs',\n\t\t'metadata',\n\t\t'reasoning',\n\t\t'thinkingBudgets',\n\t]);\n\tconst entries = Object.entries(options as Record<string, unknown>).filter(([key, value]) => {\n\t\treturn !knownOptionKeys.has(key) && value !== undefined;\n\t});\n\treturn entries.length > 0 ? Object.fromEntries(entries) : undefined;\n}\n\n/** Wraps {@link streamSimple} so extension-registered models use the plugin `createStream()` path. */\nexport function createExtensionAwareStreamFn(): StreamFn {\n\treturn ((model: Model<Api>, context: Context, options?: SimpleStreamOptions) => {\n\t\tif (model.baseUrl !== EXTENSION_PROVIDER_BASE_URL) {\n\t\t\treturn streamSimple(model, context, options);\n\t\t}\n\n\t\tconst plugin = getProviderRegistry().get(model.provider);\n\t\tif (!plugin) {\n\t\t\treturn streamSimple(model, context, options);\n\t\t}\n\n\t\tlog.info({ provider: model.provider, modelId: model.id }, 'Streaming via extension provider');\n\n\t\tconst stream = createAssistantMessageEventStream();\n\n\t\tconst params: ProviderStreamParams = {\n\t\t\tmodel: model.id,\n\t\t\tsystemPrompt: context.systemPrompt,\n\t\t\tmessages: context.messages as unknown as ProviderStreamParams['messages'],\n\t\t\ttools: context.tools as unknown as ProviderStreamParams['tools'],\n\t\t\ttemperature: options?.temperature,\n\t\t\tmaxTokens: options?.maxTokens,\n\t\t\tapiKey: options?.apiKey,\n\t\t\tsessionId: options?.sessionId,\n\t\t\treasoning: options?.reasoning,\n\t\t\theaders: options?.headers,\n\t\t\ttimeoutMs: options?.timeoutMs,\n\t\t\tmaxRetries: options?.maxRetries,\n\t\t\tmetadata: options?.metadata,\n\t\t\tcacheRetention: options?.cacheRetention,\n\t\t\ttransport: options?.transport,\n\t\t\tthinkingBudgets: options?.thinkingBudgets,\n\t\t\textra: collectExtraStreamOptions(options),\n\t\t\tsignal: options?.signal,\n\t\t};\n\n\t\tvoid (async () => {\n\t\t\tconst partial = createPartialMessage(model);\n\t\t\tlet textContentIndex = -1;\n\t\t\tlet hasStarted = false;\n\n\t\t\ttry {\n\t\t\t\tfor await (const chunk of plugin.createStream(params)) {\n\t\t\t\t\tif (options?.signal?.aborted) {\n\t\t\t\t\t\tpartial.stopReason = 'aborted';\n\t\t\t\t\t\tpartial.errorMessage = 'Request aborted';\n\t\t\t\t\t\tstream.push({ type: 'error', reason: 'aborted', error: partial });\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\n\t\t\t\t\tswitch (chunk.type) {\n\t\t\t\t\t\tcase 'text': {\n\t\t\t\t\t\t\tif (!hasStarted) {\n\t\t\t\t\t\t\t\thasStarted = true;\n\t\t\t\t\t\t\t\tstream.push({ type: 'start', partial });\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif (textContentIndex === -1) {\n\t\t\t\t\t\t\t\ttextContentIndex = partial.content.length;\n\t\t\t\t\t\t\t\tpartial.content.push({ type: 'text', text: '' });\n\t\t\t\t\t\t\t\tstream.push({ type: 'text_start', contentIndex: textContentIndex, partial });\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tconst textContent = partial.content[textContentIndex];\n\t\t\t\t\t\t\tif (textContent?.type === 'text' && chunk.text) {\n\t\t\t\t\t\t\t\ttextContent.text += chunk.text;\n\t\t\t\t\t\t\t\tstream.push({\n\t\t\t\t\t\t\t\t\ttype: 'text_delta',\n\t\t\t\t\t\t\t\t\tcontentIndex: textContentIndex,\n\t\t\t\t\t\t\t\t\tdelta: chunk.text,\n\t\t\t\t\t\t\t\t\tpartial,\n\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tcase 'tool_call': {\n\t\t\t\t\t\t\tif (!hasStarted) {\n\t\t\t\t\t\t\t\thasStarted = true;\n\t\t\t\t\t\t\t\tstream.push({ type: 'start', partial });\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif (textContentIndex !== -1) {\n\t\t\t\t\t\t\t\tconst tc = partial.content[textContentIndex];\n\t\t\t\t\t\t\t\tif (tc?.type === 'text') {\n\t\t\t\t\t\t\t\t\tstream.push({\n\t\t\t\t\t\t\t\t\t\ttype: 'text_end',\n\t\t\t\t\t\t\t\t\t\tcontentIndex: textContentIndex,\n\t\t\t\t\t\t\t\t\t\tcontent: tc.text,\n\t\t\t\t\t\t\t\t\t\tpartial,\n\t\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\ttextContentIndex = -1;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif (chunk.toolCall) {\n\t\t\t\t\t\t\t\tconst idx = partial.content.length;\n\t\t\t\t\t\t\t\tconst toolCall = {\n\t\t\t\t\t\t\t\t\ttype: 'toolCall' as const,\n\t\t\t\t\t\t\t\t\tid: chunk.toolCall.id,\n\t\t\t\t\t\t\t\t\tname: chunk.toolCall.name,\n\t\t\t\t\t\t\t\t\targuments: parseToolArguments(chunk.toolCall.arguments),\n\t\t\t\t\t\t\t\t};\n\t\t\t\t\t\t\t\tpartial.content.push(toolCall);\n\t\t\t\t\t\t\t\tstream.push({ type: 'toolcall_start', contentIndex: idx, partial });\n\t\t\t\t\t\t\t\tstream.push({\n\t\t\t\t\t\t\t\t\ttype: 'toolcall_delta',\n\t\t\t\t\t\t\t\t\tcontentIndex: idx,\n\t\t\t\t\t\t\t\t\tdelta: chunk.toolCall.arguments || '{}',\n\t\t\t\t\t\t\t\t\tpartial,\n\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\tstream.push({ type: 'toolcall_end', contentIndex: idx, toolCall, partial });\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tcase 'usage': {\n\t\t\t\t\t\t\tif (chunk.usage) {\n\t\t\t\t\t\t\t\tconst inputCost = (chunk.usage.input / 1_000_000) * (model.cost?.input ?? 0);\n\t\t\t\t\t\t\t\tconst outputCost = (chunk.usage.output / 1_000_000) * (model.cost?.output ?? 0);\n\t\t\t\t\t\t\t\tpartial.usage = {\n\t\t\t\t\t\t\t\t\tinput: chunk.usage.input,\n\t\t\t\t\t\t\t\t\toutput: chunk.usage.output,\n\t\t\t\t\t\t\t\t\tcacheRead: 0,\n\t\t\t\t\t\t\t\t\tcacheWrite: 0,\n\t\t\t\t\t\t\t\t\ttotalTokens: chunk.usage.total ?? chunk.usage.input + chunk.usage.output,\n\t\t\t\t\t\t\t\t\tcost: {\n\t\t\t\t\t\t\t\t\t\tinput: inputCost,\n\t\t\t\t\t\t\t\t\t\toutput: outputCost,\n\t\t\t\t\t\t\t\t\t\tcacheRead: 0,\n\t\t\t\t\t\t\t\t\t\tcacheWrite: 0,\n\t\t\t\t\t\t\t\t\t\ttotal: inputCost + outputCost,\n\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t};\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tcase 'error': {\n\t\t\t\t\t\t\tif (!hasStarted) {\n\t\t\t\t\t\t\t\thasStarted = true;\n\t\t\t\t\t\t\t\tstream.push({ type: 'start', partial });\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tpartial.stopReason = 'error';\n\t\t\t\t\t\t\tpartial.errorMessage = chunk.error ?? 'Unknown extension provider error';\n\t\t\t\t\t\t\tstream.push({ type: 'error', reason: 'error', error: partial });\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tcase 'done':\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif (textContentIndex !== -1) {\n\t\t\t\t\tconst tc = partial.content[textContentIndex];\n\t\t\t\t\tif (tc?.type === 'text') {\n\t\t\t\t\t\tstream.push({\n\t\t\t\t\t\t\ttype: 'text_end',\n\t\t\t\t\t\t\tcontentIndex: textContentIndex,\n\t\t\t\t\t\t\tcontent: tc.text,\n\t\t\t\t\t\t\tpartial,\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (!hasStarted) {\n\t\t\t\t\thasStarted = true;\n\t\t\t\t\tstream.push({ type: 'start', partial });\n\t\t\t\t}\n\n\t\t\t\tconst hasToolCalls = partial.content.some(c => c.type === 'toolCall');\n\t\t\t\tconst stopReason = hasToolCalls ? 'toolUse' : 'stop';\n\t\t\t\tpartial.stopReason = stopReason;\n\t\t\t\tstream.push({ type: 'done', reason: stopReason, message: partial });\n\t\t\t} catch (err) {\n\t\t\t\tif (!hasStarted) stream.push({ type: 'start', partial });\n\t\t\t\tpartial.stopReason = 'error';\n\t\t\t\tpartial.errorMessage = err instanceof Error ? err.message : String(err);\n\t\t\t\tstream.push({ type: 'error', reason: 'error', error: partial });\n\t\t\t}\n\t\t})();\n\n\t\treturn stream;\n\t}) as StreamFn;\n}\n"],"mappings":";;;;;;sBAW2D;gBACF;aACP;AAElD,MAAM,MAAM,aAAa,wBAAwB;AAEjD,SAAS,qBAAqB,OAAqC;AAClE,QAAO;EACN,MAAM;EACN,SAAS,EAAE;EACX,KAAK,MAAM;EACX,UAAU,MAAM;EAChB,OAAO,MAAM;EACb,OAAO;GACN,OAAO;GACP,QAAQ;GACR,WAAW;GACX,YAAY;GACZ,aAAa;GACb,MAAM;IAAE,OAAO;IAAG,QAAQ;IAAG,WAAW;IAAG,YAAY;IAAG,OAAO;IAAG;GACpE;EACD,YAAY;EACZ,WAAW,KAAK,KAAK;EACrB;;AAGF,SAAS,mBAAmB,KAA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WAAO,KAAK;KAAE,MAAM;KAAQ,QAAQ;KAAY,SAAS;KAAS,CAAC;YAC3D,KAAK;AACb,QAAI,CAAC,WAAY,QAAO,KAAK;KAAE,MAAM;KAAS;KAAS,CAAC;AACxD,YAAQ,aAAa;AACrB,YAAQ,eAAe,eAAe,QAAQ,IAAI,UAAU,OAAO,IAAI;AACvE,WAAO,KAAK;KAAE,MAAM;KAAS,QAAQ;KAAS,OAAO;KAAS,CAAC;;MAE7D;AAEJ,SAAO"}
|
|
1
|
+
{"version":3,"file":"extension-stream-bridge.js","names":[],"sources":["../../../src/providers/extension-stream-bridge.ts"],"sourcesContent":["import {\n\tstreamSimple,\n\tcreateAssistantMessageEventStream,\n\ttype AssistantMessage,\n\ttype Model,\n\ttype Api,\n\ttype Context,\n\ttype SimpleStreamOptions,\n} from '@earendil-works/pi-ai/compat';\nimport type { StreamFn } from '@earendil-works/pi-agent-core';\nimport type { ProviderStreamParams } from '../extensions/types/providers.js';\nimport { getProviderRegistry } from './plugin-registry.js';\nimport { EXTENSION_PROVIDER_BASE_URL } from './index.js';\nimport { createLogger } from '../utils/logger.js';\n\nconst log = createLogger('ExtensionStreamBridge');\n\nfunction createPartialMessage(model: Model<Api>): AssistantMessage {\n\treturn {\n\t\trole: 'assistant',\n\t\tcontent: [],\n\t\tapi: model.api,\n\t\tprovider: model.provider,\n\t\tmodel: model.id,\n\t\tusage: {\n\t\t\tinput: 0,\n\t\t\toutput: 0,\n\t\t\tcacheRead: 0,\n\t\t\tcacheWrite: 0,\n\t\t\ttotalTokens: 0,\n\t\t\tcost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },\n\t\t},\n\t\tstopReason: 'stop',\n\t\ttimestamp: Date.now(),\n\t};\n}\n\nfunction parseToolArguments(raw: string | undefined): Record<string, unknown> {\n\tif (!raw?.trim()) return {};\n\ttry {\n\t\treturn JSON.parse(raw) as Record<string, unknown>;\n\t} catch {\n\t\treturn {};\n\t}\n}\n\nfunction collectExtraStreamOptions(options?: SimpleStreamOptions): Record<string, unknown> | undefined {\n\tif (!options) return undefined;\n\tconst knownOptionKeys = new Set([\n\t\t'temperature',\n\t\t'maxTokens',\n\t\t'signal',\n\t\t'apiKey',\n\t\t'transport',\n\t\t'cacheRetention',\n\t\t'sessionId',\n\t\t'onPayload',\n\t\t'onResponse',\n\t\t'headers',\n\t\t'timeoutMs',\n\t\t'maxRetries',\n\t\t'maxRetryDelayMs',\n\t\t'metadata',\n\t\t'reasoning',\n\t\t'thinkingBudgets',\n\t]);\n\tconst entries = Object.entries(options as Record<string, unknown>).filter(([key, value]) => {\n\t\treturn !knownOptionKeys.has(key) && value !== undefined;\n\t});\n\treturn entries.length > 0 ? Object.fromEntries(entries) : undefined;\n}\n\n/** Wraps {@link streamSimple} so extension-registered models use the plugin `createStream()` path. */\nexport function createExtensionAwareStreamFn(): StreamFn {\n\treturn ((model: Model<Api>, context: Context, options?: SimpleStreamOptions) => {\n\t\tif (model.baseUrl !== EXTENSION_PROVIDER_BASE_URL) {\n\t\t\treturn streamSimple(model, context, options);\n\t\t}\n\n\t\tconst plugin = getProviderRegistry().get(model.provider);\n\t\tif (!plugin) {\n\t\t\treturn streamSimple(model, context, options);\n\t\t}\n\n\t\tlog.info({ provider: model.provider, modelId: model.id }, 'Streaming via extension provider');\n\n\t\tconst stream = createAssistantMessageEventStream();\n\n\t\tconst params: ProviderStreamParams = {\n\t\t\tmodel: model.id,\n\t\t\tsystemPrompt: context.systemPrompt,\n\t\t\tmessages: context.messages as unknown as ProviderStreamParams['messages'],\n\t\t\ttools: context.tools as unknown as ProviderStreamParams['tools'],\n\t\t\ttemperature: options?.temperature,\n\t\t\tmaxTokens: options?.maxTokens,\n\t\t\tapiKey: options?.apiKey,\n\t\t\tsessionId: options?.sessionId,\n\t\t\treasoning: options?.reasoning,\n\t\t\theaders: options?.headers,\n\t\t\ttimeoutMs: options?.timeoutMs,\n\t\t\tmaxRetries: options?.maxRetries,\n\t\t\tmetadata: options?.metadata,\n\t\t\tcacheRetention: options?.cacheRetention,\n\t\t\ttransport: options?.transport,\n\t\t\tthinkingBudgets: options?.thinkingBudgets,\n\t\t\textra: collectExtraStreamOptions(options),\n\t\t\tsignal: options?.signal,\n\t\t};\n\n\t\tvoid (async () => {\n\t\t\tconst partial = createPartialMessage(model);\n\t\t\tlet textContentIndex = -1;\n\t\t\tlet hasStarted = false;\n\n\t\t\ttry {\n\t\t\t\tfor await (const chunk of plugin.createStream(params)) {\n\t\t\t\t\tif (options?.signal?.aborted) {\n\t\t\t\t\t\tpartial.stopReason = 'aborted';\n\t\t\t\t\t\tpartial.errorMessage = 'Request aborted';\n\t\t\t\t\t\tstream.push({ type: 'error', reason: 'aborted', error: partial });\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\n\t\t\t\t\tswitch (chunk.type) {\n\t\t\t\t\t\tcase 'text': {\n\t\t\t\t\t\t\tif (!hasStarted) {\n\t\t\t\t\t\t\t\thasStarted = true;\n\t\t\t\t\t\t\t\tstream.push({ type: 'start', partial });\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif (textContentIndex === -1) {\n\t\t\t\t\t\t\t\ttextContentIndex = partial.content.length;\n\t\t\t\t\t\t\t\tpartial.content.push({ type: 'text', text: '' });\n\t\t\t\t\t\t\t\tstream.push({ type: 'text_start', contentIndex: textContentIndex, partial });\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tconst textContent = partial.content[textContentIndex];\n\t\t\t\t\t\t\tif (textContent?.type === 'text' && chunk.text) {\n\t\t\t\t\t\t\t\ttextContent.text += chunk.text;\n\t\t\t\t\t\t\t\tstream.push({\n\t\t\t\t\t\t\t\t\ttype: 'text_delta',\n\t\t\t\t\t\t\t\t\tcontentIndex: textContentIndex,\n\t\t\t\t\t\t\t\t\tdelta: chunk.text,\n\t\t\t\t\t\t\t\t\tpartial,\n\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tcase 'tool_call': {\n\t\t\t\t\t\t\tif (!hasStarted) {\n\t\t\t\t\t\t\t\thasStarted = true;\n\t\t\t\t\t\t\t\tstream.push({ type: 'start', partial });\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif (textContentIndex !== -1) {\n\t\t\t\t\t\t\t\tconst tc = partial.content[textContentIndex];\n\t\t\t\t\t\t\t\tif (tc?.type === 'text') {\n\t\t\t\t\t\t\t\t\tstream.push({\n\t\t\t\t\t\t\t\t\t\ttype: 'text_end',\n\t\t\t\t\t\t\t\t\t\tcontentIndex: textContentIndex,\n\t\t\t\t\t\t\t\t\t\tcontent: tc.text,\n\t\t\t\t\t\t\t\t\t\tpartial,\n\t\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\ttextContentIndex = -1;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif (chunk.toolCall) {\n\t\t\t\t\t\t\t\tconst idx = partial.content.length;\n\t\t\t\t\t\t\t\tconst toolCall = {\n\t\t\t\t\t\t\t\t\ttype: 'toolCall' as const,\n\t\t\t\t\t\t\t\t\tid: chunk.toolCall.id,\n\t\t\t\t\t\t\t\t\tname: chunk.toolCall.name,\n\t\t\t\t\t\t\t\t\targuments: parseToolArguments(chunk.toolCall.arguments),\n\t\t\t\t\t\t\t\t};\n\t\t\t\t\t\t\t\tpartial.content.push(toolCall);\n\t\t\t\t\t\t\t\tstream.push({ type: 'toolcall_start', contentIndex: idx, partial });\n\t\t\t\t\t\t\t\tstream.push({\n\t\t\t\t\t\t\t\t\ttype: 'toolcall_delta',\n\t\t\t\t\t\t\t\t\tcontentIndex: idx,\n\t\t\t\t\t\t\t\t\tdelta: chunk.toolCall.arguments || '{}',\n\t\t\t\t\t\t\t\t\tpartial,\n\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\tstream.push({ type: 'toolcall_end', contentIndex: idx, toolCall, partial });\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tcase 'usage': {\n\t\t\t\t\t\t\tif (chunk.usage) {\n\t\t\t\t\t\t\t\tconst inputCost = (chunk.usage.input / 1_000_000) * (model.cost?.input ?? 0);\n\t\t\t\t\t\t\t\tconst outputCost = (chunk.usage.output / 1_000_000) * (model.cost?.output ?? 0);\n\t\t\t\t\t\t\t\tpartial.usage = {\n\t\t\t\t\t\t\t\t\tinput: chunk.usage.input,\n\t\t\t\t\t\t\t\t\toutput: chunk.usage.output,\n\t\t\t\t\t\t\t\t\tcacheRead: 0,\n\t\t\t\t\t\t\t\t\tcacheWrite: 0,\n\t\t\t\t\t\t\t\t\ttotalTokens: chunk.usage.total ?? chunk.usage.input + chunk.usage.output,\n\t\t\t\t\t\t\t\t\tcost: {\n\t\t\t\t\t\t\t\t\t\tinput: inputCost,\n\t\t\t\t\t\t\t\t\t\toutput: outputCost,\n\t\t\t\t\t\t\t\t\t\tcacheRead: 0,\n\t\t\t\t\t\t\t\t\t\tcacheWrite: 0,\n\t\t\t\t\t\t\t\t\t\ttotal: inputCost + outputCost,\n\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t};\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tcase 'error': {\n\t\t\t\t\t\t\tif (!hasStarted) {\n\t\t\t\t\t\t\t\thasStarted = true;\n\t\t\t\t\t\t\t\tstream.push({ type: 'start', partial });\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tpartial.stopReason = 'error';\n\t\t\t\t\t\t\tpartial.errorMessage = chunk.error ?? 'Unknown extension provider error';\n\t\t\t\t\t\t\tstream.push({ type: 'error', reason: 'error', error: partial });\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tcase 'done':\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif (textContentIndex !== -1) {\n\t\t\t\t\tconst tc = partial.content[textContentIndex];\n\t\t\t\t\tif (tc?.type === 'text') {\n\t\t\t\t\t\tstream.push({\n\t\t\t\t\t\t\ttype: 'text_end',\n\t\t\t\t\t\t\tcontentIndex: textContentIndex,\n\t\t\t\t\t\t\tcontent: tc.text,\n\t\t\t\t\t\t\tpartial,\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (!hasStarted) {\n\t\t\t\t\thasStarted = true;\n\t\t\t\t\tstream.push({ type: 'start', partial });\n\t\t\t\t}\n\n\t\t\t\tconst hasToolCalls = partial.content.some(c => c.type === 'toolCall');\n\t\t\t\tconst stopReason = hasToolCalls ? 'toolUse' : 'stop';\n\t\t\t\tpartial.stopReason = stopReason;\n\t\t\t\tstream.push({ type: 'done', reason: stopReason, message: partial });\n\t\t\t} catch (err) {\n\t\t\t\tif (!hasStarted) stream.push({ type: 'start', partial });\n\t\t\t\tpartial.stopReason = 'error';\n\t\t\t\tpartial.errorMessage = err instanceof Error ? err.message : String(err);\n\t\t\t\tstream.push({ type: 'error', reason: 'error', error: partial });\n\t\t\t}\n\t\t})();\n\n\t\treturn stream;\n\t}) as StreamFn;\n}\n"],"mappings":";;;;;;;sBAW2D;gBACF;aACP;AAElD,MAAM,MAAM,aAAa,wBAAwB;AAEjD,SAAS,qBAAqB,OAAqC;AAClE,QAAO;EACN,MAAM;EACN,SAAS,EAAE;EACX,KAAK,MAAM;EACX,UAAU,MAAM;EAChB,OAAO,MAAM;EACb,OAAO;GACN,OAAO;GACP,QAAQ;GACR,WAAW;GACX,YAAY;GACZ,aAAa;GACb,MAAM;IAAE,OAAO;IAAG,QAAQ;IAAG,WAAW;IAAG,YAAY;IAAG,OAAO;IAAG;GACpE;EACD,YAAY;EACZ,WAAW,KAAK,KAAK;EACrB;;AAGF,SAAS,mBAAmB,KAAkD;AAC7E,KAAI,CAAC,KAAK,MAAM,CAAE,QAAO,EAAE;AAC3B,KAAI;AACH,S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AK;AACb,QAAI,CAAC,WAAY,QAAO,KAAK;KAAE,MAAM;KAAS;KAAS,CAAC;AACxD,YAAQ,aAAa;AACrB,YAAQ,eAAe,eAAe,QAAQ,IAAI,UAAU,OAAO,IAAI;AACvE,WAAO,KAAK;KAAE,MAAM;KAAS,QAAQ;KAAS,OAAO;KAAS,CAAC;;MAE7D;AAEJ,SAAO"}
|
|
@@ -3,10 +3,10 @@
|
|
|
3
3
|
*/
|
|
4
4
|
import { type Model, type Api } from '@earendil-works/pi-ai/compat';
|
|
5
5
|
import { type Config } from '../config/schema.js';
|
|
6
|
+
import { type CredentialResolverOptions } from '../auth/credentials.js';
|
|
6
7
|
import type { ProviderModelDefinition } from '../extensions/types/providers.js';
|
|
8
|
+
export { EXTENSION_PROVIDER_BASE_URL } from './constants.js';
|
|
7
9
|
export { getApiKeyFromEnv, PROVIDER_ENV_MAP } from './env-keys.js';
|
|
8
|
-
/** Sentinel base URL: model is served by an extension {@link ProviderPluginRegistry} provider. */
|
|
9
|
-
export declare const EXTENSION_PROVIDER_BASE_URL = "extension://provider-plugin";
|
|
10
10
|
/** Map a plugin registry model to the pi-ai {@link Model} shape. */
|
|
11
11
|
export declare function pluginModelToModel(providerId: string, definition: ProviderModelDefinition): Model<Api>;
|
|
12
12
|
/**
|
|
@@ -23,7 +23,7 @@ export declare function getApiKeySync(provider: string): string | undefined;
|
|
|
23
23
|
export declare function resolveModel(ref: string): Model<Api>;
|
|
24
24
|
export declare function getModelsByProvider(provider: string): readonly Model<Api>[];
|
|
25
25
|
export declare function getAllProviders(): string[];
|
|
26
|
-
export declare function getApiKey(provider: string): Promise<string | undefined>;
|
|
26
|
+
export declare function getApiKey(provider: string, credentialOptions?: CredentialResolverOptions): Promise<string | undefined>;
|
|
27
27
|
/**
|
|
28
28
|
* Synchronous version for use in non-async contexts
|
|
29
29
|
* Only checks environment variables and registry, not credential system
|
|
@@ -4,6 +4,7 @@ import { hasProviderAuthOnDiskSync, init_sync_provider_auth } from "../auth/sync
|
|
|
4
4
|
import { PROVIDER_ENV_MAP, getApiKeyFromEnv, init_env_keys } from "./env-keys.js";
|
|
5
5
|
import { ModelRegistry, getModelRegistry, init_model_registry, prewarmModelRegistry, resetModelRegistry } from "./model-registry.js";
|
|
6
6
|
import { CredentialResolver, hasCredentials, init_credentials, resolveApiKey } from "../auth/credentials.js";
|
|
7
|
+
import { EXTENSION_PROVIDER_BASE_URL, init_constants } from "./constants.js";
|
|
7
8
|
import { getSupplementalModels, init_model_supplements } from "./model-supplements.js";
|
|
8
9
|
import { getProviderRegistry, init_plugin_registry } from "./plugin-registry.js";
|
|
9
10
|
import { getModel, getModels, getProviders } from "@earendil-works/pi-ai/compat";
|
|
@@ -137,9 +138,9 @@ function getAllProviders() {
|
|
|
137
138
|
for (const plugin of getProviderRegistry().listAll()) providers.add(plugin.id);
|
|
138
139
|
return Array.from(providers);
|
|
139
140
|
}
|
|
140
|
-
async function getApiKey(provider) {
|
|
141
|
+
async function getApiKey(provider, credentialOptions) {
|
|
141
142
|
if (getProviderRegistry().has(provider)) return "extension-managed";
|
|
142
|
-
const credentialKey = await resolveApiKey(provider);
|
|
143
|
+
const credentialKey = await resolveApiKey(provider, credentialOptions);
|
|
143
144
|
if (credentialKey) return credentialKey;
|
|
144
145
|
const registryKey = getModelRegistry().getApiKey(provider);
|
|
145
146
|
if (registryKey) return registryKey;
|
|
@@ -303,16 +304,16 @@ function getDefaultModelSync(config) {
|
|
|
303
304
|
if (modelRef) return modelRef;
|
|
304
305
|
return "";
|
|
305
306
|
}
|
|
306
|
-
var
|
|
307
|
+
var OPENAI_CODEX_CANONICAL_BASE_URL, PROVIDER_META;
|
|
307
308
|
var init_providers = __esmMin((() => {
|
|
308
309
|
init_schema();
|
|
309
310
|
init_model_registry();
|
|
310
311
|
init_credentials();
|
|
311
312
|
init_sync_provider_auth();
|
|
312
313
|
init_env_keys();
|
|
314
|
+
init_constants();
|
|
313
315
|
init_model_supplements();
|
|
314
316
|
init_plugin_registry();
|
|
315
|
-
EXTENSION_PROVIDER_BASE_URL = "extension://provider-plugin";
|
|
316
317
|
OPENAI_CODEX_CANONICAL_BASE_URL = "https://chatgpt.com/backend-api/codex";
|
|
317
318
|
PROVIDER_META = {
|
|
318
319
|
"openai": {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":["getPiAiModel","getPiAiProviders","getPiAiModels"],"sources":["../../../src/providers/index.ts"],"sourcesContent":["/**\n * Model provider module - integrates built-in models with custom models from models.json\n */\n\nimport {\n\tgetModel as getPiAiModel,\n\tgetModels as getPiAiModels,\n\tgetProviders as getPiAiProviders,\n\ttype Model,\n\ttype Api,\n} from '@earendil-works/pi-ai/compat';\nimport { getAgentDefaultModelRef, type Config } from '../config/schema.js';\nimport { getModelRegistry } from './model-registry.js';\nimport { CredentialResolver, resolveApiKey, hasCredentials } from '../auth/credentials.js';\nimport { hasProviderAuthOnDiskSync } from '../auth/sync-provider-auth.js';\nimport { getApiKeyFromEnv } from './env-keys.js';\nimport { getSupplementalModels } from './model-supplements.js';\nimport { getProviderRegistry } from './plugin-registry.js';\nimport type { ProviderModelDefinition } from '../extensions/types/providers.js';\n\nexport { getApiKeyFromEnv, PROVIDER_ENV_MAP } from './env-keys.js';\n\n/** Sentinel base URL: model is served by an extension {@link ProviderPluginRegistry} provider. */\nexport const EXTENSION_PROVIDER_BASE_URL = 'extension://provider-plugin';\nconst OPENAI_CODEX_CANONICAL_BASE_URL = 'https://chatgpt.com/backend-api/codex';\n\nfunction normalizeProviderModel(model: Model<Api>): Model<Api> {\n\tif (model.provider === 'openai-codex' && model.api === 'openai-codex-responses') {\n\t\treturn { ...model, baseUrl: OPENAI_CODEX_CANONICAL_BASE_URL } as Model<Api>;\n\t}\n\treturn model;\n}\n\n/** Map a plugin registry model to the pi-ai {@link Model} shape. */\nexport function pluginModelToModel(providerId: string, definition: ProviderModelDefinition): Model<Api> {\n\treturn {\n\t\tprovider: providerId,\n\t\tid: definition.id,\n\t\tname: definition.name,\n\t\tapi: 'openai-completions' as Api,\n\t\tbaseUrl: EXTENSION_PROVIDER_BASE_URL,\n\t\treasoning: false,\n\t\tinput: definition.supportsImages ? (['text', 'image'] as ('text' | 'image')[]) : (['text'] as ('text' | 'image')[]),\n\t\tcontextWindow: definition.contextWindow ?? 128000,\n\t\tmaxTokens: definition.maxOutputTokens ?? 4096,\n\t\tcost: {\n\t\t\tinput: definition.pricing?.input ?? 0,\n\t\t\toutput: definition.pricing?.output ?? 0,\n\t\t\tcacheRead: 0,\n\t\t\tcacheWrite: 0,\n\t\t},\n\t} as Model<Api>;\n}\n\n/**\n * Get API key synchronously: checks registry (models.json) first, then environment variables.\n * Use this for Agent's getApiKey callback which must be synchronous.\n */\nexport function getApiKeySync(provider: string): string | undefined {\n const pluginRegistry = getProviderRegistry();\n if (pluginRegistry.has(provider)) return 'extension-managed';\n\n const registry = getModelRegistry();\n const registryKey = registry.getApiKey(provider);\n if (registryKey) {\n return registryKey;\n }\n return getApiKeyFromEnv(provider);\n}\n\n/**\n * Resolve model reference. Supports:\n * - \"provider/modelId\" format\n * - \"modelId\" auto-detection via pi-ai or custom models\n * @throws if model not found\n */\nexport function resolveModel(ref: string): Model<Api> {\n\tconst trimmedRef = typeof ref === 'string' ? ref.trim() : '';\n\tif (!trimmedRef) {\n\t\tthrow new Error(\n\t\t\t'No default model configured. Choose a model in onboarding or set agents.capabilityPresets.default.models.roles.<role>.model.',\n\t\t);\n\t}\n\n\t// First try ModelRegistry (includes custom models)\n\tconst registry = getModelRegistry();\n\tconst customModel = registry.resolve(trimmedRef);\n\tif (customModel) {\n\t\treturn customModel;\n\t}\n\n\tif (trimmedRef.includes('/')) {\n\t\tconst [provider, modelId] = trimmedRef.split('/');\n\t\tconst piAiModel = getPiAiModel(provider as any, modelId as any);\n\t\tif (piAiModel) return normalizeProviderModel(piAiModel as Model<Api>);\n\n\t\tconst supplementalModel = getSupplementalModels().find(m => m.provider === provider && m.id === modelId);\n\t\tif (supplementalModel) return normalizeProviderModel(supplementalModel);\n\n\t\tconst pluginRegistry = getProviderRegistry();\n\t\tconst plugin = pluginRegistry.get(provider);\n\t\tif (plugin) {\n\t\t\tconst pluginModel = plugin.models.find(m => m.id === modelId);\n\t\t\tif (pluginModel) return pluginModelToModel(provider, pluginModel);\n\t\t}\n\t\tthrow new Error(`Model not found: ${trimmedRef}`);\n\t}\n\n\tfor (const provider of getPiAiProviders()) {\n\t\ttry {\n\t\t\tconst models = getPiAiModels(provider);\n\t\t\tconst found = models.find(m => m.id === trimmedRef);\n\t\t\tif (found) return normalizeProviderModel(found as Model<Api>);\n\t\t} catch {\n\t\t\tcontinue;\n\t\t}\n\t}\n\n\tconst supplementalModel = getSupplementalModels().find(m => m.id === trimmedRef);\n\tif (supplementalModel) return normalizeProviderModel(supplementalModel);\n\n\tconst pluginRegistry = getProviderRegistry();\n\tfor (const plugin of pluginRegistry.listAll()) {\n\t\tconst found = plugin.models.find(m => m.id === trimmedRef);\n\t\tif (found) return pluginModelToModel(plugin.id, found);\n\t}\n\n\tthrow new Error(`Model not found: ${trimmedRef}. Use format: provider/model-id`);\n}\n\nexport function getModelsByProvider(provider: string): readonly Model<Api>[] {\n\tconst registry = getModelRegistry();\n\tconst fromRegistry = registry.getAll().filter(m => m.provider === provider).map(normalizeProviderModel);\n\tconst existingIds = new Set(fromRegistry.map(m => m.id));\n\tconst supplementalModels = getSupplementalModels()\n\t\t.filter(m => m.provider === provider && !existingIds.has(m.id))\n\t\t.map(normalizeProviderModel);\n\tconst plugin = getProviderRegistry().get(provider);\n\tif (!plugin) return [...fromRegistry, ...supplementalModels];\n\tconst pluginModels = plugin.models.map(m => pluginModelToModel(provider, m));\n\treturn [...fromRegistry, ...supplementalModels, ...pluginModels];\n}\n\nexport function getAllProviders(): string[] {\n\tconst registry = getModelRegistry();\n\tconst providers = new Set<string>();\n\n\t// Add built-in providers\n\tfor (const p of getPiAiProviders()) {\n\t\tproviders.add(p);\n\t}\n\n\t// Add custom providers from registry\n\tfor (const m of registry.getAll()) {\n\t\tproviders.add(m.provider);\n\t}\n\n\tfor (const plugin of getProviderRegistry().listAll()) {\n\t\tproviders.add(plugin.id);\n\t}\n\n\treturn Array.from(providers);\n}\n\nexport async function getApiKey(provider: string): Promise<string | undefined> {\n\tif (getProviderRegistry().has(provider)) return 'extension-managed';\n\n\t// Use new credential resolver first (checks: agent private > global > oauth > env)\n\tconst credentialKey = await resolveApiKey(provider);\n\tif (credentialKey) {\n\t\treturn credentialKey;\n\t}\n\n\t// Check registry for custom providers (from models.json)\n\tconst registry = getModelRegistry();\n\tconst registryKey = registry.getApiKey(provider);\n\tif (registryKey) {\n\t\treturn registryKey;\n\t}\n\n\t// Fallback to environment variables\n\treturn getApiKeyFromEnv(provider);\n}\n\n/**\n * Synchronous version for use in non-async contexts\n * Only checks environment variables and registry, not credential system\n */\nexport function isProviderConfiguredSync(provider: string): boolean {\n\tif (getProviderRegistry().has(provider)) return true;\n\n\t// Check registry for custom providers\n\tconst registry = getModelRegistry();\n\tif (registry.getApiKey(provider)) {\n\t\treturn true;\n\t}\n\t// Check environment variables\n\tif (getApiKeyFromEnv(provider)) {\n\t\treturn true;\n\t}\n\t// Gateway UI / CLI store keys in auth-profiles.json (async CredentialResolver); sync path for fallback list\n\treturn hasProviderAuthOnDiskSync(provider);\n}\n\nexport async function isProviderConfigured(provider: string): Promise<boolean> {\n if (getProviderRegistry().has(provider)) return true;\n\n // Check registry first for custom providers (from models.json)\n const registry = getModelRegistry();\n if (registry.getApiKey(provider)) {\n return true;\n }\n return await hasCredentials(provider);\n}\n\n/** Where runtime {@link getApiKey} resolves the key from (no secret values). */\nexport type ProviderActiveKeySource = 'none' | 'agent' | 'gateway' | 'oauth' | 'env' | 'models_json' | 'extension';\n\nexport type ProviderAuthMode = ProviderActiveKeySource;\nexport type ProviderAuthStatus = 'connected' | 'expired' | 'not_connected';\n\nexport interface ProviderAuthState {\n authMode: ProviderAuthMode;\n authStatus: ProviderAuthStatus;\n expiresAt?: number;\n}\n\nexport async function getProviderActiveKeySource(provider: string): Promise<ProviderActiveKeySource> {\n const authState = await getProviderAuthState(provider);\n return authState.authMode;\n}\n\nexport async function getProviderAuthState(provider: string): Promise<ProviderAuthState> {\n if (getProviderRegistry().has(provider)) {\n return { authMode: 'extension', authStatus: 'connected' };\n }\n\n const resolver = new CredentialResolver();\n const fromCredentials = await resolver.resolveApiKeySource(provider);\n if (fromCredentials === 'agent') return { authMode: 'agent', authStatus: 'connected' };\n if (fromCredentials === 'global') return { authMode: 'gateway', authStatus: 'connected' };\n if (fromCredentials === 'oauth') {\n const token = await resolver.loadOAuthTokenRecord(provider);\n const expired = Boolean(token?.expiresAt && token.expiresAt < Date.now());\n return {\n authMode: 'oauth',\n authStatus: expired ? 'expired' : 'connected',\n ...(token?.expiresAt ? { expiresAt: token.expiresAt } : {}),\n };\n }\n if (fromCredentials === 'env') return { authMode: 'env', authStatus: 'connected' };\n\n const expiredOAuthToken = await resolver.loadOAuthTokenRecord(provider);\n if (expiredOAuthToken?.expiresAt && expiredOAuthToken.expiresAt < Date.now()) {\n return {\n authMode: 'oauth',\n authStatus: 'expired',\n expiresAt: expiredOAuthToken.expiresAt,\n };\n }\n\n const registry = getModelRegistry();\n if (registry.getApiKey(provider)) {\n return { authMode: 'models_json', authStatus: 'connected' };\n }\n\n return { authMode: 'none', authStatus: 'not_connected' };\n}\n\nexport async function getConfiguredProviders(): Promise<string[]> {\n\tconst allProviders = getAllProviders();\n\tconst configured: string[] = [];\n\tfor (const p of allProviders) {\n\t\tif (await isProviderConfigured(p)) {\n\t\t\tconfigured.push(p);\n\t\t}\n\t}\n\treturn configured;\n}\n\nexport function getAllModels(): readonly Model<Api>[] {\n\tconst registry = getModelRegistry();\n\tconst registryModels = registry.getAll().map(normalizeProviderModel);\n\tconst existingIds = new Set(registryModels.map(m => `${m.provider}/${m.id}`));\n\tconst supplementalModels = getSupplementalModels()\n\t\t.filter(m => !existingIds.has(`${m.provider}/${m.id}`))\n\t\t.map(normalizeProviderModel);\n\tfor (const model of supplementalModels) {\n\t\texistingIds.add(`${model.provider}/${model.id}`);\n\t}\n\tconst pluginProviders = getProviderRegistry().listAll();\n\tif (pluginProviders.length === 0) return [...registryModels, ...supplementalModels];\n\n\tconst merged: Model<Api>[] = [...registryModels, ...supplementalModels];\n\tfor (const plugin of pluginProviders) {\n\t\tfor (const model of plugin.models) {\n\t\t\tconst compositeId = `${plugin.id}/${model.id}`;\n\t\t\tif (!existingIds.has(compositeId)) {\n\t\t\t\tmerged.push(pluginModelToModel(plugin.id, model));\n\t\t\t\texistingIds.add(compositeId);\n\t\t\t}\n\t\t}\n\t}\n\treturn merged;\n}\n\nexport async function getAvailableModels(): Promise<readonly Model<Api>[]> {\n\tconst allModels = getAllModels();\n\tconst pluginRegistry = getProviderRegistry();\n\tconst available: Model<Api>[] = [];\n\tconst configuredByProvider = new Map<string, boolean>();\n\n\tfor (const model of allModels) {\n\t\tif (pluginRegistry.has(model.provider)) {\n\t\t\tavailable.push(model);\n\t\t\tcontinue;\n\t\t}\n\t\tlet configured = configuredByProvider.get(model.provider);\n\t\tif (configured === undefined) {\n\t\t\tconfigured = await isProviderConfigured(model.provider);\n\t\t\tconfiguredByProvider.set(model.provider, configured);\n\t\t}\n\t\tif (configured) {\n\t\t\tavailable.push(model);\n\t\t}\n\t}\n\treturn available;\n}\n\nexport type { Model, Api } from '@earendil-works/pi-ai';\n\nexport type ProviderCategory = 'common' | 'domestic' | 'specialty' | 'oauth' | 'enterprise' | 'extension';\n\nexport interface ProviderMeta {\n name: string;\n category: ProviderCategory;\n supportsOAuth?: boolean;\n supportsApiKey?: boolean;\n}\n\nexport const PROVIDER_META: Record<string, ProviderMeta> = {\n 'openai': { name: 'OpenAI', category: 'common', supportsApiKey: true },\n 'anthropic': { name: 'Anthropic', category: 'common', supportsApiKey: true, supportsOAuth: true },\n 'deepseek': { name: 'DeepSeek', category: 'domestic', supportsApiKey: true },\n 'google': { name: 'Google AI', category: 'common', supportsApiKey: true },\n 'groq': { name: 'Groq', category: 'common', supportsApiKey: true },\n 'minimax': { name: 'MiniMax', category: 'domestic', supportsApiKey: true, supportsOAuth: true },\n 'minimax-cn': { name: 'MiniMax CN', category: 'domestic', supportsApiKey: true, supportsOAuth: true },\n 'kimi-coding': { name: 'Kimi For Coding', category: 'domestic', supportsApiKey: true, supportsOAuth: true },\n 'xai': { name: 'xAI', category: 'specialty', supportsApiKey: true },\n 'mistral': { name: 'Mistral AI', category: 'specialty', supportsApiKey: true },\n 'cerebras': { name: 'Cerebras', category: 'specialty', supportsApiKey: true },\n 'openrouter': { name: 'OpenRouter', category: 'specialty', supportsApiKey: true },\n 'huggingface': { name: 'Hugging Face', category: 'specialty', supportsApiKey: true },\n moonshotai: { name: 'Moonshot AI (Kimi · International)', category: 'domestic', supportsApiKey: true },\n 'moonshotai-cn': { name: 'Moonshot AI (Kimi · China)', category: 'domestic', supportsApiKey: true },\n fireworks: { name: 'Fireworks AI', category: 'specialty', supportsApiKey: true },\n together: { name: 'Together AI', category: 'specialty', supportsApiKey: true },\n 'cloudflare-workers-ai': { name: 'Cloudflare Workers AI', category: 'enterprise', supportsApiKey: true },\n 'cloudflare-ai-gateway': { name: 'Cloudflare AI Gateway', category: 'enterprise', supportsApiKey: true },\n xiaomi: { name: 'Xiaomi Mimo', category: 'domestic', supportsApiKey: true },\n 'xiaomi-token-plan-cn': { name: 'Xiaomi Token Plan (CN)', category: 'domestic', supportsApiKey: true },\n 'xiaomi-token-plan-ams': { name: 'Xiaomi Token Plan (AMS)', category: 'domestic', supportsApiKey: true },\n 'xiaomi-token-plan-sgp': { name: 'Xiaomi Token Plan (SGP)', category: 'domestic', supportsApiKey: true },\n 'opencode': { name: 'OpenCode', category: 'specialty', supportsApiKey: true },\n 'opencode-go': { name: 'OpenCode Go', category: 'specialty', supportsApiKey: true },\n 'dashscope': { name: 'DashScope (Alibaba)', category: 'domestic', supportsApiKey: true },\n 'dashscope-cn': { name: 'Alibaba Bailian / DashScope China', category: 'domestic', supportsApiKey: true },\n 'dashscope-intl': { name: 'Alibaba Bailian / DashScope International', category: 'domestic', supportsApiKey: true },\n 'volcengine-ark': { name: 'Volcengine Ark', category: 'domestic', supportsApiKey: true },\n 'volcengine-plan': { name: 'Volcengine Doubao Coding Plan', category: 'domestic', supportsApiKey: true },\n 'byteplus-plan': { name: 'BytePlus Doubao Coding Plan', category: 'domestic', supportsApiKey: true },\n 'stepfun': { name: 'StepFun', category: 'domestic', supportsApiKey: true },\n 'stepfun-cn': { name: 'StepFun China', category: 'domestic', supportsApiKey: true },\n 'stepfun-intl': { name: 'StepFun International', category: 'domestic', supportsApiKey: true },\n 'stepfun-plan': { name: 'StepFun Step Plan', category: 'domestic', supportsApiKey: true },\n 'stepfun-plan-cn': { name: 'StepFun Step Plan China', category: 'domestic', supportsApiKey: true },\n 'stepfun-plan-intl': { name: 'StepFun Step Plan International', category: 'domestic', supportsApiKey: true },\n 'ant-ling': { name: 'Ant Ling', category: 'domestic', supportsApiKey: true },\n 'zhipu-cn': { name: 'Zhipu GLM (China)', category: 'domestic', supportsApiKey: true },\n 'zai-coding-cn': { name: 'Zhipu GLM Coding Plan (China)', category: 'domestic', supportsApiKey: true },\n 'zai-coding-global': { name: 'Zhipu GLM Coding Plan (International)', category: 'domestic', supportsApiKey: true },\n 'zhipu-coding-cn': { name: 'Zhipu GLM Coding Plan (China)', category: 'domestic', supportsApiKey: true },\n /** International GLM (api.z.ai). Auth: API key (ZAI_API_KEY); no published OAuth for this HTTP API. */\n 'zai': { name: 'Zhipu GLM (International · z.ai)', category: 'domestic', supportsApiKey: true },\n 'amazon-bedrock': { name: 'Amazon Bedrock', category: 'enterprise', supportsApiKey: true },\n 'azure-openai-responses': { name: 'Azure OpenAI', category: 'enterprise', supportsApiKey: true },\n 'google-vertex': { name: 'Google Vertex AI', category: 'enterprise', supportsApiKey: true },\n 'vercel-ai-gateway': { name: 'Vercel AI Gateway', category: 'enterprise', supportsApiKey: true },\n 'github-copilot': { name: 'GitHub Copilot (OAuth)', category: 'oauth', supportsOAuth: true, supportsApiKey: false },\n 'openai-codex': { name: 'OpenAI Codex (OAuth)', category: 'oauth', supportsOAuth: true, supportsApiKey: false },\n 'google-gemini-cli': { name: 'Google Gemini CLI (OAuth)', category: 'oauth', supportsOAuth: true, supportsApiKey: false },\n 'google-antigravity': { name: 'Google Antigravity (OAuth)', category: 'oauth', supportsOAuth: true, supportsApiKey: false },\n};\n\nexport function getSortedProviders(): string[] {\n const all = getAllProviders();\n const catOrder: Record<ProviderCategory, number> = {\n common: 0,\n domestic: 1,\n specialty: 2,\n enterprise: 3,\n oauth: 4,\n extension: 5,\n };\n const pluginRegistry = getProviderRegistry();\n\n return [...all].sort((a, b) => {\n const catA = pluginRegistry.has(a) ? 'extension' : (PROVIDER_META[a]?.category ?? 'specialty');\n const catB = pluginRegistry.has(b) ? 'extension' : (PROVIDER_META[b]?.category ?? 'specialty');\n if (catOrder[catA] !== catOrder[catB]) {\n return catOrder[catA] - catOrder[catB];\n }\n return a.localeCompare(b);\n });\n}\n\nexport function getProviderDisplayName(provider: string): string {\n const plugin = getProviderRegistry().get(provider);\n if (plugin) return plugin.name;\n return PROVIDER_META[provider]?.name || provider;\n}\n\nexport function providerSupportsOAuth(provider: string): boolean {\n return PROVIDER_META[provider]?.supportsOAuth ?? false;\n}\n\nexport function providerSupportsApiKey(provider: string): boolean {\n return PROVIDER_META[provider]?.supportsApiKey ?? true;\n}\n\n// ============================================\n// Dynamic Default Model Resolution\n// ============================================\n\n/**\n * Get a default model reference.\n * Priority:\n * 1. Effective model inherited from the global default preset / agent presets / agent override\n * 2. Empty string only when no default model is present in the loaded config\n */\nexport async function getDefaultModel(config?: Config | null | undefined): Promise<string> {\n const modelRef = config ? getAgentDefaultModelRef(config) : undefined;\n if (modelRef) {\n const availableModels = await getAvailableModels();\n const configured = availableModels.find(m =>\n `${m.provider}/${m.id}` === modelRef ||\n m.id === modelRef\n );\n if (configured) {\n return `${configured.provider}/${configured.id}`;\n }\n return modelRef;\n }\n\n return '';\n}\n\n/**\n * Synchronous default model resolution for constructors and sync code paths.\n * Uses catalog/registry only (no async credential checks).\n *\n * When no model is present in the loaded config, returns an empty string so\n * setup flows can prompt for the global default model.\n */\nexport function getDefaultModelSync(config?: Config | null | undefined): string {\n const modelRef = config ? getAgentDefaultModelRef(config) : undefined;\n if (modelRef) {\n return modelRef;\n }\n\n return '';\n}\n\n// Re-export ModelRegistry for advanced use cases\nexport { ModelRegistry, getModelRegistry, resetModelRegistry, prewarmModelRegistry } from './model-registry.js';\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA0BA,SAAS,uBAAuB,OAA+B;AAC9D,KAAI,MAAM,aAAa,kBAAkB,MAAM,QAAQ,yBACtD,QAAO;EAAE,GAAG;EAAO,SAAS;EAAiC;AAE9D,QAAO;;;AAIR,SAAgB,mBAAmB,YAAoB,YAAiD;AACvG,QAAO;EACN,UAAU;EACV,IAAI,WAAW;EACf,MAAM,WAAW;EACjB,KAAK;EACL,SAAS;EACT,WAAW;EACX,OAAO,WAAW,iBAAkB,CAAC,QAAQ,QAAQ,GAA6B,CAAC,OAAO;EAC1F,eAAe,WAAW,iBAAiB;EAC3C,WAAW,WAAW,mBAAmB;EACzC,MAAM;GACL,OAAO,WAAW,SAAS,SAAS;GACpC,QAAQ,WAAW,SAAS,UAAU;GACtC,WAAW;GACX,YAAY;GACZ;EACD;;;;;;AAOF,SAAgB,cAAc,UAAsC;AAElE,KADuB,qBACL,CAAC,IAAI,SAAS,CAAE,QAAO;CAGzC,MAAM,cADW,kBACW,CAAC,UAAU,SAAS;AAChD,KAAI,YACF,QAAO;AAET,QAAO,iBAAiB,SAAS;;;;;;;;AASnC,SAAgB,aAAa,KAAyB;CACrD,MAAM,aAAa,OAAO,QAAQ,WAAW,IAAI,MAAM,GAAG;AAC1D,KAAI,CAAC,WACJ,OAAM,IAAI,MACT,+HACA;CAKF,MAAM,cADW,kBACW,CAAC,QAAQ,WAAW;AAChD,KAAI,Y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Y,gBAAgB;GAAM;;EAExG,OAAO;GAAE,MAAM;GAAoC,UAAU;GAAY,gBAAgB;GAAM;EAC/F,kBAAkB;GAAE,MAAM;GAAkB,UAAU;GAAc,gBAAgB;GAAM;EAC1F,0BAA0B;GAAE,MAAM;GAAgB,UAAU;GAAc,gBAAgB;GAAM;EAChG,iBAAiB;GAAE,MAAM;GAAoB,UAAU;GAAc,gBAAgB;GAAM;EAC3F,qBAAqB;GAAE,MAAM;GAAqB,UAAU;GAAc,gBAAgB;GAAM;EAChG,kBAAkB;GAAE,MAAM;GAA0B,UAAU;GAAS,eAAe;GAAM,gBAAgB;GAAO;EACnH,gBAAgB;GAAE,MAAM;GAAwB,UAAU;GAAS,eAAe;GAAM,gBAAgB;GAAO;EAC/G,qBAAqB;GAAE,MAAM;GAA6B,UAAU;GAAS,eAAe;GAAM,gBAAgB;GAAO;EACzH,sBAAsB;GAAE,MAAM;GAA8B,UAAU;GAAS,eAAe;GAAM,gBAAgB;GAAO;EAC5H"}
|
|
1
|
+
{"version":3,"file":"index.js","names":["getPiAiModel","getPiAiProviders","getPiAiModels"],"sources":["../../../src/providers/index.ts"],"sourcesContent":["/**\n * Model provider module - integrates built-in models with custom models from models.json\n */\n\nimport {\n\tgetModel as getPiAiModel,\n\tgetModels as getPiAiModels,\n\tgetProviders as getPiAiProviders,\n\ttype Model,\n\ttype Api,\n} from '@earendil-works/pi-ai/compat';\nimport { getAgentDefaultModelRef, type Config } from '../config/schema.js';\nimport { getModelRegistry } from './model-registry.js';\nimport {\n\tCredentialResolver,\n\tresolveApiKey,\n\thasCredentials,\n\ttype CredentialResolverOptions,\n} from '../auth/credentials.js';\nimport { hasProviderAuthOnDiskSync } from '../auth/sync-provider-auth.js';\nimport { getApiKeyFromEnv } from './env-keys.js';\nimport { EXTENSION_PROVIDER_BASE_URL } from './constants.js';\nimport { getSupplementalModels } from './model-supplements.js';\nimport { getProviderRegistry } from './plugin-registry.js';\nimport type { ProviderModelDefinition } from '../extensions/types/providers.js';\n\nexport { EXTENSION_PROVIDER_BASE_URL } from './constants.js';\nexport { getApiKeyFromEnv, PROVIDER_ENV_MAP } from './env-keys.js';\nconst OPENAI_CODEX_CANONICAL_BASE_URL = 'https://chatgpt.com/backend-api/codex';\n\nfunction normalizeProviderModel(model: Model<Api>): Model<Api> {\n\tif (model.provider === 'openai-codex' && model.api === 'openai-codex-responses') {\n\t\treturn { ...model, baseUrl: OPENAI_CODEX_CANONICAL_BASE_URL } as Model<Api>;\n\t}\n\treturn model;\n}\n\n/** Map a plugin registry model to the pi-ai {@link Model} shape. */\nexport function pluginModelToModel(providerId: string, definition: ProviderModelDefinition): Model<Api> {\n\treturn {\n\t\tprovider: providerId,\n\t\tid: definition.id,\n\t\tname: definition.name,\n\t\tapi: 'openai-completions' as Api,\n\t\tbaseUrl: EXTENSION_PROVIDER_BASE_URL,\n\t\treasoning: false,\n\t\tinput: definition.supportsImages ? (['text', 'image'] as ('text' | 'image')[]) : (['text'] as ('text' | 'image')[]),\n\t\tcontextWindow: definition.contextWindow ?? 128000,\n\t\tmaxTokens: definition.maxOutputTokens ?? 4096,\n\t\tcost: {\n\t\t\tinput: definition.pricing?.input ?? 0,\n\t\t\toutput: definition.pricing?.output ?? 0,\n\t\t\tcacheRead: 0,\n\t\t\tcacheWrite: 0,\n\t\t},\n\t} as Model<Api>;\n}\n\n/**\n * Get API key synchronously: checks registry (models.json) first, then environment variables.\n * Use this for Agent's getApiKey callback which must be synchronous.\n */\nexport function getApiKeySync(provider: string): string | undefined {\n const pluginRegistry = getProviderRegistry();\n if (pluginRegistry.has(provider)) return 'extension-managed';\n\n const registry = getModelRegistry();\n const registryKey = registry.getApiKey(provider);\n if (registryKey) {\n return registryKey;\n }\n return getApiKeyFromEnv(provider);\n}\n\n/**\n * Resolve model reference. Supports:\n * - \"provider/modelId\" format\n * - \"modelId\" auto-detection via pi-ai or custom models\n * @throws if model not found\n */\nexport function resolveModel(ref: string): Model<Api> {\n\tconst trimmedRef = typeof ref === 'string' ? ref.trim() : '';\n\tif (!trimmedRef) {\n\t\tthrow new Error(\n\t\t\t'No default model configured. Choose a model in onboarding or set agents.capabilityPresets.default.models.roles.<role>.model.',\n\t\t);\n\t}\n\n\t// First try ModelRegistry (includes custom models)\n\tconst registry = getModelRegistry();\n\tconst customModel = registry.resolve(trimmedRef);\n\tif (customModel) {\n\t\treturn customModel;\n\t}\n\n\tif (trimmedRef.includes('/')) {\n\t\tconst [provider, modelId] = trimmedRef.split('/');\n\t\tconst piAiModel = getPiAiModel(provider as any, modelId as any);\n\t\tif (piAiModel) return normalizeProviderModel(piAiModel as Model<Api>);\n\n\t\tconst supplementalModel = getSupplementalModels().find(m => m.provider === provider && m.id === modelId);\n\t\tif (supplementalModel) return normalizeProviderModel(supplementalModel);\n\n\t\tconst pluginRegistry = getProviderRegistry();\n\t\tconst plugin = pluginRegistry.get(provider);\n\t\tif (plugin) {\n\t\t\tconst pluginModel = plugin.models.find(m => m.id === modelId);\n\t\t\tif (pluginModel) return pluginModelToModel(provider, pluginModel);\n\t\t}\n\t\tthrow new Error(`Model not found: ${trimmedRef}`);\n\t}\n\n\tfor (const provider of getPiAiProviders()) {\n\t\ttry {\n\t\t\tconst models = getPiAiModels(provider);\n\t\t\tconst found = models.find(m => m.id === trimmedRef);\n\t\t\tif (found) return normalizeProviderModel(found as Model<Api>);\n\t\t} catch {\n\t\t\tcontinue;\n\t\t}\n\t}\n\n\tconst supplementalModel = getSupplementalModels().find(m => m.id === trimmedRef);\n\tif (supplementalModel) return normalizeProviderModel(supplementalModel);\n\n\tconst pluginRegistry = getProviderRegistry();\n\tfor (const plugin of pluginRegistry.listAll()) {\n\t\tconst found = plugin.models.find(m => m.id === trimmedRef);\n\t\tif (found) return pluginModelToModel(plugin.id, found);\n\t}\n\n\tthrow new Error(`Model not found: ${trimmedRef}. Use format: provider/model-id`);\n}\n\nexport function getModelsByProvider(provider: string): readonly Model<Api>[] {\n\tconst registry = getModelRegistry();\n\tconst fromRegistry = registry.getAll().filter(m => m.provider === provider).map(normalizeProviderModel);\n\tconst existingIds = new Set(fromRegistry.map(m => m.id));\n\tconst supplementalModels = getSupplementalModels()\n\t\t.filter(m => m.provider === provider && !existingIds.has(m.id))\n\t\t.map(normalizeProviderModel);\n\tconst plugin = getProviderRegistry().get(provider);\n\tif (!plugin) return [...fromRegistry, ...supplementalModels];\n\tconst pluginModels = plugin.models.map(m => pluginModelToModel(provider, m));\n\treturn [...fromRegistry, ...supplementalModels, ...pluginModels];\n}\n\nexport function getAllProviders(): string[] {\n\tconst registry = getModelRegistry();\n\tconst providers = new Set<string>();\n\n\t// Add built-in providers\n\tfor (const p of getPiAiProviders()) {\n\t\tproviders.add(p);\n\t}\n\n\t// Add custom providers from registry\n\tfor (const m of registry.getAll()) {\n\t\tproviders.add(m.provider);\n\t}\n\n\tfor (const plugin of getProviderRegistry().listAll()) {\n\t\tproviders.add(plugin.id);\n\t}\n\n\treturn Array.from(providers);\n}\n\nexport async function getApiKey(\n\tprovider: string,\n\tcredentialOptions?: CredentialResolverOptions,\n): Promise<string | undefined> {\n\tif (getProviderRegistry().has(provider)) return 'extension-managed';\n\n\t// Use new credential resolver first (checks: agent private > global > oauth > env)\n\tconst credentialKey = await resolveApiKey(provider, credentialOptions);\n\tif (credentialKey) {\n\t\treturn credentialKey;\n\t}\n\n\t// Check registry for custom providers (from models.json)\n\tconst registry = getModelRegistry();\n\tconst registryKey = registry.getApiKey(provider);\n\tif (registryKey) {\n\t\treturn registryKey;\n\t}\n\n\t// Fallback to environment variables\n\treturn getApiKeyFromEnv(provider);\n}\n\n/**\n * Synchronous version for use in non-async contexts\n * Only checks environment variables and registry, not credential system\n */\nexport function isProviderConfiguredSync(provider: string): boolean {\n\tif (getProviderRegistry().has(provider)) return true;\n\n\t// Check registry for custom providers\n\tconst registry = getModelRegistry();\n\tif (registry.getApiKey(provider)) {\n\t\treturn true;\n\t}\n\t// Check environment variables\n\tif (getApiKeyFromEnv(provider)) {\n\t\treturn true;\n\t}\n\t// Gateway UI / CLI store keys in auth-profiles.json (async CredentialResolver); sync path for fallback list\n\treturn hasProviderAuthOnDiskSync(provider);\n}\n\nexport async function isProviderConfigured(provider: string): Promise<boolean> {\n if (getProviderRegistry().has(provider)) return true;\n\n // Check registry first for custom providers (from models.json)\n const registry = getModelRegistry();\n if (registry.getApiKey(provider)) {\n return true;\n }\n return await hasCredentials(provider);\n}\n\n/** Where runtime {@link getApiKey} resolves the key from (no secret values). */\nexport type ProviderActiveKeySource = 'none' | 'agent' | 'gateway' | 'oauth' | 'env' | 'models_json' | 'extension';\n\nexport type ProviderAuthMode = ProviderActiveKeySource;\nexport type ProviderAuthStatus = 'connected' | 'expired' | 'not_connected';\n\nexport interface ProviderAuthState {\n authMode: ProviderAuthMode;\n authStatus: ProviderAuthStatus;\n expiresAt?: number;\n}\n\nexport async function getProviderActiveKeySource(provider: string): Promise<ProviderActiveKeySource> {\n const authState = await getProviderAuthState(provider);\n return authState.authMode;\n}\n\nexport async function getProviderAuthState(provider: string): Promise<ProviderAuthState> {\n if (getProviderRegistry().has(provider)) {\n return { authMode: 'extension', authStatus: 'connected' };\n }\n\n const resolver = new CredentialResolver();\n const fromCredentials = await resolver.resolveApiKeySource(provider);\n if (fromCredentials === 'agent') return { authMode: 'agent', authStatus: 'connected' };\n if (fromCredentials === 'global') return { authMode: 'gateway', authStatus: 'connected' };\n if (fromCredentials === 'oauth') {\n const token = await resolver.loadOAuthTokenRecord(provider);\n const expired = Boolean(token?.expiresAt && token.expiresAt < Date.now());\n return {\n authMode: 'oauth',\n authStatus: expired ? 'expired' : 'connected',\n ...(token?.expiresAt ? { expiresAt: token.expiresAt } : {}),\n };\n }\n if (fromCredentials === 'env') return { authMode: 'env', authStatus: 'connected' };\n\n const expiredOAuthToken = await resolver.loadOAuthTokenRecord(provider);\n if (expiredOAuthToken?.expiresAt && expiredOAuthToken.expiresAt < Date.now()) {\n return {\n authMode: 'oauth',\n authStatus: 'expired',\n expiresAt: expiredOAuthToken.expiresAt,\n };\n }\n\n const registry = getModelRegistry();\n if (registry.getApiKey(provider)) {\n return { authMode: 'models_json', authStatus: 'connected' };\n }\n\n return { authMode: 'none', authStatus: 'not_connected' };\n}\n\nexport async function getConfiguredProviders(): Promise<string[]> {\n\tconst allProviders = getAllProviders();\n\tconst configured: string[] = [];\n\tfor (const p of allProviders) {\n\t\tif (await isProviderConfigured(p)) {\n\t\t\tconfigured.push(p);\n\t\t}\n\t}\n\treturn configured;\n}\n\nexport function getAllModels(): readonly Model<Api>[] {\n\tconst registry = getModelRegistry();\n\tconst registryModels = registry.getAll().map(normalizeProviderModel);\n\tconst existingIds = new Set(registryModels.map(m => `${m.provider}/${m.id}`));\n\tconst supplementalModels = getSupplementalModels()\n\t\t.filter(m => !existingIds.has(`${m.provider}/${m.id}`))\n\t\t.map(normalizeProviderModel);\n\tfor (const model of supplementalModels) {\n\t\texistingIds.add(`${model.provider}/${model.id}`);\n\t}\n\tconst pluginProviders = getProviderRegistry().listAll();\n\tif (pluginProviders.length === 0) return [...registryModels, ...supplementalModels];\n\n\tconst merged: Model<Api>[] = [...registryModels, ...supplementalModels];\n\tfor (const plugin of pluginProviders) {\n\t\tfor (const model of plugin.models) {\n\t\t\tconst compositeId = `${plugin.id}/${model.id}`;\n\t\t\tif (!existingIds.has(compositeId)) {\n\t\t\t\tmerged.push(pluginModelToModel(plugin.id, model));\n\t\t\t\texistingIds.add(compositeId);\n\t\t\t}\n\t\t}\n\t}\n\treturn merged;\n}\n\nexport async function getAvailableModels(): Promise<readonly Model<Api>[]> {\n\tconst allModels = getAllModels();\n\tconst pluginRegistry = getProviderRegistry();\n\tconst available: Model<Api>[] = [];\n\tconst configuredByProvider = new Map<string, boolean>();\n\n\tfor (const model of allModels) {\n\t\tif (pluginRegistry.has(model.provider)) {\n\t\t\tavailable.push(model);\n\t\t\tcontinue;\n\t\t}\n\t\tlet configured = configuredByProvider.get(model.provider);\n\t\tif (configured === undefined) {\n\t\t\tconfigured = await isProviderConfigured(model.provider);\n\t\t\tconfiguredByProvider.set(model.provider, configured);\n\t\t}\n\t\tif (configured) {\n\t\t\tavailable.push(model);\n\t\t}\n\t}\n\treturn available;\n}\n\nexport type { Model, Api } from '@earendil-works/pi-ai';\n\nexport type ProviderCategory = 'common' | 'domestic' | 'specialty' | 'oauth' | 'enterprise' | 'extension';\n\nexport interface ProviderMeta {\n name: string;\n category: ProviderCategory;\n supportsOAuth?: boolean;\n supportsApiKey?: boolean;\n}\n\nexport const PROVIDER_META: Record<string, ProviderMeta> = {\n 'openai': { name: 'OpenAI', category: 'common', supportsApiKey: true },\n 'anthropic': { name: 'Anthropic', category: 'common', supportsApiKey: true, supportsOAuth: true },\n 'deepseek': { name: 'DeepSeek', category: 'domestic', supportsApiKey: true },\n 'google': { name: 'Google AI', category: 'common', supportsApiKey: true },\n 'groq': { name: 'Groq', category: 'common', supportsApiKey: true },\n 'minimax': { name: 'MiniMax', category: 'domestic', supportsApiKey: true, supportsOAuth: true },\n 'minimax-cn': { name: 'MiniMax CN', category: 'domestic', supportsApiKey: true, supportsOAuth: true },\n 'kimi-coding': { name: 'Kimi For Coding', category: 'domestic', supportsApiKey: true, supportsOAuth: true },\n 'xai': { name: 'xAI', category: 'specialty', supportsApiKey: true },\n 'mistral': { name: 'Mistral AI', category: 'specialty', supportsApiKey: true },\n 'cerebras': { name: 'Cerebras', category: 'specialty', supportsApiKey: true },\n 'openrouter': { name: 'OpenRouter', category: 'specialty', supportsApiKey: true },\n 'huggingface': { name: 'Hugging Face', category: 'specialty', supportsApiKey: true },\n moonshotai: { name: 'Moonshot AI (Kimi · International)', category: 'domestic', supportsApiKey: true },\n 'moonshotai-cn': { name: 'Moonshot AI (Kimi · China)', category: 'domestic', supportsApiKey: true },\n fireworks: { name: 'Fireworks AI', category: 'specialty', supportsApiKey: true },\n together: { name: 'Together AI', category: 'specialty', supportsApiKey: true },\n 'cloudflare-workers-ai': { name: 'Cloudflare Workers AI', category: 'enterprise', supportsApiKey: true },\n 'cloudflare-ai-gateway': { name: 'Cloudflare AI Gateway', category: 'enterprise', supportsApiKey: true },\n xiaomi: { name: 'Xiaomi Mimo', category: 'domestic', supportsApiKey: true },\n 'xiaomi-token-plan-cn': { name: 'Xiaomi Token Plan (CN)', category: 'domestic', supportsApiKey: true },\n 'xiaomi-token-plan-ams': { name: 'Xiaomi Token Plan (AMS)', category: 'domestic', supportsApiKey: true },\n 'xiaomi-token-plan-sgp': { name: 'Xiaomi Token Plan (SGP)', category: 'domestic', supportsApiKey: true },\n 'opencode': { name: 'OpenCode', category: 'specialty', supportsApiKey: true },\n 'opencode-go': { name: 'OpenCode Go', category: 'specialty', supportsApiKey: true },\n 'dashscope': { name: 'DashScope (Alibaba)', category: 'domestic', supportsApiKey: true },\n 'dashscope-cn': { name: 'Alibaba Bailian / DashScope China', category: 'domestic', supportsApiKey: true },\n 'dashscope-intl': { name: 'Alibaba Bailian / DashScope International', category: 'domestic', supportsApiKey: true },\n 'volcengine-ark': { name: 'Volcengine Ark', category: 'domestic', supportsApiKey: true },\n 'volcengine-plan': { name: 'Volcengine Doubao Coding Plan', category: 'domestic', supportsApiKey: true },\n 'byteplus-plan': { name: 'BytePlus Doubao Coding Plan', category: 'domestic', supportsApiKey: true },\n 'stepfun': { name: 'StepFun', category: 'domestic', supportsApiKey: true },\n 'stepfun-cn': { name: 'StepFun China', category: 'domestic', supportsApiKey: true },\n 'stepfun-intl': { name: 'StepFun International', category: 'domestic', supportsApiKey: true },\n 'stepfun-plan': { name: 'StepFun Step Plan', category: 'domestic', supportsApiKey: true },\n 'stepfun-plan-cn': { name: 'StepFun Step Plan China', category: 'domestic', supportsApiKey: true },\n 'stepfun-plan-intl': { name: 'StepFun Step Plan International', category: 'domestic', supportsApiKey: true },\n 'ant-ling': { name: 'Ant Ling', category: 'domestic', supportsApiKey: true },\n 'zhipu-cn': { name: 'Zhipu GLM (China)', category: 'domestic', supportsApiKey: true },\n 'zai-coding-cn': { name: 'Zhipu GLM Coding Plan (China)', category: 'domestic', supportsApiKey: true },\n 'zai-coding-global': { name: 'Zhipu GLM Coding Plan (International)', category: 'domestic', supportsApiKey: true },\n 'zhipu-coding-cn': { name: 'Zhipu GLM Coding Plan (China)', category: 'domestic', supportsApiKey: true },\n /** International GLM (api.z.ai). Auth: API key (ZAI_API_KEY); no published OAuth for this HTTP API. */\n 'zai': { name: 'Zhipu GLM (International · z.ai)', category: 'domestic', supportsApiKey: true },\n 'amazon-bedrock': { name: 'Amazon Bedrock', category: 'enterprise', supportsApiKey: true },\n 'azure-openai-responses': { name: 'Azure OpenAI', category: 'enterprise', supportsApiKey: true },\n 'google-vertex': { name: 'Google Vertex AI', category: 'enterprise', supportsApiKey: true },\n 'vercel-ai-gateway': { name: 'Vercel AI Gateway', category: 'enterprise', supportsApiKey: true },\n 'github-copilot': { name: 'GitHub Copilot (OAuth)', category: 'oauth', supportsOAuth: true, supportsApiKey: false },\n 'openai-codex': { name: 'OpenAI Codex (OAuth)', category: 'oauth', supportsOAuth: true, supportsApiKey: false },\n 'google-gemini-cli': { name: 'Google Gemini CLI (OAuth)', category: 'oauth', supportsOAuth: true, supportsApiKey: false },\n 'google-antigravity': { name: 'Google Antigravity (OAuth)', category: 'oauth', supportsOAuth: true, supportsApiKey: false },\n};\n\nexport function getSortedProviders(): string[] {\n const all = getAllProviders();\n const catOrder: Record<ProviderCategory, number> = {\n common: 0,\n domestic: 1,\n specialty: 2,\n enterprise: 3,\n oauth: 4,\n extension: 5,\n };\n const pluginRegistry = getProviderRegistry();\n\n return [...all].sort((a, b) => {\n const catA = pluginRegistry.has(a) ? 'extension' : (PROVIDER_META[a]?.category ?? 'specialty');\n const catB = pluginRegistry.has(b) ? 'extension' : (PROVIDER_META[b]?.category ?? 'specialty');\n if (catOrder[catA] !== catOrder[catB]) {\n return catOrder[catA] - catOrder[catB];\n }\n return a.localeCompare(b);\n });\n}\n\nexport function getProviderDisplayName(provider: string): string {\n const plugin = getProviderRegistry().get(provider);\n if (plugin) return plugin.name;\n return PROVIDER_META[provider]?.name || provider;\n}\n\nexport function providerSupportsOAuth(provider: string): boolean {\n return PROVIDER_META[provider]?.supportsOAuth ?? false;\n}\n\nexport function providerSupportsApiKey(provider: string): boolean {\n return PROVIDER_META[provider]?.supportsApiKey ?? true;\n}\n\n// ============================================\n// Dynamic Default Model Resolution\n// ============================================\n\n/**\n * Get a default model reference.\n * Priority:\n * 1. Effective model inherited from the global default preset / agent presets / agent override\n * 2. Empty string only when no default model is present in the loaded config\n */\nexport async function getDefaultModel(config?: Config | null | undefined): Promise<string> {\n const modelRef = config ? getAgentDefaultModelRef(config) : undefined;\n if (modelRef) {\n const availableModels = await getAvailableModels();\n const configured = availableModels.find(m =>\n `${m.provider}/${m.id}` === modelRef ||\n m.id === modelRef\n );\n if (configured) {\n return `${configured.provider}/${configured.id}`;\n }\n return modelRef;\n }\n\n return '';\n}\n\n/**\n * Synchronous default model resolution for constructors and sync code paths.\n * Uses catalog/registry only (no async credential checks).\n *\n * When no model is present in the loaded config, returns an empty string so\n * setup flows can prompt for the global default model.\n */\nexport function getDefaultModelSync(config?: Config | null | undefined): string {\n const modelRef = config ? getAgentDefaultModelRef(config) : undefined;\n if (modelRef) {\n return modelRef;\n }\n\n return '';\n}\n\n// Re-export ModelRegistry for advanced use cases\nexport { ModelRegistry, getModelRegistry, resetModelRegistry, prewarmModelRegistry } from './model-registry.js';\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA8BA,SAAS,uBAAuB,OAA+B;AAC9D,KAAI,MAAM,aAAa,kBAAkB,MAAM,QAAQ,yBACtD,QAAO;EAAE,GAAG;EAAO,SAAS;EAAiC;AAE9D,QAAO;;;AAIR,SAAgB,mBAAmB,YAAoB,YAAiD;AACvG,QAAO;EACN,UAAU;EACV,IAAI,WAAW;EACf,MAAM,WAAW;EACjB,KAAK;EACL,SAAS;EACT,WAAW;EACX,OAAO,WAAW,iBAAkB,CAAC,QAAQ,QAAQ,GAA6B,CAAC,OAAO;EAC1F,eAAe,W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-ai/compat';
|
|
2
|
+
import type { CredentialResolverOptions } from '../auth/credentials.js';
|
|
3
|
+
export declare function isLocalModelBaseUrl(baseUrl: string | undefined): boolean;
|
|
4
|
+
/** Codex Responses rejects the temperature request parameter. */
|
|
5
|
+
export declare function supportsModelTemperature(model: Model<Api>): boolean;
|
|
6
|
+
export declare function resolveModelCallApiKey(model: Model<Api>, credentialOptions?: CredentialResolverOptions): Promise<string | undefined>;
|
|
7
|
+
export declare function resolveModelCallOptions(model: Model<Api>, options?: SimpleStreamOptions, credentialOptions?: CredentialResolverOptions): Promise<SimpleStreamOptions>;
|
|
8
|
+
/**
|
|
9
|
+
* Complete a one-shot request with xopc credential resolution and extension-provider routing.
|
|
10
|
+
*/
|
|
11
|
+
export declare function completeWithResolvedCredentials(model: Model<Api>, context: Context, options?: SimpleStreamOptions, credentialOptions?: CredentialResolverOptions): Promise<AssistantMessage>;
|
|
12
|
+
/**
|
|
13
|
+
* Start a model stream with xopc credential resolution and extension-provider routing.
|
|
14
|
+
* Callers that need live visible output should consume the returned stream before calling
|
|
15
|
+
* its `result()` method.
|
|
16
|
+
*/
|
|
17
|
+
export declare function createResolvedModelStream(model: Model<Api>, context: Context, options?: SimpleStreamOptions, credentialOptions?: CredentialResolverOptions): Promise<import("@earendil-works/pi-ai/compat").AssistantMessageEventStream>;
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
import { init_constants } from "./constants.js";
|
|
2
|
+
import { getApiKey, init_providers } from "./index.js";
|
|
3
|
+
import { createExtensionAwareStreamFn } from "./extension-stream-bridge.js";
|
|
4
|
+
import { complete } from "@earendil-works/pi-ai/compat";
|
|
5
|
+
//#region src/providers/model-call.ts
|
|
6
|
+
init_constants();
|
|
7
|
+
init_providers();
|
|
8
|
+
function isLocalModelBaseUrl(baseUrl) {
|
|
9
|
+
if (!baseUrl) return false;
|
|
10
|
+
try {
|
|
11
|
+
const host = new URL(baseUrl).hostname.toLowerCase();
|
|
12
|
+
return host === "localhost" || host === "127.0.0.1" || host === "::1" || host === "[::1]" || host.startsWith("127.") || host.startsWith("10.") || host.startsWith("192.168.") || /^172\.(1[6-9]|2\d|3[0-1])\./.test(host);
|
|
13
|
+
} catch {
|
|
14
|
+
return false;
|
|
15
|
+
}
|
|
16
|
+
}
|
|
17
|
+
/** Codex Responses rejects the temperature request parameter. */
|
|
18
|
+
function supportsModelTemperature(model) {
|
|
19
|
+
return model.api !== "openai-codex-responses";
|
|
20
|
+
}
|
|
21
|
+
async function resolveModelCallApiKey(model, credentialOptions) {
|
|
22
|
+
try {
|
|
23
|
+
const apiKey = credentialOptions ? await getApiKey(model.provider, credentialOptions) : await getApiKey(model.provider);
|
|
24
|
+
if (apiKey) return apiKey;
|
|
25
|
+
} catch {
|
|
26
|
+
if (!isLocalModelBaseUrl(model.baseUrl)) throw new Error(`Could not load credentials for provider: ${model.provider}`);
|
|
27
|
+
}
|
|
28
|
+
return isLocalModelBaseUrl(model.baseUrl) ? "xopc-local" : void 0;
|
|
29
|
+
}
|
|
30
|
+
async function resolveModelCallOptions(model, options = {}, credentialOptions) {
|
|
31
|
+
const apiKey = options.apiKey ?? await resolveModelCallApiKey(model, credentialOptions);
|
|
32
|
+
if (!apiKey) throw new Error(`No API key for provider: ${model.provider}`);
|
|
33
|
+
const { temperature, ...rest } = options;
|
|
34
|
+
return {
|
|
35
|
+
...rest,
|
|
36
|
+
apiKey,
|
|
37
|
+
...temperature !== void 0 && supportsModelTemperature(model) ? { temperature } : {}
|
|
38
|
+
};
|
|
39
|
+
}
|
|
40
|
+
/**
|
|
41
|
+
* Complete a one-shot request with xopc credential resolution and extension-provider routing.
|
|
42
|
+
*/
|
|
43
|
+
async function completeWithResolvedCredentials(model, context, options = {}, credentialOptions) {
|
|
44
|
+
const resolvedOptions = await resolveModelCallOptions(model, options, credentialOptions);
|
|
45
|
+
if (model.baseUrl === "extension://provider-plugin") return await (await createExtensionAwareStreamFn()(model, context, resolvedOptions)).result();
|
|
46
|
+
return await complete(model, context, resolvedOptions);
|
|
47
|
+
}
|
|
48
|
+
/**
|
|
49
|
+
* Start a model stream with xopc credential resolution and extension-provider routing.
|
|
50
|
+
* Callers that need live visible output should consume the returned stream before calling
|
|
51
|
+
* its `result()` method.
|
|
52
|
+
*/
|
|
53
|
+
async function createResolvedModelStream(model, context, options = {}, credentialOptions) {
|
|
54
|
+
const resolvedOptions = await resolveModelCallOptions(model, options, credentialOptions);
|
|
55
|
+
return await createExtensionAwareStreamFn()(model, context, resolvedOptions);
|
|
56
|
+
}
|
|
57
|
+
//#endregion
|
|
58
|
+
export { completeWithResolvedCredentials, createResolvedModelStream, isLocalModelBaseUrl, resolveModelCallApiKey, resolveModelCallOptions, supportsModelTemperature };
|
|
59
|
+
|
|
60
|
+
//# sourceMappingURL=model-call.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"model-call.js","names":[],"sources":["../../../src/providers/model-call.ts"],"sourcesContent":["import {\n complete,\n type Api,\n type AssistantMessage,\n type Context,\n type Model,\n type SimpleStreamOptions,\n} from '@earendil-works/pi-ai/compat';\n\nimport type { CredentialResolverOptions } from '../auth/credentials.js';\nimport { EXTENSION_PROVIDER_BASE_URL } from './constants.js';\nimport { getApiKey } from './index.js';\nimport { createExtensionAwareStreamFn } from './extension-stream-bridge.js';\n\nexport function isLocalModelBaseUrl(baseUrl: string | undefined): boolean {\n if (!baseUrl) return false;\n try {\n const url = new URL(baseUrl);\n const host = url.hostname.toLowerCase();\n return (\n host === 'localhost' ||\n host === '127.0.0.1' ||\n host === '::1' ||\n host === '[::1]' ||\n host.startsWith('127.') ||\n host.startsWith('10.') ||\n host.startsWith('192.168.') ||\n /^172\\.(1[6-9]|2\\d|3[0-1])\\./.test(host)\n );\n } catch {\n return false;\n }\n}\n\n/** Codex Responses rejects the temperature request parameter. */\nexport function supportsModelTemperature(model: Model<Api>): boolean {\n return model.api !== 'openai-codex-responses';\n}\n\nexport async function resolveModelCallApiKey(\n model: Model<Api>,\n credentialOptions?: CredentialResolverOptions,\n): Promise<string | undefined> {\n try {\n const apiKey = credentialOptions\n ? await getApiKey(model.provider, credentialOptions)\n : await getApiKey(model.provider);\n if (apiKey) return apiKey;\n } catch {\n if (!isLocalModelBaseUrl(model.baseUrl)) throw new Error(`Could not load credentials for provider: ${model.provider}`);\n }\n\n return isLocalModelBaseUrl(model.baseUrl) ? 'xopc-local' : undefined;\n}\n\nexport async function resolveModelCallOptions(\n model: Model<Api>,\n options: SimpleStreamOptions = {},\n credentialOptions?: CredentialResolverOptions,\n): Promise<SimpleStreamOptions> {\n const apiKey = options.apiKey ?? await resolveModelCallApiKey(model, credentialOptions);\n if (!apiKey) {\n throw new Error(`No API key for provider: ${model.provider}`);\n }\n\n const { temperature, ...rest } = options;\n return {\n ...rest,\n apiKey,\n ...(temperature !== undefined && supportsModelTemperature(model) ? { temperature } : {}),\n };\n}\n\n/**\n * Complete a one-shot request with xopc credential resolution and extension-provider routing.\n */\nexport async function completeWithResolvedCredentials(\n model: Model<Api>,\n context: Context,\n options: SimpleStreamOptions = {},\n credentialOptions?: CredentialResolverOptions,\n): Promise<AssistantMessage> {\n const resolvedOptions = await resolveModelCallOptions(model, options, credentialOptions);\n if (model.baseUrl === EXTENSION_PROVIDER_BASE_URL) {\n const stream = await createExtensionAwareStreamFn()(model, context, resolvedOptions);\n return await stream.result();\n }\n return await complete(model, context, resolvedOptions as never);\n}\n\n/**\n * Start a model stream with xopc credential resolution and extension-provider routing.\n * Callers that need live visible output should consume the returned stream before calling\n * its `result()` method.\n */\nexport async function createResolvedModelStream(\n model: Model<Api>,\n context: Context,\n options: SimpleStreamOptions = {},\n credentialOptions?: CredentialResolverOptions,\n) {\n const resolvedOptions = await resolveModelCallOptions(model, options, credentialOptions);\n return await createExtensionAwareStreamFn()(model, context, resolvedOptions);\n}\n"],"mappings":";;;;;gBAU6D;gBACtB;AAGvC,SAAgB,oBAAoB,SAAsC;AACxE,KAAI,CAAC,QAAS,QAAO;AACrB,KAAI;EAEF,MAAM,OAAO,I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M,wBAAwB,OAAO,SAAS,kBAAkB;AACxF,QAAO,MAAM,8BAA8B,CAAC,OAAO,SAAS,gBAAgB"}
|
|
@@ -3,10 +3,10 @@ import { init_logger } from "../utils/logger.js";
|
|
|
3
3
|
import { isCronSessionKey } from "../routing/session-key-utils.js";
|
|
4
4
|
import { init_session_key, parseSessionKey } from "../routing/session-key.js";
|
|
5
5
|
import { init_providers, resolveModel } from "../providers/index.js";
|
|
6
|
+
import { completeWithResolvedCredentials } from "../providers/model-call.js";
|
|
6
7
|
import { readAgentMessageContent } from "../agent/memory/agent-message-access.js";
|
|
7
8
|
import { stripSessionStartupContextFromUserText } from "../agent/reply/startup-context.js";
|
|
8
9
|
import { stripEnvelopeTimestampPrefix } from "../channels/envelope-timestamp.js";
|
|
9
|
-
import { complete } from "@earendil-works/pi-ai/compat";
|
|
10
10
|
//#region src/session/session-title.ts
|
|
11
11
|
init_session_key();
|
|
12
12
|
init_providers();
|
|
@@ -150,7 +150,7 @@ Title:`,
|
|
|
150
150
|
timestamp: Date.now()
|
|
151
151
|
};
|
|
152
152
|
try {
|
|
153
|
-
const result = await
|
|
153
|
+
const result = await completeWithResolvedCredentials(model, { messages: [userMsg] }, {
|
|
154
154
|
maxTokens: 64,
|
|
155
155
|
temperature: .35,
|
|
156
156
|
signal
|