@xopcai/xopc 0.0.106 → 0.0.108
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/dashscope/xopc.extension.json +7 -2
- package/dist/extensions/fal/xopc.extension.json +7 -2
- package/dist/extensions/feishu/src/adapters/gateway-setup.js +22 -26
- package/dist/extensions/feishu/src/adapters/gateway-setup.js.map +1 -1
- package/dist/extensions/feishu/xopc.extension.json +458 -26
- package/dist/extensions/google/xopc.extension.json +7 -2
- package/dist/extensions/minimax/xopc.extension.json +8 -2
- package/dist/extensions/openai/xopc.extension.json +7 -2
- package/dist/extensions/telegram/xopc.extension.json +10 -2
- package/dist/extensions/weixin/xopc.extension.json +57 -14
- package/dist/gateway/static/root/apple-touch-icon.png +0 -0
- package/dist/gateway/static/root/assets/agents-56kCGHdV.js +78 -0
- package/dist/gateway/static/root/assets/apps-page-Dd88J47r.js +1 -0
- package/dist/gateway/static/root/assets/channels-settings-Ckyvnvml.js +1 -0
- package/dist/gateway/static/root/assets/cron-page-DKo2ZdRA.js +1 -0
- package/dist/gateway/static/root/assets/{dist-OM9qGfm5.js → dist-dmxWdtPG.js} +1 -1
- package/dist/gateway/static/root/assets/{extension-debug-page-D-WHrr_w.js → extension-debug-page-iGpG-vpp.js} +1 -1
- package/dist/gateway/static/root/assets/{extension-page-CCgjSoKn.js → extension-page-I7-3uHiD.js} +1 -1
- package/dist/gateway/static/root/assets/{extension-settings-page-BJH5a-Gn.js → extension-settings-page-BisnHG7r.js} +1 -1
- package/dist/gateway/static/root/assets/{fetch-CkvRO30i.js → fetch-CFdKBnE6.js} +1 -1
- package/dist/gateway/static/root/assets/{gateway-startup-retry-BkKyRDrF.js → gateway-startup-retry-DdngdObI.js} +1 -1
- package/dist/gateway/static/root/assets/{heartbeat-config-api-CVyP6pFj.js → heartbeat-config-api-tbWAFPN8.js} +1 -1
- package/dist/gateway/static/root/assets/index-DI5_GsZt.css +1 -0
- package/dist/gateway/static/root/assets/index-slwUkhxH.js +4845 -0
- package/dist/gateway/static/root/assets/{logs-page-R6Vv_Ja6.js → logs-page-CCZiXrWu.js} +2 -2
- package/dist/gateway/static/root/assets/{note-detail-page-BUDarLhh.js → note-detail-page-BYbw2GLl.js} +4 -4
- package/dist/gateway/static/root/assets/{note-time-Cc2-T21g.js → note-time-Cya72Lte.js} +1 -1
- package/dist/gateway/static/root/assets/notes-page-DrAO7VRK.js +1 -0
- package/dist/gateway/static/root/assets/{schema-form-CrlOmEZt.js → schema-form-a6UJCK55.js} +1 -1
- package/dist/gateway/static/root/assets/sessions-page-DNU3Ymvz.js +1 -0
- package/dist/gateway/static/root/assets/{settings-advanced-gate-BBAQxxew.js → settings-advanced-gate-CyEJYTbw.js} +1 -1
- package/dist/gateway/static/root/assets/{settings-form-section-DjPD-ErC.js → settings-form-section-DpHo2ecA.js} +1 -1
- package/dist/gateway/static/root/assets/settings-page-YRwe4q56.js +3 -0
- package/dist/gateway/static/root/assets/{share-preview-page-BjvPht3V.js → share-preview-page-B7rf4QB4.js} +1 -1
- package/dist/gateway/static/root/assets/skills-page-we1NAt7u.js +2 -0
- package/dist/gateway/static/root/assets/{theme-store-DYgVdRB4.js → theme-store-BZozwAeK.js} +1 -1
- package/dist/gateway/static/root/assets/url-DQRqHuL-.js +3 -0
- package/dist/gateway/static/root/assets/voice-api-key-field-Btagks_B.js +1 -0
- package/dist/gateway/static/root/assets/{workflow-page.utils-D4sqR0yX.js → workflow-page.utils-DvzJKs6W.js} +1 -1
- package/dist/gateway/static/root/assets/workflows-page-BgOAgCOG.js +18 -0
- package/dist/gateway/static/root/favicon-16.png +0 -0
- package/dist/gateway/static/root/favicon-32.png +0 -0
- package/dist/gateway/static/root/favicon.ico +0 -0
- package/dist/gateway/static/root/favicon.svg +18 -0
- package/dist/gateway/static/root/index.html +11 -10
- package/dist/package.js +1 -1
- package/dist/src/agent/skills/marketplace/adapters/store/store-api-client.d.ts +4 -0
- package/dist/src/agent/skills/marketplace/adapters/store/store-api-client.js +4 -2
- package/dist/src/agent/skills/marketplace/adapters/store/store-api-client.js.map +1 -1
- package/dist/src/agent/starter-agents.d.ts +19 -0
- package/dist/src/agent/starter-agents.js +190 -0
- package/dist/src/agent/starter-agents.js.map +1 -0
- package/dist/src/agent/workflow/runtime.js +49 -15
- package/dist/src/agent/workflow/runtime.js.map +1 -1
- package/dist/src/agent/workflow/types.d.ts +11 -0
- package/dist/src/channels/catalog/channel-catalog-service.js +13 -0
- package/dist/src/channels/catalog/channel-catalog-service.js.map +1 -1
- package/dist/src/channels/plugins/types.adapters.d.ts +2 -0
- package/dist/src/cli/commands/extension-create.d.ts +2 -0
- package/dist/src/cli/commands/extension-create.js +165 -0
- package/dist/src/cli/commands/extension-create.js.map +1 -0
- package/dist/src/cli/commands/extension-dev.js +0 -2
- package/dist/src/cli/commands/extension-dev.js.map +1 -1
- package/dist/src/cli/commands/extension-marketplace.js +104 -80
- package/dist/src/cli/commands/extension-marketplace.js.map +1 -1
- package/dist/src/cli/commands/extension-pack.d.ts +13 -0
- package/dist/src/cli/commands/extension-pack.js +159 -91
- package/dist/src/cli/commands/extension-pack.js.map +1 -1
- package/dist/src/cli/commands/extension.d.ts +2 -0
- package/dist/src/cli/commands/extension.js +375 -3
- package/dist/src/cli/commands/extension.js.map +1 -1
- package/dist/src/cli/commands/gateway/run-foreground.js +1 -2
- package/dist/src/cli/commands/gateway/run-foreground.js.map +1 -1
- package/dist/src/cli/commands/onboard.js +0 -2
- package/dist/src/cli/commands/onboard.js.map +1 -1
- package/dist/src/cli/commands/setup.js +0 -2
- package/dist/src/cli/commands/setup.js.map +1 -1
- package/dist/src/cli/utils/init-workspace-core.js +9 -6
- package/dist/src/cli/utils/init-workspace-core.js.map +1 -1
- package/dist/src/config/paths.d.ts +2 -2
- package/dist/src/config/paths.js +10 -6
- package/dist/src/config/paths.js.map +1 -1
- package/dist/src/config/schema.d.ts +2 -0
- package/dist/src/config/schema.js +3 -1
- package/dist/src/config/schema.js.map +1 -1
- package/dist/src/extensions/api.d.ts +4 -2
- package/dist/src/extensions/api.js +31 -12
- package/dist/src/extensions/api.js.map +1 -1
- package/dist/src/extensions/discover-extensions.js +1 -0
- package/dist/src/extensions/discover-extensions.js.map +1 -1
- package/dist/src/extensions/install.d.ts +1 -0
- package/dist/src/extensions/install.js +51 -8
- package/dist/src/extensions/install.js.map +1 -1
- package/dist/src/extensions/loader.d.ts +0 -4
- package/dist/src/extensions/loader.js +54 -87
- package/dist/src/extensions/loader.js.map +1 -1
- package/dist/src/extensions/lockfile.d.ts +9 -1
- package/dist/src/extensions/lockfile.js.map +1 -1
- package/dist/src/extensions/normalize-manifest.js +20 -4
- package/dist/src/extensions/normalize-manifest.js.map +1 -1
- package/dist/src/extensions/package-contract.d.ts +12 -0
- package/dist/src/extensions/package-contract.js +59 -0
- package/dist/src/extensions/package-contract.js.map +1 -0
- package/dist/src/extensions/sdk/core.d.ts +1 -1
- package/dist/src/extensions/sdk/index.d.ts +1 -1
- package/dist/src/extensions/sdk/index.js.map +1 -1
- package/dist/src/extensions/types/manifest.d.ts +15 -0
- package/dist/src/gateway/agents-admin.d.ts +0 -8
- package/dist/src/gateway/agents-admin.js +1 -26
- package/dist/src/gateway/agents-admin.js.map +1 -1
- package/dist/src/gateway/hono/routes/agents.js +1 -55
- package/dist/src/gateway/hono/routes/agents.js.map +1 -1
- package/dist/src/gateway/hono/routes/channels.js +10 -1
- package/dist/src/gateway/hono/routes/channels.js.map +1 -1
- package/dist/src/gateway/hono/routes/workflows.js +130 -0
- package/dist/src/gateway/hono/routes/workflows.js.map +1 -1
- package/dist/src/gateway/service.d.ts +2 -0
- package/dist/src/gateway/service.js +44 -0
- package/dist/src/gateway/service.js.map +1 -1
- package/dist/src/notes/agent-context.d.ts +12 -4
- package/dist/src/notes/agent-context.js.map +1 -1
- package/dist/src/tui/backends/embedded-backend.js +0 -7
- package/dist/src/tui/backends/embedded-backend.js.map +1 -1
- package/dist/src/tui/backends/gateway-sse-backend.js +0 -7
- package/dist/src/tui/backends/gateway-sse-backend.js.map +1 -1
- package/dist/src/tui/tui-backend.d.ts +0 -1
- package/dist/src/tui/tui-commands.js +1 -1
- package/dist/src/tui/tui-commands.js.map +1 -1
- package/dist/src/tui/tui-picker-overlay.js +1 -1
- package/dist/src/tui/tui-picker-overlay.js.map +1 -1
- package/dist/src/workflows/domain/definition-utils.d.ts +1 -0
- package/dist/src/workflows/domain/definition-utils.js +32 -2
- package/dist/src/workflows/domain/definition-utils.js.map +1 -1
- package/dist/src/workflows/domain/definition.d.ts +2 -0
- package/dist/src/workflows/domain/event.d.ts +2 -1
- package/dist/src/workflows/domain/index.d.ts +1 -0
- package/dist/src/workflows/domain/index.js +3 -2
- package/dist/src/workflows/domain/run.d.ts +27 -1
- package/dist/src/workflows/domain/run.js.map +1 -1
- package/dist/src/workflows/domain/schema-validation.d.ts +8 -0
- package/dist/src/workflows/domain/schema-validation.js +28 -0
- package/dist/src/workflows/domain/schema-validation.js.map +1 -0
- package/dist/src/workflows/draft/index.d.ts +3 -0
- package/dist/src/workflows/draft/index.js +3 -0
- package/dist/src/workflows/draft/workflow-draft-prompt.d.ts +23 -0
- package/dist/src/workflows/draft/workflow-draft-prompt.js +98 -0
- package/dist/src/workflows/draft/workflow-draft-prompt.js.map +1 -0
- package/dist/src/workflows/draft/workflow-draft-service.d.ts +12 -0
- package/dist/src/workflows/draft/workflow-draft-service.js +131 -0
- package/dist/src/workflows/draft/workflow-draft-service.js.map +1 -0
- package/dist/src/workflows/draft/workflow-draft-validator.d.ts +4 -0
- package/dist/src/workflows/draft/workflow-draft-validator.js +133 -0
- package/dist/src/workflows/draft/workflow-draft-validator.js.map +1 -0
- package/dist/src/workflows/draft/workflow-draft.types.d.ts +44 -0
- package/dist/src/workflows/draft/workflow-draft.types.js +1 -0
- package/dist/src/workflows/engine/projector.js +1 -0
- package/dist/src/workflows/engine/projector.js.map +1 -1
- package/dist/src/workflows/engine/workflow-engine.d.ts +18 -0
- package/dist/src/workflows/engine/workflow-engine.js +320 -11
- package/dist/src/workflows/engine/workflow-engine.js.map +1 -1
- package/dist/src/workflows/index.js +4 -3
- package/dist/src/workflows/service/workflow-run-service.d.ts +14 -3
- package/dist/src/workflows/service/workflow-run-service.js +227 -6
- package/dist/src/workflows/service/workflow-run-service.js.map +1 -1
- package/dist/src/workflows/service/workflow-run-service.types.d.ts +7 -2
- package/package.json +4 -2
- package/dist/gateway/static/root/assets/agents-3eP0vqFO.js +0 -396
- package/dist/gateway/static/root/assets/apps-page-CZ2ZKrko.js +0 -1
- package/dist/gateway/static/root/assets/channels-settings-BbETa93K.js +0 -1
- package/dist/gateway/static/root/assets/cron-page-DCtUkHMu.js +0 -1
- package/dist/gateway/static/root/assets/index-BPYKW7FB.css +0 -1
- package/dist/gateway/static/root/assets/index-CEZxETzw.js +0 -4845
- package/dist/gateway/static/root/assets/notes-page-EAHl16bq.js +0 -1
- package/dist/gateway/static/root/assets/sessions-page-Ce_xuuSB.js +0 -1
- package/dist/gateway/static/root/assets/settings-page-KhQ9QgH0.js +0 -3
- package/dist/gateway/static/root/assets/skills-page-C0laq7l1.js +0 -2
- package/dist/gateway/static/root/assets/url-DPEStU4M.js +0 -3
- package/dist/gateway/static/root/assets/voice-api-key-field-DeGckWkl.js +0 -1
- package/dist/gateway/static/root/assets/workflows-page-DFjM95g5.js +0 -27
- package/dist/src/agent/builtin-agent-ids.d.ts +0 -2
- package/dist/src/agent/builtin-agent-ids.js +0 -17
- package/dist/src/agent/builtin-agent-ids.js.map +0 -1
|
@@ -0,0 +1,190 @@
|
|
|
1
|
+
import { init_agent_scope, listAgentEntries, normalizeAgentId, resolveAgentProfileDir, resolveAgentWorkspaceDir } from "./agent-scope.js";
|
|
2
|
+
import { WORKSPACE_FILES, init_paths } from "../config/paths.js";
|
|
3
|
+
import { applyAgentConfig } from "../commands/agents.config.js";
|
|
4
|
+
import { existsSync, mkdirSync, writeFileSync } from "node:fs";
|
|
5
|
+
import { join } from "node:path";
|
|
6
|
+
//#region src/agent/starter-agents.ts
|
|
7
|
+
init_paths();
|
|
8
|
+
init_agent_scope();
|
|
9
|
+
const STARTER_AGENTS_INITIALIZED_VERSION = 1;
|
|
10
|
+
function identity(params) {
|
|
11
|
+
return `# IDENTITY.md - Who Am I?\n\n- **Name:** ${params.name}\n- **Description:** ${params.description}\n- **Language:** en\n- **Creature:** ${params.creature}\n- **Emoji:** ${params.emoji}\n- **Avatar:**\n`;
|
|
12
|
+
}
|
|
13
|
+
const STARTER_AGENTS = [
|
|
14
|
+
{
|
|
15
|
+
id: "main",
|
|
16
|
+
displayName: "Main",
|
|
17
|
+
description: "General-purpose personal assistant.",
|
|
18
|
+
emoji: "✨",
|
|
19
|
+
profileFiles: {
|
|
20
|
+
[WORKSPACE_FILES.IDENTITY]: identity({
|
|
21
|
+
name: "Main",
|
|
22
|
+
description: "General-purpose personal assistant.",
|
|
23
|
+
creature: "assistant",
|
|
24
|
+
emoji: "✨"
|
|
25
|
+
}),
|
|
26
|
+
[WORKSPACE_FILES.SOUL]: `# SOUL.md - Main\n\nYou are a helpful personal AI assistant. Adapt to the user's intent, keep responses practical, and use tools when they clearly help.\n`,
|
|
27
|
+
[WORKSPACE_FILES.TOOLS]: `# TOOLS.md - Main Tool Policy\n\n- Use tools when they materially improve the answer.\n- Prefer safe inspection before changing files or external state.\n- Ask before destructive actions.\n`
|
|
28
|
+
}
|
|
29
|
+
},
|
|
30
|
+
{
|
|
31
|
+
id: "coder",
|
|
32
|
+
displayName: "Coder",
|
|
33
|
+
description: "Software development, debugging, refactoring, and tests.",
|
|
34
|
+
emoji: "💻",
|
|
35
|
+
tools: { disable: [
|
|
36
|
+
"image_generate",
|
|
37
|
+
"send_message",
|
|
38
|
+
"send_media",
|
|
39
|
+
"cronjob"
|
|
40
|
+
] },
|
|
41
|
+
profileFiles: {
|
|
42
|
+
[WORKSPACE_FILES.IDENTITY]: identity({
|
|
43
|
+
name: "Coder",
|
|
44
|
+
description: "Software development, debugging, refactoring, and tests.",
|
|
45
|
+
creature: "software engineer",
|
|
46
|
+
emoji: "💻"
|
|
47
|
+
}),
|
|
48
|
+
[WORKSPACE_FILES.SOUL]: `# SOUL.md - Coder\n\nYou are a software engineering agent. Understand the codebase, make focused changes, and verify behavior.\n\n## Workflow\n\n1. Read relevant files before proposing or editing code.\n2. Follow existing architecture, naming, and test style.\n3. Keep changes scoped to the requested behavior.\n4. Run the smallest meaningful verification.\n5. Report changed files, tests, and remaining risk.\n\n## Boundaries\n\n- Ask before destructive filesystem or git operations.\n- Do not send messages or media on the user's behalf.\n- Do not generate images for coding tasks.\n`,
|
|
49
|
+
[WORKSPACE_FILES.TOOLS]: `# TOOLS.md - Coder Tool Policy\n\n- Use grep, find, list_dir, and read_file to understand code first.\n- Use edit_file or write_file only after the target change is clear.\n- Use shell for tests, type checks, builds, and safe inspection commands.\n- Use web_search or web_fetch only for current external docs or APIs.\n- Do not use send_message, send_media, cronjob, or image_generate.\n`
|
|
50
|
+
}
|
|
51
|
+
},
|
|
52
|
+
{
|
|
53
|
+
id: "writer",
|
|
54
|
+
displayName: "Writer",
|
|
55
|
+
description: "Drafting, editing, rewriting, and audience-aware content.",
|
|
56
|
+
emoji: "✍️",
|
|
57
|
+
tools: { disable: [
|
|
58
|
+
"shell",
|
|
59
|
+
"browser_use",
|
|
60
|
+
"send_message",
|
|
61
|
+
"send_media",
|
|
62
|
+
"cronjob",
|
|
63
|
+
"bundle-mcp"
|
|
64
|
+
] },
|
|
65
|
+
profileFiles: {
|
|
66
|
+
[WORKSPACE_FILES.IDENTITY]: identity({
|
|
67
|
+
name: "Writer",
|
|
68
|
+
description: "Drafting, editing, rewriting, and audience-aware content.",
|
|
69
|
+
creature: "editor",
|
|
70
|
+
emoji: "✍️"
|
|
71
|
+
}),
|
|
72
|
+
[WORKSPACE_FILES.SOUL]: `# SOUL.md - Writer\n\nYou are a writing and editing agent. Improve clarity, structure, voice, and usefulness.\n\n## Workflow\n\n1. Identify audience, purpose, channel, and tone.\n2. Propose structure before long-form writing.\n3. Preserve the user's intent and voice unless asked to change it.\n4. Cut filler and vague claims.\n5. Mark assumptions, missing facts, and placeholders.\n\n## Boundaries\n\n- Do not run shell commands.\n- Do not control browsers.\n- Do not send drafts externally.\n`,
|
|
73
|
+
[WORKSPACE_FILES.TOOLS]: `# TOOLS.md - Writer Tool Policy\n\n- Use read_file to inspect source material.\n- Use write_file or edit_file only when the user asks to save or revise a document.\n- Use web_search and web_fetch for fact checks and source-backed writing.\n- Do not use shell, browser_use, send_message, send_media, cronjob, or bundle-mcp.\n`
|
|
74
|
+
}
|
|
75
|
+
},
|
|
76
|
+
{
|
|
77
|
+
id: "researcher",
|
|
78
|
+
displayName: "Researcher",
|
|
79
|
+
description: "Deep research, source comparison, and fact synthesis.",
|
|
80
|
+
emoji: "🔍",
|
|
81
|
+
tools: { disable: [
|
|
82
|
+
"shell",
|
|
83
|
+
"write_file",
|
|
84
|
+
"edit_file",
|
|
85
|
+
"send_message",
|
|
86
|
+
"send_media",
|
|
87
|
+
"cronjob"
|
|
88
|
+
] },
|
|
89
|
+
profileFiles: {
|
|
90
|
+
[WORKSPACE_FILES.IDENTITY]: identity({
|
|
91
|
+
name: "Researcher",
|
|
92
|
+
description: "Deep research, source comparison, and fact synthesis.",
|
|
93
|
+
creature: "analyst",
|
|
94
|
+
emoji: "🔍"
|
|
95
|
+
}),
|
|
96
|
+
[WORKSPACE_FILES.SOUL]: `# SOUL.md - Researcher\n\nYou are a research agent. Find reliable evidence, compare sources, and produce careful synthesis.\n\n## Workflow\n\n1. Clarify the research question and decision context.\n2. Start broad, then move to primary sources.\n3. Prefer official docs, papers, filings, standards, datasets, and first-party statements.\n4. Cross-check important claims.\n5. Separate facts, source-backed claims, inference, and opinion.\n\n## Boundaries\n\n- Do not edit local files unless asked to save a report.\n- Do not run shell commands.\n- Do not send findings externally.\n`,
|
|
97
|
+
[WORKSPACE_FILES.TOOLS]: `# TOOLS.md - Researcher Tool Policy\n\n- Use web_search to map the topic and find candidate sources.\n- Use web_fetch for primary sources and source excerpts.\n- Use browser_use only when a page requires interaction.\n- Use read_file when the user provides local source material.\n- Do not use shell, write_file, edit_file, send_message, send_media, or cronjob.\n`
|
|
98
|
+
}
|
|
99
|
+
},
|
|
100
|
+
{
|
|
101
|
+
id: "data-analyst",
|
|
102
|
+
displayName: "Data Analyst",
|
|
103
|
+
description: "Data cleaning, analysis, visualization, and reproducible reports.",
|
|
104
|
+
emoji: "📊",
|
|
105
|
+
tools: { disable: [
|
|
106
|
+
"browser_use",
|
|
107
|
+
"send_message",
|
|
108
|
+
"send_media",
|
|
109
|
+
"cronjob"
|
|
110
|
+
] },
|
|
111
|
+
profileFiles: {
|
|
112
|
+
[WORKSPACE_FILES.IDENTITY]: identity({
|
|
113
|
+
name: "Data Analyst",
|
|
114
|
+
description: "Data cleaning, analysis, visualization, and reproducible reports.",
|
|
115
|
+
creature: "data analyst",
|
|
116
|
+
emoji: "📊"
|
|
117
|
+
}),
|
|
118
|
+
[WORKSPACE_FILES.SOUL]: `# SOUL.md - Data Analyst\n\nYou are a data analysis agent. Inspect data, explain assumptions, and produce reproducible analysis.\n\n## Workflow\n\n1. Inspect schema, sample rows, missing values, and units.\n2. State assumptions before drawing conclusions.\n3. Use reproducible commands or scripts for calculations.\n4. Prefer clear tables and charts over verbose prose.\n5. Highlight data quality issues and uncertainty.\n\n## Boundaries\n\n- Do not control browsers by default.\n- Do not send results externally.\n- Do not schedule cron jobs without explicit user intent.\n`,
|
|
119
|
+
[WORKSPACE_FILES.TOOLS]: `# TOOLS.md - Data Analyst Tool Policy\n\n- Use read_file, list_dir, grep, and find to inspect datasets and notes.\n- Use shell for reproducible analysis commands and scripts.\n- Use write_file or edit_file for notebooks, scripts, cleaned data, and reports.\n- Use web_fetch or web_search only when external data or documentation is needed.\n- Do not use browser_use, send_message, send_media, or cronjob.\n`
|
|
120
|
+
}
|
|
121
|
+
},
|
|
122
|
+
{
|
|
123
|
+
id: "creative",
|
|
124
|
+
displayName: "Creative",
|
|
125
|
+
description: "Visual direction, image prompts, design critique, and creative options.",
|
|
126
|
+
emoji: "🎨",
|
|
127
|
+
tools: { disable: [
|
|
128
|
+
"shell",
|
|
129
|
+
"send_message",
|
|
130
|
+
"send_media",
|
|
131
|
+
"cronjob"
|
|
132
|
+
] },
|
|
133
|
+
profileFiles: {
|
|
134
|
+
[WORKSPACE_FILES.IDENTITY]: identity({
|
|
135
|
+
name: "Creative",
|
|
136
|
+
description: "Visual direction, image prompts, design critique, and creative options.",
|
|
137
|
+
creature: "creative director",
|
|
138
|
+
emoji: "🎨"
|
|
139
|
+
}),
|
|
140
|
+
[WORKSPACE_FILES.SOUL]: `# SOUL.md - Creative\n\nYou are a creative design agent. Explore visual directions, produce strong options, and explain design tradeoffs.\n\n## Workflow\n\n1. Identify audience, medium, constraints, and taste direction.\n2. Offer distinct creative directions when the brief is open.\n3. Explain why each direction works.\n4. Respect accessibility, brand constraints, and production limits.\n5. Iterate concretely from user feedback.\n\n## Boundaries\n\n- Do not run shell commands.\n- Do not send creative work externally.\n- Do not schedule cron jobs.\n`,
|
|
141
|
+
[WORKSPACE_FILES.TOOLS]: `# TOOLS.md - Creative Tool Policy\n\n- Use image_generate when the user wants visual options or assets.\n- Use image to inspect user-provided images.\n- Use web_search and web_fetch for references, style research, or current product visuals.\n- Use write_file or edit_file to save prompts, design specs, or copy.\n- Do not use shell, send_message, send_media, or cronjob.\n`
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
];
|
|
145
|
+
function hasAgentEntry(cfg, agentId) {
|
|
146
|
+
const id = normalizeAgentId(agentId);
|
|
147
|
+
return listAgentEntries(cfg).some((entry) => normalizeAgentId(entry.id) === id);
|
|
148
|
+
}
|
|
149
|
+
function writeFileIfMissing(path, content) {
|
|
150
|
+
if (!existsSync(path)) writeFileSync(path, content, "utf-8");
|
|
151
|
+
}
|
|
152
|
+
function materializeStarterAgentFiles(cfg) {
|
|
153
|
+
for (const starter of STARTER_AGENTS) {
|
|
154
|
+
const profileDir = resolveAgentProfileDir(cfg, starter.id);
|
|
155
|
+
const workspaceDir = resolveAgentWorkspaceDir(cfg, starter.id);
|
|
156
|
+
mkdirSync(profileDir, { recursive: true });
|
|
157
|
+
mkdirSync(workspaceDir, { recursive: true });
|
|
158
|
+
for (const [name, content] of Object.entries(starter.profileFiles)) writeFileIfMissing(join(profileDir, name), content);
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
function ensureStarterAgentsInitialized(cfg) {
|
|
162
|
+
if ((cfg.agents?.starterAgentsInitializedVersion ?? 0) >= 1) return {
|
|
163
|
+
config: cfg,
|
|
164
|
+
changed: false
|
|
165
|
+
};
|
|
166
|
+
let next = cfg;
|
|
167
|
+
for (const starter of STARTER_AGENTS) {
|
|
168
|
+
if (hasAgentEntry(next, starter.id)) continue;
|
|
169
|
+
next = applyAgentConfig(next, {
|
|
170
|
+
agentId: starter.id,
|
|
171
|
+
...starter.tools ? { tools: starter.tools } : {}
|
|
172
|
+
});
|
|
173
|
+
}
|
|
174
|
+
next = {
|
|
175
|
+
...next,
|
|
176
|
+
agents: {
|
|
177
|
+
...next.agents,
|
|
178
|
+
starterAgentsInitializedVersion: 1
|
|
179
|
+
}
|
|
180
|
+
};
|
|
181
|
+
materializeStarterAgentFiles(next);
|
|
182
|
+
return {
|
|
183
|
+
config: next,
|
|
184
|
+
changed: next !== cfg
|
|
185
|
+
};
|
|
186
|
+
}
|
|
187
|
+
//#endregion
|
|
188
|
+
export { STARTER_AGENTS, STARTER_AGENTS_INITIALIZED_VERSION, ensureStarterAgentsInitialized, materializeStarterAgentFiles };
|
|
189
|
+
|
|
190
|
+
//# sourceMappingURL=starter-agents.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"starter-agents.js","names":[],"sources":["../../../src/agent/starter-agents.ts"],"sourcesContent":["import { existsSync, mkdirSync, writeFileSync } from 'node:fs';\nimport { join } from 'node:path';\n\nimport type { Config } from '../config/schema.js';\nimport { WORKSPACE_FILES } from '../config/paths.js';\nimport { applyAgentConfig, listAgentEntries } from '../commands/agents.config.js';\nimport {\n normalizeAgentId,\n resolveAgentProfileDir,\n resolveAgentWorkspaceDir,\n} from './agent-scope.js';\n\nexport const STARTER_AGENTS_INITIALIZED_VERSION = 1;\n\ntype StarterAgent = {\n id: string;\n displayName: string;\n description: string;\n emoji: string;\n tools?: { disable?: string[] };\n profileFiles: Record<string, string>;\n};\n\nfunction identity(params: { name: string; description: string; creature: string; emoji: string }): string {\n return `# IDENTITY.md - Who Am I?\\n\\n- **Name:** ${params.name}\\n- **Description:** ${params.description}\\n- **Language:** en\\n- **Creature:** ${params.creature}\\n- **Emoji:** ${params.emoji}\\n- **Avatar:**\\n`;\n}\n\nexport const STARTER_AGENTS: readonly StarterAgent[] = [\n {\n id: 'main',\n displayName: 'Main',\n description: 'General-purpose personal assistant.',\n emoji: '✨',\n profileFiles: {\n [WORKSPACE_FILES.IDENTITY]: identity({\n name: 'Main',\n description: 'General-purpose personal assistant.',\n creature: 'assistant',\n emoji: '✨',\n }),\n [WORKSPACE_FILES.SOUL]: `# SOUL.md - Main\\n\\nYou are a helpful personal AI assistant. Adapt to the user's intent, keep responses practical, and use tools when they clearly help.\\n`,\n [WORKSPACE_FILES.TOOLS]: `# TOOLS.md - Main Tool Policy\\n\\n- Use tools when they materially improve the answer.\\n- Prefer safe inspection before changing files or external state.\\n- Ask before destructive actions.\\n`,\n },\n },\n {\n id: 'coder',\n displayName: 'Coder',\n description: 'Software development, debugging, refactoring, and tests.',\n emoji: '💻',\n tools: { disable: ['image_generate', 'send_message', 'send_media', 'cronjob'] },\n profileFiles: {\n [WORKSPACE_FILES.IDENTITY]: identity({\n name: 'Coder',\n description: 'Software development, debugging, refactoring, and tests.',\n creature: 'software engineer',\n emoji: '💻',\n }),\n [WORKSPACE_FILES.SOUL]: `# SOUL.md - Coder\\n\\nYou are a software engineering agent. Understand the codebase, make focused changes, and verify behavior.\\n\\n## Workflow\\n\\n1. Read relevant files before proposing or editing code.\\n2. Follow existing architecture, naming, and test style.\\n3. Keep changes scoped to the requested behavior.\\n4. Run the smallest meaningful verification.\\n5. Report changed files, tests, and remaining risk.\\n\\n## Boundaries\\n\\n- Ask before destructive filesystem or git operations.\\n- Do not send messages or media on the user's behalf.\\n- Do not generate images for coding tasks.\\n`,\n [WORKSPACE_FILES.TOOLS]: `# TOOLS.md - Coder Tool Policy\\n\\n- Use grep, find, list_dir, and read_file to understand code first.\\n- Use edit_file or write_file only after the target change is clear.\\n- Use shell for tests, type checks, builds, and safe inspection commands.\\n- Use web_search or web_fetch only for current external docs or APIs.\\n- Do not use send_message, send_media, cronjob, or image_generate.\\n`,\n },\n },\n {\n id: 'writer',\n displayName: 'Writer',\n description: 'Drafting, editing, rewriting, and audience-aware content.',\n emoji: '✍️',\n tools: { disable: ['shell', 'browser_use', 'send_message', 'send_media', 'cronjob', 'bundle-mcp'] },\n profileFiles: {\n [WORKSPACE_FILES.IDENTITY]: identity({\n name: 'Writer',\n description: 'Drafting, editing, rewriting, and audience-aware content.',\n creature: 'editor',\n emoji: '✍️',\n }),\n [WORKSPACE_FILES.SOUL]: `# SOUL.md - Writer\\n\\nYou are a writing and editing agent. Improve clarity, structure, voice, and usefulness.\\n\\n## Workflow\\n\\n1. Identify audience, purpose, channel, and tone.\\n2. Propose structure before long-form writing.\\n3. Preserve the user's intent and voice unless asked to change it.\\n4. Cut filler and vague claims.\\n5. Mark assumptions, missing facts, and placeholders.\\n\\n## Boundaries\\n\\n- Do not run shell commands.\\n- Do not control browsers.\\n- Do not send drafts externally.\\n`,\n [WORKSPACE_FILES.TOOLS]: `# TOOLS.md - Writer Tool Policy\\n\\n- Use read_file to inspect source material.\\n- Use write_file or edit_file only when the user asks to save or revise a document.\\n- Use web_search and web_fetch for fact checks and source-backed writing.\\n- Do not use shell, browser_use, send_message, send_media, cronjob, or bundle-mcp.\\n`,\n },\n },\n {\n id: 'researcher',\n displayName: 'Researcher',\n description: 'Deep research, source comparison, and fact synthesis.',\n emoji: '🔍',\n tools: { disable: ['shell', 'write_file', 'edit_file', 'send_message', 'send_media', 'cronjob'] },\n profileFiles: {\n [WORKSPACE_FILES.IDENTITY]: identity({\n name: 'Researcher',\n description: 'Deep research, source comparison, and fact synthesis.',\n creature: 'analyst',\n emoji: '🔍',\n }),\n [WORKSPACE_FILES.SOUL]: `# SOUL.md - Researcher\\n\\nYou are a research agent. Find reliable evidence, compare sources, and produce careful synthesis.\\n\\n## Workflow\\n\\n1. Clarify the research question and decision context.\\n2. Start broad, then move to primary sources.\\n3. Prefer official docs, papers, filings, standards, datasets, and first-party statements.\\n4. Cross-check important claims.\\n5. Separate facts, source-backed claims, inference, and opinion.\\n\\n## Boundaries\\n\\n- Do not edit local files unless asked to save a report.\\n- Do not run shell commands.\\n- Do not send findings externally.\\n`,\n [WORKSPACE_FILES.TOOLS]: `# TOOLS.md - Researcher Tool Policy\\n\\n- Use web_search to map the topic and find candidate sources.\\n- Use web_fetch for primary sources and source excerpts.\\n- Use browser_use only when a page requires interaction.\\n- Use read_file when the user provides local source material.\\n- Do not use shell, write_file, edit_file, send_message, send_media, or cronjob.\\n`,\n },\n },\n {\n id: 'data-analyst',\n displayName: 'Data Analyst',\n description: 'Data cleaning, analysis, visualization, and reproducible reports.',\n emoji: '📊',\n tools: { disable: ['browser_use', 'send_message', 'send_media', 'cronjob'] },\n profileFiles: {\n [WORKSPACE_FILES.IDENTITY]: identity({\n name: 'Data Analyst',\n description: 'Data cleaning, analysis, visualization, and reproducible reports.',\n creature: 'data analyst',\n emoji: '📊',\n }),\n [WORKSPACE_FILES.SOUL]: `# SOUL.md - Data Analyst\\n\\nYou are a data analysis agent. Inspect data, explain assumptions, and produce reproducible analysis.\\n\\n## Workflow\\n\\n1. Inspect schema, sample rows, missing values, and units.\\n2. State assumptions before drawing conclusions.\\n3. Use reproducible commands or scripts for calculations.\\n4. Prefer clear tables and charts over verbose prose.\\n5. Highlight data quality issues and uncertainty.\\n\\n## Boundaries\\n\\n- Do not control browsers by default.\\n- Do not send results externally.\\n- Do not schedule cron jobs without explicit user intent.\\n`,\n [WORKSPACE_FILES.TOOLS]: `# TOOLS.md - Data Analyst Tool Policy\\n\\n- Use read_file, list_dir, grep, and find to inspect datasets and notes.\\n- Use shell for reproducible analysis commands and scripts.\\n- Use write_file or edit_file for notebooks, scripts, cleaned data, and reports.\\n- Use web_fetch or web_search only when external data or documentation is needed.\\n- Do not use browser_use, send_message, send_media, or cronjob.\\n`,\n },\n },\n {\n id: 'creative',\n displayName: 'Creative',\n description: 'Visual direction, image prompts, design critique, and creative options.',\n emoji: '🎨',\n tools: { disable: ['shell', 'send_message', 'send_media', 'cronjob'] },\n profileFiles: {\n [WORKSPACE_FILES.IDENTITY]: identity({\n name: 'Creative',\n description: 'Visual direction, image prompts, design critique, and creative options.',\n creature: 'creative director',\n emoji: '🎨',\n }),\n [WORKSPACE_FILES.SOUL]: `# SOUL.md - Creative\\n\\nYou are a creative design agent. Explore visual directions, produce strong options, and explain design tradeoffs.\\n\\n## Workflow\\n\\n1. Identify audience, medium, constraints, and taste direction.\\n2. Offer distinct creative directions when the brief is open.\\n3. Explain why each direction works.\\n4. Respect accessibility, brand constraints, and production limits.\\n5. Iterate concretely from user feedback.\\n\\n## Boundaries\\n\\n- Do not run shell commands.\\n- Do not send creative work externally.\\n- Do not schedule cron jobs.\\n`,\n [WORKSPACE_FILES.TOOLS]: `# TOOLS.md - Creative Tool Policy\\n\\n- Use image_generate when the user wants visual options or assets.\\n- Use image to inspect user-provided images.\\n- Use web_search and web_fetch for references, style research, or current product visuals.\\n- Use write_file or edit_file to save prompts, design specs, or copy.\\n- Do not use shell, send_message, send_media, or cronjob.\\n`,\n },\n },\n];\n\nfunction hasAgentEntry(cfg: Config, agentId: string): boolean {\n const id = normalizeAgentId(agentId);\n return listAgentEntries(cfg).some((entry) => normalizeAgentId(entry.id) === id);\n}\n\nfunction writeFileIfMissing(path: string, content: string): void {\n if (!existsSync(path)) {\n writeFileSync(path, content, 'utf-8');\n }\n}\n\nexport function materializeStarterAgentFiles(cfg: Config): void {\n for (const starter of STARTER_AGENTS) {\n const profileDir = resolveAgentProfileDir(cfg, starter.id);\n const workspaceDir = resolveAgentWorkspaceDir(cfg, starter.id);\n mkdirSync(profileDir, { recursive: true });\n mkdirSync(workspaceDir, { recursive: true });\n for (const [name, content] of Object.entries(starter.profileFiles)) {\n writeFileIfMissing(join(profileDir, name), content);\n }\n }\n}\n\nexport function ensureStarterAgentsInitialized(cfg: Config): { config: Config; changed: boolean } {\n if ((cfg.agents?.starterAgentsInitializedVersion ?? 0) >= STARTER_AGENTS_INITIALIZED_VERSION) {\n return { config: cfg, changed: false };\n }\n\n let next = cfg;\n for (const starter of STARTER_AGENTS) {\n if (hasAgentEntry(next, starter.id)) continue;\n next = applyAgentConfig(next, {\n agentId: starter.id,\n ...(starter.tools ? { tools: starter.tools } : {}),\n });\n }\n\n next = {\n ...next,\n agents: {\n ...next.agents,\n starterAgentsInitializedVersion: STARTER_AGENTS_INITIALIZED_VERSION,\n },\n };\n\n materializeStarterAgentFiles(next);\n return { config: next, changed: next !== cfg };\n}\n"],"mappings":";;;;;;YAIqD;kBAM3B;AAE1B,MAAa,qCAAqC;AAWlD,SAAS,SAAS,QAAwF;AACxG,QAAO,4CAA4C,OAAO,KAAK,uBAAuB,OAAO,YAAY,wCAAwC,OAAO,SAAS,iBAAiB,OAAO,MAAM;;AAGjM,MAAa,iBAA0C;CACrD;EACE,IAAI;EACJ,aAAa;EACb,aAAa;EACb,OAAO;EACP,cAAc;IACX,gBAAgB,WAAW,SAAS;IACnC,MAAM;IACN,aAAa;IACb,UAAU;IACV,OAAO;IACR,CAAC;IACD,gBAAgB,OAAO;IACvB,gBAAgB,QAAQ;GAC1B;EACF;CACD;EACE,IAAI;EACJ,aAAa;EACb,aAAa;EACb,OAAO;EACP,OAAO,EAAE,SAAS;GAAC;GAAkB;GAAgB;GAAc;GAAU,EAAE;EAC/E,cAAc;IACX,gBAAgB,W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;AACpC,QAAO,iBAAiB,IAAI,CAAC,MAAM,UAAU,iBAAiB,MAAM,GAAG,KAAK,GAAG;;AAGjF,SAAS,mBAAmB,MAAc,SAAuB;AAC/D,KAAI,CAAC,WAAW,KAAK,CACnB,eAAc,MAAM,SAAS,QAAQ;;AAIzC,SAAgB,6BAA6B,KAAmB;AAC9D,MAAK,MAAM,WAAW,gBAAgB;EACpC,MAAM,aAAa,uBAAuB,KAAK,QAAQ,GAAG;EAC1D,MAAM,eAAe,yBAAyB,KAAK,QAAQ,GAAG;AAC9D,YAAU,YAAY,EAAE,WAAW,MAAM,CAAC;AAC1C,YAAU,cAAc,EAAE,WAAW,MAAM,CAAC;AAC5C,OAAK,MAAM,CAAC,MAAM,YAAY,OAAO,QAAQ,QAAQ,aAAa,CAChE,oBAAmB,KAAK,YAAY,KAAK,EAAE,QAAQ;;;AAKzD,SAAgB,+BAA+B,KAAmD;AAChG,MAAK,IAAI,QAAQ,mCAAmC,MAAA,EAClD,QAAO;EAAE,QAAQ;EAAK,SAAS;EAAO;CAGxC,IAAI,OAAO;AACX,MAAK,MAAM,WAAW,gBAAgB;AACpC,MAAI,cAAc,MAAM,QAAQ,GAAG,CAAE;AACrC,SAAO,iBAAiB,MAAM;GAC5B,SAAS,QAAQ;GACjB,GAAI,QAAQ,QAAQ,EAAE,OAAO,QAAQ,OAAO,GAAG,EAAE;GAClD,CAAC;;AAGJ,QAAO;EACL,GAAG;EACH,QAAQ;GACN,GAAG,KAAK;GACR,iCAAA;GACD;EACF;AAED,8BAA6B,KAAK;AAClC,QAAO;EAAE,QAAQ;EAAM,SAAS,SAAS;EAAK"}
|
|
@@ -62,21 +62,24 @@ async function runWorkflow(script, deps, options) {
|
|
|
62
62
|
remaining: () => options.tokenBudget == null ? Number.POSITIVE_INFINITY : Math.max(0, options.tokenBudget - state.spent)
|
|
63
63
|
});
|
|
64
64
|
const throwIfAborted = () => {
|
|
65
|
-
if (options.signal?.aborted)
|
|
65
|
+
if (!options.signal?.aborted) return;
|
|
66
|
+
const reason = options.signal.reason;
|
|
67
|
+
if (reason instanceof Error) throw reason;
|
|
68
|
+
if (reason) throw new Error(String(reason));
|
|
69
|
+
throw new Error("workflow aborted");
|
|
66
70
|
};
|
|
67
|
-
const
|
|
68
|
-
const
|
|
69
|
-
if (
|
|
71
|
+
const resolveAgentModelSelection = (normalized, assignedPhase) => {
|
|
72
|
+
const modelRef = normalized.model?.trim() || (assignedPhase ? phaseDefaultModels.get(assignedPhase) : void 0);
|
|
73
|
+
if (modelRef) {
|
|
70
74
|
if (!deps.resolveModelId) throw new Error("workflow runtime missing resolveModelId; cannot resolve real model id");
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
return deps.resolveModelId(phaseRef);
|
|
78
|
-
}
|
|
75
|
+
const model = deps.resolveModelId(modelRef);
|
|
76
|
+
return {
|
|
77
|
+
modelRef,
|
|
78
|
+
resolvedModelRef: modelToRef(model),
|
|
79
|
+
model
|
|
80
|
+
};
|
|
79
81
|
}
|
|
82
|
+
return {};
|
|
80
83
|
};
|
|
81
84
|
const agent = async (prompt, agentOptions = {}) => {
|
|
82
85
|
throwIfAborted();
|
|
@@ -86,14 +89,23 @@ async function runWorkflow(script, deps, options) {
|
|
|
86
89
|
const normalized = normalizeAgentOptions(agentOptions);
|
|
87
90
|
const assignedPhase = normalized.phase ?? state.currentPhase;
|
|
88
91
|
const requestedLabel = normalized.label?.trim();
|
|
92
|
+
const modelSelection = resolveAgentModelSelection(normalized, assignedPhase);
|
|
89
93
|
state.agentCount += 1;
|
|
90
94
|
const id = state.agentCount;
|
|
91
95
|
const label = requestedLabel || defaultAgentLabel(assignedPhase, id);
|
|
96
|
+
const invocation = buildInvocationSnapshot({
|
|
97
|
+
prompt: taskPrompt,
|
|
98
|
+
label,
|
|
99
|
+
phase: assignedPhase,
|
|
100
|
+
normalized,
|
|
101
|
+
modelSelection
|
|
102
|
+
});
|
|
92
103
|
options.onAgentQueued?.({
|
|
93
104
|
id,
|
|
94
105
|
label,
|
|
95
106
|
phase: assignedPhase,
|
|
96
|
-
prompt: taskPrompt
|
|
107
|
+
prompt: taskPrompt,
|
|
108
|
+
invocation
|
|
97
109
|
});
|
|
98
110
|
const runPromise = limiter(async () => {
|
|
99
111
|
options.onAgentStart?.({
|
|
@@ -104,7 +116,6 @@ async function runWorkflow(script, deps, options) {
|
|
|
104
116
|
});
|
|
105
117
|
try {
|
|
106
118
|
throwIfAborted();
|
|
107
|
-
const resolvedModel = resolveAgentModel(normalized, assignedPhase);
|
|
108
119
|
const enhanced = options.enhanceSubagentRun?.({
|
|
109
120
|
id,
|
|
110
121
|
label,
|
|
@@ -118,7 +129,7 @@ async function runWorkflow(script, deps, options) {
|
|
|
118
129
|
maxIterations: normalized.maxIterations,
|
|
119
130
|
phase: assignedPhase,
|
|
120
131
|
signal: options.signal,
|
|
121
|
-
model:
|
|
132
|
+
model: modelSelection.model,
|
|
122
133
|
...enhanced
|
|
123
134
|
});
|
|
124
135
|
throwIfAborted();
|
|
@@ -299,6 +310,29 @@ function normalizeAgentOptions(value) {
|
|
|
299
310
|
maxIterations
|
|
300
311
|
};
|
|
301
312
|
}
|
|
313
|
+
function buildInvocationSnapshot(params) {
|
|
314
|
+
return compactObject({
|
|
315
|
+
prompt: params.prompt,
|
|
316
|
+
label: params.label,
|
|
317
|
+
phase: params.phase,
|
|
318
|
+
modelRef: params.modelSelection.modelRef,
|
|
319
|
+
resolvedModelRef: params.modelSelection.resolvedModelRef,
|
|
320
|
+
schema: cloneJsonValue(params.normalized.schema),
|
|
321
|
+
toolset: params.normalized.toolset ? [...params.normalized.toolset] : void 0,
|
|
322
|
+
maxIterations: params.normalized.maxIterations
|
|
323
|
+
});
|
|
324
|
+
}
|
|
325
|
+
function modelToRef(model) {
|
|
326
|
+
return `${model.provider}/${model.id}`;
|
|
327
|
+
}
|
|
328
|
+
function cloneJsonValue(value) {
|
|
329
|
+
if (value === void 0) return void 0;
|
|
330
|
+
return structuredClone(value);
|
|
331
|
+
}
|
|
332
|
+
function compactObject(value) {
|
|
333
|
+
for (const key of Object.keys(value)) if (value[key] === void 0) delete value[key];
|
|
334
|
+
return value;
|
|
335
|
+
}
|
|
302
336
|
function assertStructuredCloneable(value, name) {
|
|
303
337
|
try {
|
|
304
338
|
structuredClone(value);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"runtime.js","names":[],"sources":["../../../../src/agent/workflow/runtime.ts"],"sourcesContent":["/**\n * Sandboxed workflow runtime.\n *\n * Parses the script via {@link parseWorkflowScript} (which strips the `meta`\n * export), wraps the remaining body in an async IIFE, and runs it inside a\n * Node `vm` context with a curated set of globals:\n *\n * - `agent(prompt, opts)` — spawns a subagent through the injected\n * {@link SubagentRunner} and returns its result (string, or schema-validated\n * object). Failures resolve to `null`.\n * - `parallel(thunks)` — concurrent fan-out; thunks (not promises!) so the\n * limiter sees each agent() call.\n * - `pipeline(items, ...stages)` — per-item sequential stages, items run\n * concurrently (no stage barrier). Each stage receives\n * `(prevResult, originalItem, index)`. A stage that throws drops that item\n * to `null` and skips remaining stages.\n * - `phase(title)` — marks the current phase; surfaces through `onPhase`.\n * - `log(message)` — appends to the workflow log.\n * - `budget` — `{ total, spent(), remaining() }` for self-pacing scripts.\n * - `args`, `cwd`, `process.cwd()`.\n *\n * The runtime is the only code that touches `vm`. It exposes no IO surface,\n * carries no LLM dependency, and is fully driven by injected callbacks — that\n * means the workflow tool, tests, and any future runner share one runtime.\n */\n\nimport { availableParallelism } from 'node:os';\nimport { createContext, Script } from 'node:vm';\n\nimport type { Api, Model } from '@earendil-works/pi-ai';\n\nimport { parseWorkflowScript } from './parser.js';\nimport type {\n AgentScriptOptions,\n SubagentRunner,\n WorkflowMetaPhase,\n WorkflowRunOptions,\n WorkflowRunResult,\n WorkflowAgentStatus,\n} from './types.js';\n\nconst DEFAULT_CONCURRENCY_FLOOR = 1;\nconst DEFAULT_CONCURRENCY_CEILING = 16;\nconst DEFAULT_MAX_SUBAGENTS = 1000;\n\ninterface RuntimeState {\n currentPhase?: string;\n logs: string[];\n phases: string[];\n agentCount: number;\n spent: number;\n}\n\nexport interface RunWorkflowDeps {\n runner: SubagentRunner;\n /** Resolve a model ref (`provider/model` or configured typed id) to a {@link Model}. Throws on unknown ref. */\n resolveModelId?: (modelId: string) => Model<Api>;\n}\n\nexport async function runWorkflow<T = unknown>(\n script: string,\n deps: RunWorkflowDeps,\n options: WorkflowRunOptions,\n): Promise<WorkflowRunResult<T>> {\n const started = Date.now();\n const { meta, body } = parseWorkflowScript(script);\n\n const state: RuntimeState = { logs: [], phases: [], agentCount: 0, spent: 0 };\n const concurrency = clampConcurrency(options.concurrency);\n const maxSubagents = Math.max(1, options.maxSubagents ?? DEFAULT_MAX_SUBAGENTS);\n const limiter = createLimiter(concurrency);\n const pendingAgentRuns = new Set<Promise<unknown>>();\n const phaseDefaultModels = buildPhaseModelMap(meta.phases);\n\n const log = (message: unknown) => {\n const text = String(message);\n state.logs.push(text);\n options.onLog?.(text);\n };\n\n const phase = (title: unknown) => {\n const text = requireString(title, 'phase title');\n state.currentPhase = text;\n if (!state.phases.includes(text)) state.phases.push(text);\n options.onPhase?.(text);\n };\n\n const budget = Object.freeze({\n total: options.tokenBudget ?? null,\n spent: () => state.spent,\n remaining: () =>\n options.tokenBudget == null\n ? Number.POSITIVE_INFINITY\n : Math.max(0, options.tokenBudget - state.spent),\n });\n\n const throwIfAborted = () => {\n if (options.signal?.aborted) throw new Error('workflow aborted');\n };\n\n const resolveAgentModel = (\n normalized: AgentScriptOptions,\n assignedPhase: string | undefined,\n ): Model<Api> | undefined => {\n const realId = normalized.model?.trim();\n if (realId) {\n if (!deps.resolveModelId) {\n throw new Error('workflow runtime missing resolveModelId; cannot resolve real model id');\n }\n return deps.resolveModelId(realId);\n }\n if (assignedPhase) {\n const phaseRef = phaseDefaultModels.get(assignedPhase);\n if (phaseRef) {\n if (!deps.resolveModelId) return undefined;\n return deps.resolveModelId(phaseRef);\n }\n }\n return undefined;\n };\n\n const agent = async (prompt: unknown, agentOptions: unknown = {}) => {\n throwIfAborted();\n if (budget.total !== null && budget.remaining() <= 0) {\n throw new Error('workflow token budget exhausted');\n }\n if (state.agentCount >= maxSubagents) {\n throw new Error(`workflow agent quota exhausted (max ${maxSubagents})`);\n }\n\n const taskPrompt = requireString(prompt, 'agent prompt');\n const normalized = normalizeAgentOptions(agentOptions);\n const assignedPhase = normalized.phase ?? state.currentPhase;\n const requestedLabel = normalized.label?.trim();\n\n state.agentCount += 1;\n const id = state.agentCount;\n const label = requestedLabel || defaultAgentLabel(assignedPhase, id);\n options.onAgentQueued?.({ id, label, phase: assignedPhase, prompt: taskPrompt });\n\n const runPromise = limiter(async () => {\n options.onAgentStart?.({ id, label, phase: assignedPhase, prompt: taskPrompt });\n\n try {\n throwIfAborted();\n const resolvedModel = resolveAgentModel(normalized, assignedPhase);\n const enhanced = options.enhanceSubagentRun?.({\n id,\n label,\n phase: assignedPhase,\n prompt: taskPrompt,\n });\n const result = await deps.runner.run<unknown>(taskPrompt, {\n label,\n schema: normalized.schema,\n allowedToolNames: normalized.toolset,\n maxIterations: normalized.maxIterations,\n phase: assignedPhase,\n signal: options.signal,\n model: resolvedModel,\n ...enhanced,\n });\n throwIfAborted();\n\n const status: WorkflowAgentStatus = result === null ? 'error' : 'done';\n state.spent += estimateTokens(result);\n options.onAgentEnd?.({ id, label, phase: assignedPhase, result, status });\n return result;\n } catch (e) {\n if (options.signal?.aborted) {\n options.onAgentEnd?.({ id, label, phase: assignedPhase, result: null, status: 'skipped' });\n throw e;\n }\n const message = e instanceof Error ? e.message : String(e);\n log(`agent ${label} failed: ${message}`);\n options.onAgentEnd?.({ id, label, phase: assignedPhase, result: null, status: 'error' });\n return null;\n }\n });\n\n pendingAgentRuns.add(runPromise);\n // `then` (not `finally`) keeps the bookkeeping promise from re-throwing into\n // the unhandled-rejection channel when `runPromise` rejects on abort.\n runPromise.then(\n () => pendingAgentRuns.delete(runPromise),\n () => pendingAgentRuns.delete(runPromise),\n );\n return runPromise;\n };\n\n const parallel = async (thunks: unknown) => {\n throwIfAborted();\n if (!Array.isArray(thunks)) throw new TypeError('parallel() expects an array of functions');\n for (const t of thunks) {\n if (typeof t !== 'function') {\n throw new TypeError(\n 'parallel() expects an array of functions, not promises. Wrap each call: () => agent(...)',\n );\n }\n }\n return Promise.all(\n thunks.map(async (thunk, index) => {\n try {\n return await (thunk as () => unknown)();\n } catch (e) {\n if (options.signal?.aborted) throw e;\n const message = e instanceof Error ? e.message : String(e);\n log(`parallel[${index}] failed: ${message}`);\n return null;\n }\n }),\n );\n };\n\n const pipeline = async (items: unknown, ...stages: Array<unknown>) => {\n throwIfAborted();\n if (!Array.isArray(items)) {\n throw new TypeError('pipeline() expects an array as the first argument');\n }\n for (const stage of stages) {\n if (typeof stage !== 'function') {\n throw new TypeError(\n 'pipeline() stages must be functions: pipeline(items, item => ..., result => ...)',\n );\n }\n }\n const typedStages = stages as Array<\n (prev: unknown, original: unknown, index: number) => unknown\n >;\n return Promise.all(\n items.map(async (item, index) => {\n let value: unknown = item;\n for (const stage of typedStages) {\n try {\n throwIfAborted();\n value = await stage(value, item, index);\n throwIfAborted();\n } catch (e) {\n if (options.signal?.aborted) throw e;\n const message = e instanceof Error ? e.message : String(e);\n log(`pipeline[${index}] failed: ${message}`);\n return null;\n }\n }\n return value;\n }),\n );\n };\n\n const context = createContext({\n agent,\n parallel,\n pipeline,\n log,\n phase,\n args: options.args,\n cwd: options.cwd,\n process: Object.freeze({ cwd: () => options.cwd }),\n budget,\n console: {\n log,\n info: log,\n warn: (m: unknown) => log(`[warn] ${String(m)}`),\n error: (m: unknown) => log(`[error] ${String(m)}`),\n },\n JSON,\n Math,\n Array,\n Object,\n String,\n Number,\n Boolean,\n Set,\n Map,\n Promise,\n });\n\n const wrapped = `(async () => {\\n${body}\\n})()`;\n const script$ = new Script(wrapped, { filename: `${meta.name}.workflow.js` });\n\n let result: unknown;\n try {\n result = await script$.runInContext(context);\n // Wait for any agent() runs the script forgot to await before declaring success.\n await Promise.allSettled([...pendingAgentRuns]);\n } catch (e) {\n // Drain pending agent calls before propagating, so the snapshot reflects final state.\n await Promise.allSettled([...pendingAgentRuns]);\n throw rewriteScriptError(e);\n }\n\n assertStructuredCloneable(result, 'workflow result');\n\n return {\n meta,\n result: result as T,\n logs: state.logs,\n phases: state.phases,\n agentCount: state.agentCount,\n durationMs: Date.now() - started,\n };\n}\n\nexport { emptySnapshotFor } from './snapshot-empty.js';\n\n// ---------------------------------------------------------------------------\n// Internals\n// ---------------------------------------------------------------------------\n\nfunction clampConcurrency(requested?: number): number {\n if (typeof requested === 'number' && Number.isFinite(requested) && requested >= 1) {\n return Math.min(Math.floor(requested), DEFAULT_CONCURRENCY_CEILING);\n }\n let cpu = DEFAULT_CONCURRENCY_CEILING;\n try {\n cpu = availableParallelism();\n } catch {\n // Some sandboxes throw; fall back to the ceiling.\n }\n return Math.max(DEFAULT_CONCURRENCY_FLOOR, Math.min(DEFAULT_CONCURRENCY_CEILING, cpu - 2));\n}\n\nfunction createLimiter(limit: number) {\n let active = 0;\n const queue: Array<() => void> = [];\n const next = () => {\n active -= 1;\n const resume = queue.shift();\n if (resume) resume();\n };\n return async <T>(fn: () => Promise<T>): Promise<T> => {\n if (active >= limit) {\n await new Promise<void>((resolve) => queue.push(resolve));\n }\n active += 1;\n try {\n return await fn();\n } finally {\n next();\n }\n };\n}\n\nfunction buildPhaseModelMap(phases: WorkflowMetaPhase[] | undefined): Map<string, string> {\n const out = new Map<string, string>();\n if (!phases) return out;\n for (const p of phases) {\n if (p && typeof p.title === 'string' && typeof p.model === 'string' && p.model.trim()) {\n out.set(p.title, p.model.trim());\n }\n }\n return out;\n}\n\nfunction requireString(value: unknown, name: string): string {\n if (typeof value !== 'string') throw new TypeError(`${name} must be a string`);\n return value;\n}\n\nfunction optionalString(value: unknown, name: string): string | undefined {\n if (value === undefined) return undefined;\n return requireString(value, name);\n}\n\nfunction normalizeAgentOptions(value: unknown): AgentScriptOptions {\n if (value === undefined || value === null) return {};\n if (typeof value !== 'object') throw new TypeError('agent options must be an object');\n const options = value as AgentScriptOptions;\n const toolset = options.toolset;\n if (toolset !== undefined) {\n if (!Array.isArray(toolset) || toolset.some((t) => typeof t !== 'string')) {\n throw new TypeError('agent toolset must be an array of strings');\n }\n }\n const maxIterations = options.maxIterations;\n if (maxIterations !== undefined) {\n if (typeof maxIterations !== 'number' || !Number.isFinite(maxIterations) || maxIterations < 1) {\n throw new TypeError('agent maxIterations must be a positive number');\n }\n }\n const modelStr = optionalString(options.model, 'agent model');\n return {\n label: optionalString(options.label, 'agent label'),\n phase: optionalString(options.phase, 'agent phase'),\n schema: options.schema,\n model: modelStr,\n toolset,\n maxIterations,\n };\n}\n\nfunction assertStructuredCloneable(value: unknown, name: string): void {\n try {\n structuredClone(value);\n } catch (e) {\n const promisePath = findPromisePath(value, '');\n if (promisePath !== null) {\n throw new Error(\n `${name} contains a Promise at \\`${promisePath || '<root>'}\\` — missing 'await' before parallel()/pipeline()/agent(). ` +\n `Async return auto-unwraps a bare Promise, but a Promise nested in an object/array is returned as-is.`,\n );\n }\n const detail = e instanceof Error ? ` ${e.message}` : '';\n throw new Error(\n `${name} must be structured-cloneable; did you forget to await agent(), parallel(), or pipeline()?${detail}`,\n );\n }\n}\n\n/**\n * Find the first Promise lurking in `value`, returning a JS-path like\n * \"results[0].pending\". Returns null when no Promise is found. Bounded\n * depth/breadth so it never explodes on weird user shapes.\n */\nfunction findPromisePath(value: unknown, path: string, depth = 0): string | null {\n if (depth > 4) return null;\n if (isThenable(value)) return path;\n if (Array.isArray(value)) {\n for (let i = 0; i < Math.min(value.length, 32); i++) {\n const inner = findPromisePath(value[i], `${path}[${i}]`, depth + 1);\n if (inner !== null) return inner;\n }\n return null;\n }\n if (value !== null && typeof value === 'object') {\n let count = 0;\n for (const [key, child] of Object.entries(value as Record<string, unknown>)) {\n if (count++ > 32) break;\n const inner = findPromisePath(child, path ? `${path}.${key}` : key, depth + 1);\n if (inner !== null) return inner;\n }\n }\n return null;\n}\n\nfunction isThenable(value: unknown): boolean {\n return (\n value !== null &&\n typeof value === 'object' &&\n typeof (value as { then?: unknown }).then === 'function'\n );\n}\n\n/**\n * Rewrite TypeErrors that look like \"called .map on a Promise\" with an\n * await-shaped hint. Static lint catches the obvious form at parse time;\n * this is the safety net for cases lint can't see (dynamic indirection,\n * values stashed in helper closures).\n */\nconst PROMISE_METHOD_ERROR =\n /\\.(map|filter|forEach|flat|flatMap|find|some|every|reduce|join|length|then)\\b is not a function/;\n\nfunction rewriteScriptError(error: unknown): Error {\n // VM-context errors aren't `instanceof` host classes (the vm has its own\n // global constructors), so check by name + duck-typing message.\n const asError = error as { name?: string; message?: string } | null | undefined;\n const isTypeError = asError?.name === 'TypeError' && typeof asError.message === 'string';\n if (!isTypeError) {\n return error instanceof Error ? error : new Error(String(error));\n }\n const message = (asError as { message: string }).message;\n if (!PROMISE_METHOD_ERROR.test(message)) {\n return error instanceof Error ? error : new Error(message);\n }\n return new Error(\n `${message}\\n\\nHint: parallel()/pipeline()/agent() return a Promise — 'await' the call before using its result.\\n` +\n ` ❌ const r = parallel(...); r.map(...)\\n` +\n ` ✅ const r = await parallel(...); r.map(...)`,\n );\n}\n\nfunction defaultAgentLabel(phase: string | undefined, index: number): string {\n return phase ? `${phase} agent ${index}` : `agent ${index}`;\n}\n\nfunction estimateTokens(value: unknown): number {\n if (value === null || value === undefined) return 0;\n try {\n return Math.ceil(JSON.stringify(value).length / 4);\n } catch {\n return Math.ceil(String(value).length / 4);\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAyCA,MAAM,4BAA4B;AAClC,MAAM,8BAA8B;AACpC,MAAM,wBAAwB;AAgB9B,eAAsB,YACpB,QACA,MACA,SAC+B;CAC/B,MAAM,UAAU,KAAK,KAAK;CAC1B,MAAM,EAAE,MAAM,SAAS,oBAAoB,OAAO;CAElD,MAAM,QAAsB;EAAE,MAA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QAAQ,QAAQ,IAAI,MAAM,OAAO,MAAM,CAAC;CAElE,MAAM,UAAW,QAAgC;AACjD,KAAI,CAAC,qBAAqB,KAAK,QAAQ,CACrC,QAAO,iBAAiB,QAAQ,QAAQ,IAAI,MAAM,QAAQ;AAE5D,wBAAO,IAAI,MACT,GAAG,QAAQ,8LAGZ;;AAGH,SAAS,kBAAkB,OAA2B,OAAuB;AAC3E,QAAO,QAAQ,GAAG,MAAM,SAAS,UAAU,SAAS;;AAGtD,SAAS,eAAe,OAAwB;AAC9C,KAAI,UAAU,QAAQ,UAAU,KAAA,EAAW,QAAO;AAClD,KAAI;AACF,SAAO,KAAK,KAAK,KAAK,UAAU,MAAM,CAAC,SAAS,EAAE;SAC5C;AACN,SAAO,KAAK,KAAK,OAAO,MAAM,CAAC,SAAS,EAAE"}
|
|
1
|
+
{"version":3,"file":"runtime.js","names":[],"sources":["../../../../src/agent/workflow/runtime.ts"],"sourcesContent":["/**\n * Sandboxed workflow runtime.\n *\n * Parses the script via {@link parseWorkflowScript} (which strips the `meta`\n * export), wraps the remaining body in an async IIFE, and runs it inside a\n * Node `vm` context with a curated set of globals:\n *\n * - `agent(prompt, opts)` — spawns a subagent through the injected\n * {@link SubagentRunner} and returns its result (string, or schema-validated\n * object). Failures resolve to `null`.\n * - `parallel(thunks)` — concurrent fan-out; thunks (not promises!) so the\n * limiter sees each agent() call.\n * - `pipeline(items, ...stages)` — per-item sequential stages, items run\n * concurrently (no stage barrier). Each stage receives\n * `(prevResult, originalItem, index)`. A stage that throws drops that item\n * to `null` and skips remaining stages.\n * - `phase(title)` — marks the current phase; surfaces through `onPhase`.\n * - `log(message)` — appends to the workflow log.\n * - `budget` — `{ total, spent(), remaining() }` for self-pacing scripts.\n * - `args`, `cwd`, `process.cwd()`.\n *\n * The runtime is the only code that touches `vm`. It exposes no IO surface,\n * carries no LLM dependency, and is fully driven by injected callbacks — that\n * means the workflow tool, tests, and any future runner share one runtime.\n */\n\nimport { availableParallelism } from 'node:os';\nimport { createContext, Script } from 'node:vm';\n\nimport type { Api, Model } from '@earendil-works/pi-ai';\n\nimport { parseWorkflowScript } from './parser.js';\nimport type {\n AgentScriptOptions,\n SubagentRunner,\n WorkflowMetaPhase,\n WorkflowRunOptions,\n WorkflowRunResult,\n WorkflowAgentStatus,\n WorkflowAgentInvocationSnapshot,\n} from './types.js';\n\nconst DEFAULT_CONCURRENCY_FLOOR = 1;\nconst DEFAULT_CONCURRENCY_CEILING = 16;\nconst DEFAULT_MAX_SUBAGENTS = 1000;\n\ninterface RuntimeState {\n currentPhase?: string;\n logs: string[];\n phases: string[];\n agentCount: number;\n spent: number;\n}\n\nexport interface RunWorkflowDeps {\n runner: SubagentRunner;\n /** Resolve a model ref (`provider/model` or configured typed id) to a {@link Model}. Throws on unknown ref. */\n resolveModelId?: (modelId: string) => Model<Api>;\n}\n\nexport async function runWorkflow<T = unknown>(\n script: string,\n deps: RunWorkflowDeps,\n options: WorkflowRunOptions,\n): Promise<WorkflowRunResult<T>> {\n const started = Date.now();\n const { meta, body } = parseWorkflowScript(script);\n\n const state: RuntimeState = { logs: [], phases: [], agentCount: 0, spent: 0 };\n const concurrency = clampConcurrency(options.concurrency);\n const maxSubagents = Math.max(1, options.maxSubagents ?? DEFAULT_MAX_SUBAGENTS);\n const limiter = createLimiter(concurrency);\n const pendingAgentRuns = new Set<Promise<unknown>>();\n const phaseDefaultModels = buildPhaseModelMap(meta.phases);\n\n const log = (message: unknown) => {\n const text = String(message);\n state.logs.push(text);\n options.onLog?.(text);\n };\n\n const phase = (title: unknown) => {\n const text = requireString(title, 'phase title');\n state.currentPhase = text;\n if (!state.phases.includes(text)) state.phases.push(text);\n options.onPhase?.(text);\n };\n\n const budget = Object.freeze({\n total: options.tokenBudget ?? null,\n spent: () => state.spent,\n remaining: () =>\n options.tokenBudget == null\n ? Number.POSITIVE_INFINITY\n : Math.max(0, options.tokenBudget - state.spent),\n });\n\n const throwIfAborted = () => {\n if (!options.signal?.aborted) return;\n const reason = options.signal.reason;\n if (reason instanceof Error) throw reason;\n if (reason) throw new Error(String(reason));\n throw new Error('workflow aborted');\n };\n\n const resolveAgentModelSelection = (\n normalized: AgentScriptOptions,\n assignedPhase: string | undefined,\n ): { modelRef?: string; resolvedModelRef?: string; model?: Model<Api> } => {\n const modelRef = normalized.model?.trim() || (assignedPhase ? phaseDefaultModels.get(assignedPhase) : undefined);\n if (modelRef) {\n if (!deps.resolveModelId) {\n throw new Error('workflow runtime missing resolveModelId; cannot resolve real model id');\n }\n const model = deps.resolveModelId(modelRef);\n return { modelRef, resolvedModelRef: modelToRef(model), model };\n }\n return {};\n };\n\n const agent = async (prompt: unknown, agentOptions: unknown = {}) => {\n throwIfAborted();\n if (budget.total !== null && budget.remaining() <= 0) {\n throw new Error('workflow token budget exhausted');\n }\n if (state.agentCount >= maxSubagents) {\n throw new Error(`workflow agent quota exhausted (max ${maxSubagents})`);\n }\n\n const taskPrompt = requireString(prompt, 'agent prompt');\n const normalized = normalizeAgentOptions(agentOptions);\n const assignedPhase = normalized.phase ?? state.currentPhase;\n const requestedLabel = normalized.label?.trim();\n const modelSelection = resolveAgentModelSelection(normalized, assignedPhase);\n\n state.agentCount += 1;\n const id = state.agentCount;\n const label = requestedLabel || defaultAgentLabel(assignedPhase, id);\n const invocation = buildInvocationSnapshot({\n prompt: taskPrompt,\n label,\n phase: assignedPhase,\n normalized,\n modelSelection,\n });\n options.onAgentQueued?.({ id, label, phase: assignedPhase, prompt: taskPrompt, invocation });\n\n const runPromise = limiter(async () => {\n options.onAgentStart?.({ id, label, phase: assignedPhase, prompt: taskPrompt });\n\n try {\n throwIfAborted();\n const enhanced = options.enhanceSubagentRun?.({\n id,\n label,\n phase: assignedPhase,\n prompt: taskPrompt,\n });\n const result = await deps.runner.run<unknown>(taskPrompt, {\n label,\n schema: normalized.schema,\n allowedToolNames: normalized.toolset,\n maxIterations: normalized.maxIterations,\n phase: assignedPhase,\n signal: options.signal,\n model: modelSelection.model,\n ...enhanced,\n });\n throwIfAborted();\n\n const status: WorkflowAgentStatus = result === null ? 'error' : 'done';\n state.spent += estimateTokens(result);\n options.onAgentEnd?.({ id, label, phase: assignedPhase, result, status });\n return result;\n } catch (e) {\n if (options.signal?.aborted) {\n options.onAgentEnd?.({ id, label, phase: assignedPhase, result: null, status: 'skipped' });\n throw e;\n }\n const message = e instanceof Error ? e.message : String(e);\n log(`agent ${label} failed: ${message}`);\n options.onAgentEnd?.({ id, label, phase: assignedPhase, result: null, status: 'error' });\n return null;\n }\n });\n\n pendingAgentRuns.add(runPromise);\n // `then` (not `finally`) keeps the bookkeeping promise from re-throwing into\n // the unhandled-rejection channel when `runPromise` rejects on abort.\n runPromise.then(\n () => pendingAgentRuns.delete(runPromise),\n () => pendingAgentRuns.delete(runPromise),\n );\n return runPromise;\n };\n\n const parallel = async (thunks: unknown) => {\n throwIfAborted();\n if (!Array.isArray(thunks)) throw new TypeError('parallel() expects an array of functions');\n for (const t of thunks) {\n if (typeof t !== 'function') {\n throw new TypeError(\n 'parallel() expects an array of functions, not promises. Wrap each call: () => agent(...)',\n );\n }\n }\n return Promise.all(\n thunks.map(async (thunk, index) => {\n try {\n return await (thunk as () => unknown)();\n } catch (e) {\n if (options.signal?.aborted) throw e;\n const message = e instanceof Error ? e.message : String(e);\n log(`parallel[${index}] failed: ${message}`);\n return null;\n }\n }),\n );\n };\n\n const pipeline = async (items: unknown, ...stages: Array<unknown>) => {\n throwIfAborted();\n if (!Array.isArray(items)) {\n throw new TypeError('pipeline() expects an array as the first argument');\n }\n for (const stage of stages) {\n if (typeof stage !== 'function') {\n throw new TypeError(\n 'pipeline() stages must be functions: pipeline(items, item => ..., result => ...)',\n );\n }\n }\n const typedStages = stages as Array<\n (prev: unknown, original: unknown, index: number) => unknown\n >;\n return Promise.all(\n items.map(async (item, index) => {\n let value: unknown = item;\n for (const stage of typedStages) {\n try {\n throwIfAborted();\n value = await stage(value, item, index);\n throwIfAborted();\n } catch (e) {\n if (options.signal?.aborted) throw e;\n const message = e instanceof Error ? e.message : String(e);\n log(`pipeline[${index}] failed: ${message}`);\n return null;\n }\n }\n return value;\n }),\n );\n };\n\n const context = createContext({\n agent,\n parallel,\n pipeline,\n log,\n phase,\n args: options.args,\n cwd: options.cwd,\n process: Object.freeze({ cwd: () => options.cwd }),\n budget,\n console: {\n log,\n info: log,\n warn: (m: unknown) => log(`[warn] ${String(m)}`),\n error: (m: unknown) => log(`[error] ${String(m)}`),\n },\n JSON,\n Math,\n Array,\n Object,\n String,\n Number,\n Boolean,\n Set,\n Map,\n Promise,\n });\n\n const wrapped = `(async () => {\\n${body}\\n})()`;\n const script$ = new Script(wrapped, { filename: `${meta.name}.workflow.js` });\n\n let result: unknown;\n try {\n result = await script$.runInContext(context);\n // Wait for any agent() runs the script forgot to await before declaring success.\n await Promise.allSettled([...pendingAgentRuns]);\n } catch (e) {\n // Drain pending agent calls before propagating, so the snapshot reflects final state.\n await Promise.allSettled([...pendingAgentRuns]);\n throw rewriteScriptError(e);\n }\n\n assertStructuredCloneable(result, 'workflow result');\n\n return {\n meta,\n result: result as T,\n logs: state.logs,\n phases: state.phases,\n agentCount: state.agentCount,\n durationMs: Date.now() - started,\n };\n}\n\nexport { emptySnapshotFor } from './snapshot-empty.js';\n\n// ---------------------------------------------------------------------------\n// Internals\n// ---------------------------------------------------------------------------\n\nfunction clampConcurrency(requested?: number): number {\n if (typeof requested === 'number' && Number.isFinite(requested) && requested >= 1) {\n return Math.min(Math.floor(requested), DEFAULT_CONCURRENCY_CEILING);\n }\n let cpu = DEFAULT_CONCURRENCY_CEILING;\n try {\n cpu = availableParallelism();\n } catch {\n // Some sandboxes throw; fall back to the ceiling.\n }\n return Math.max(DEFAULT_CONCURRENCY_FLOOR, Math.min(DEFAULT_CONCURRENCY_CEILING, cpu - 2));\n}\n\nfunction createLimiter(limit: number) {\n let active = 0;\n const queue: Array<() => void> = [];\n const next = () => {\n active -= 1;\n const resume = queue.shift();\n if (resume) resume();\n };\n return async <T>(fn: () => Promise<T>): Promise<T> => {\n if (active >= limit) {\n await new Promise<void>((resolve) => queue.push(resolve));\n }\n active += 1;\n try {\n return await fn();\n } finally {\n next();\n }\n };\n}\n\nfunction buildPhaseModelMap(phases: WorkflowMetaPhase[] | undefined): Map<string, string> {\n const out = new Map<string, string>();\n if (!phases) return out;\n for (const p of phases) {\n if (p && typeof p.title === 'string' && typeof p.model === 'string' && p.model.trim()) {\n out.set(p.title, p.model.trim());\n }\n }\n return out;\n}\n\nfunction requireString(value: unknown, name: string): string {\n if (typeof value !== 'string') throw new TypeError(`${name} must be a string`);\n return value;\n}\n\nfunction optionalString(value: unknown, name: string): string | undefined {\n if (value === undefined) return undefined;\n return requireString(value, name);\n}\n\nfunction normalizeAgentOptions(value: unknown): AgentScriptOptions {\n if (value === undefined || value === null) return {};\n if (typeof value !== 'object') throw new TypeError('agent options must be an object');\n const options = value as AgentScriptOptions;\n const toolset = options.toolset;\n if (toolset !== undefined) {\n if (!Array.isArray(toolset) || toolset.some((t) => typeof t !== 'string')) {\n throw new TypeError('agent toolset must be an array of strings');\n }\n }\n const maxIterations = options.maxIterations;\n if (maxIterations !== undefined) {\n if (typeof maxIterations !== 'number' || !Number.isFinite(maxIterations) || maxIterations < 1) {\n throw new TypeError('agent maxIterations must be a positive number');\n }\n }\n const modelStr = optionalString(options.model, 'agent model');\n return {\n label: optionalString(options.label, 'agent label'),\n phase: optionalString(options.phase, 'agent phase'),\n schema: options.schema,\n model: modelStr,\n toolset,\n maxIterations,\n };\n}\n\nfunction buildInvocationSnapshot(params: {\n prompt: string;\n label: string;\n phase: string | undefined;\n normalized: AgentScriptOptions;\n modelSelection: { modelRef?: string; resolvedModelRef?: string };\n}): WorkflowAgentInvocationSnapshot {\n return compactObject({\n prompt: params.prompt,\n label: params.label,\n phase: params.phase,\n modelRef: params.modelSelection.modelRef,\n resolvedModelRef: params.modelSelection.resolvedModelRef,\n schema: cloneJsonValue(params.normalized.schema),\n toolset: params.normalized.toolset ? [...params.normalized.toolset] : undefined,\n maxIterations: params.normalized.maxIterations,\n });\n}\n\nfunction modelToRef(model: Model<Api>): string {\n return `${model.provider}/${model.id}`;\n}\n\nfunction cloneJsonValue<T>(value: T | undefined): T | undefined {\n if (value === undefined) return undefined;\n return structuredClone(value);\n}\n\nfunction compactObject<T extends Record<string, unknown>>(value: T): T {\n for (const key of Object.keys(value)) {\n if (value[key] === undefined) delete value[key];\n }\n return value;\n}\n\nfunction assertStructuredCloneable(value: unknown, name: string): void {\n try {\n structuredClone(value);\n } catch (e) {\n const promisePath = findPromisePath(value, '');\n if (promisePath !== null) {\n throw new Error(\n `${name} contains a Promise at \\`${promisePath || '<root>'}\\` — missing 'await' before parallel()/pipeline()/agent(). ` +\n `Async return auto-unwraps a bare Promise, but a Promise nested in an object/array is returned as-is.`,\n );\n }\n const detail = e instanceof Error ? ` ${e.message}` : '';\n throw new Error(\n `${name} must be structured-cloneable; did you forget to await agent(), parallel(), or pipeline()?${detail}`,\n );\n }\n}\n\n/**\n * Find the first Promise lurking in `value`, returning a JS-path like\n * \"results[0].pending\". Returns null when no Promise is found. Bounded\n * depth/breadth so it never explodes on weird user shapes.\n */\nfunction findPromisePath(value: unknown, path: string, depth = 0): string | null {\n if (depth > 4) return null;\n if (isThenable(value)) return path;\n if (Array.isArray(value)) {\n for (let i = 0; i < Math.min(value.length, 32); i++) {\n const inner = findPromisePath(value[i], `${path}[${i}]`, depth + 1);\n if (inner !== null) return inner;\n }\n return null;\n }\n if (value !== null && typeof value === 'object') {\n let count = 0;\n for (const [key, child] of Object.entries(value as Record<string, unknown>)) {\n if (count++ > 32) break;\n const inner = findPromisePath(child, path ? `${path}.${key}` : key, depth + 1);\n if (inner !== null) return inner;\n }\n }\n return null;\n}\n\nfunction isThenable(value: unknown): boolean {\n return (\n value !== null &&\n typeof value === 'object' &&\n typeof (value as { then?: unknown }).then === 'function'\n );\n}\n\n/**\n * Rewrite TypeErrors that look like \"called .map on a Promise\" with an\n * await-shaped hint. Static lint catches the obvious form at parse time;\n * this is the safety net for cases lint can't see (dynamic indirection,\n * values stashed in helper closures).\n */\nconst PROMISE_METHOD_ERROR =\n /\\.(map|filter|forEach|flat|flatMap|find|some|every|reduce|join|length|then)\\b is not a function/;\n\nfunction rewriteScriptError(error: unknown): Error {\n // VM-context errors aren't `instanceof` host classes (the vm has its own\n // global constructors), so check by name + duck-typing message.\n const asError = error as { name?: string; message?: string } | null | undefined;\n const isTypeError = asError?.name === 'TypeError' && typeof asError.message === 'string';\n if (!isTypeError) {\n return error instanceof Error ? error : new Error(String(error));\n }\n const message = (asError as { message: string }).message;\n if (!PROMISE_METHOD_ERROR.test(message)) {\n return error instanceof Error ? error : new Error(message);\n }\n return new Error(\n `${message}\\n\\nHint: parallel()/pipeline()/agent() return a Promise — 'await' the call before using its result.\\n` +\n ` ❌ const r = parallel(...); r.map(...)\\n` +\n ` ✅ const r = await parallel(...); r.map(...)`,\n );\n}\n\nfunction defaultAgentLabel(phase: string | undefined, index: number): string {\n return phase ? `${phase} agent ${index}` : `agent ${index}`;\n}\n\nfunction estimateTokens(value: unknown): number {\n if (value === null || value === undefined) return 0;\n try {\n return Math.ceil(JSON.stringify(value).length / 4);\n } catch {\n return Math.ceil(String(value).length / 4);\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA0CA,MAAM,4BAA4B;AAClC,MAAM,8BAA8B;AACpC,MAAM,wBAAwB;AAgB9B,eAAsB,YACpB,QACA,MACA,SAC+B;CAC/B,MAAM,UAAU,KAAK,KAAK;CAC1B,MAAM,EAAE,MAAM,SAAS,oBAAoB,OAAO;CAElD,MAAM,QAAsB;EAAE,MAAM,EAAE;EAAE,QAAQ,EAAE;EAAE,YAAY;EAAG,OAAO;EAAG;CAC7E,MAAM,cAAc,iBAAiB,QAAQ,YAAY;CACzD,MAAM,eAAe,KAAK,IAAI,GAAG,QAAQ,gBAAgB,sBAAsB;CAC/E,MAAM,UAAU,cAAc,YAAY;CAC1C,MAAM,mCAAmB,IAAI,KAAuB;CACp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nE,OAAI,UAAU,KAAM,QAAO;;AAE7B,SAAO;;AAET,KAAI,UAAU,QAAQ,OAAO,UAAU,UAAU;EAC/C,IAAI,QAAQ;AACZ,OAAK,MAAM,CAAC,KAAK,UAAU,OAAO,QAAQ,MAAiC,EAAE;AAC3E,OAAI,UAAU,GAAI;GAClB,MAAM,QAAQ,gBAAgB,OAAO,OAAO,GAAG,KAAK,GAAG,QAAQ,KAAK,QAAQ,EAAE;AAC9E,OAAI,UAAU,KAAM,QAAO;;;AAG/B,QAAO;;AAGT,SAAS,WAAW,OAAyB;AAC3C,QACE,UAAU,QACV,OAAO,UAAU,YACjB,OAAQ,MAA6B,SAAS;;;;;;;;AAUlD,MAAM,uBACJ;AAEF,SAAS,mBAAmB,OAAuB;CAGjD,MAAM,UAAU;AAEhB,KAAI,EADgB,SAAS,SAAS,eAAe,OAAO,QAAQ,YAAY,UAE9E,QAAO,iBAAiB,QAAQ,QAAQ,IAAI,MAAM,OAAO,MAAM,CAAC;CAElE,MAAM,UAAW,QAAgC;AACjD,KAAI,CAAC,qBAAqB,KAAK,QAAQ,CACrC,QAAO,iBAAiB,QAAQ,QAAQ,IAAI,MAAM,QAAQ;AAE5D,wBAAO,IAAI,MACT,GAAG,QAAQ,8LAGZ;;AAGH,SAAS,kBAAkB,OAA2B,OAAuB;AAC3E,QAAO,QAAQ,GAAG,MAAM,SAAS,UAAU,SAAS;;AAGtD,SAAS,eAAe,OAAwB;AAC9C,KAAI,UAAU,QAAQ,UAAU,KAAA,EAAW,QAAO;AAClD,KAAI;AACF,SAAO,KAAK,KAAK,KAAK,UAAU,MAAM,CAAC,SAAS,EAAE;SAC5C;AACN,SAAO,KAAK,KAAK,OAAO,MAAM,CAAC,SAAS,EAAE"}
|
|
@@ -87,6 +87,16 @@ export interface WorkflowAgentSnapshot {
|
|
|
87
87
|
/** Accumulated assistant/thinking text when subagentStream is `full`. */
|
|
88
88
|
streamText?: string;
|
|
89
89
|
}
|
|
90
|
+
export interface WorkflowAgentInvocationSnapshot {
|
|
91
|
+
prompt: string;
|
|
92
|
+
label: string;
|
|
93
|
+
phase?: string;
|
|
94
|
+
modelRef?: string;
|
|
95
|
+
resolvedModelRef?: string;
|
|
96
|
+
schema?: JsonSchema;
|
|
97
|
+
toolset?: string[];
|
|
98
|
+
maxIterations?: number;
|
|
99
|
+
}
|
|
90
100
|
export interface WorkflowSnapshot {
|
|
91
101
|
runId?: string;
|
|
92
102
|
name: string;
|
|
@@ -202,6 +212,7 @@ export interface WorkflowRunOptions {
|
|
|
202
212
|
label: string;
|
|
203
213
|
phase?: string;
|
|
204
214
|
prompt: string;
|
|
215
|
+
invocation: WorkflowAgentInvocationSnapshot;
|
|
205
216
|
}) => void;
|
|
206
217
|
onAgentStart?: (event: {
|
|
207
218
|
id: number;
|
|
@@ -42,6 +42,18 @@ function hasConfiguredWeixinAccount(raw) {
|
|
|
42
42
|
if (!isRecord(accounts)) return false;
|
|
43
43
|
return Object.values(accounts).some((account) => isRecord(account) && account.enabled !== false);
|
|
44
44
|
}
|
|
45
|
+
function hasConfiguredFeishuCredential(raw) {
|
|
46
|
+
if (!isRecord(raw)) return false;
|
|
47
|
+
if (hasNonEmptyString(raw.appId) && hasNonEmptyString(raw.appSecret)) return true;
|
|
48
|
+
const accounts = raw.accounts;
|
|
49
|
+
if (!isRecord(accounts)) return false;
|
|
50
|
+
return Object.values(accounts).some((account) => {
|
|
51
|
+
if (!isRecord(account) || account.enabled === false) return false;
|
|
52
|
+
const appId = hasNonEmptyString(account.appId) ? account.appId : raw.appId;
|
|
53
|
+
const appSecret = hasNonEmptyString(account.appSecret) ? account.appSecret : raw.appSecret;
|
|
54
|
+
return hasNonEmptyString(appId) && hasNonEmptyString(appSecret);
|
|
55
|
+
});
|
|
56
|
+
}
|
|
45
57
|
function withoutUndefined(value) {
|
|
46
58
|
return Object.fromEntries(Object.entries(value).filter(([, item]) => item !== void 0));
|
|
47
59
|
}
|
|
@@ -148,6 +160,7 @@ function isChannelConfigured(config, channelId) {
|
|
|
148
160
|
if (!raw) return false;
|
|
149
161
|
if (id === "telegram") return hasConfiguredTelegramCredential(raw);
|
|
150
162
|
if (id === "weixin") return hasConfiguredWeixinAccount(raw);
|
|
163
|
+
if (id === "feishu" || id === "lark") return hasConfiguredFeishuCredential(raw);
|
|
151
164
|
return isRecord(raw) ? raw.enabled === true || Object.keys(raw).length > 0 : true;
|
|
152
165
|
}
|
|
153
166
|
function getConfiguredChannelIds(config) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"channel-catalog-service.js","names":[],"sources":["../../../../src/channels/catalog/channel-catalog-service.ts"],"sourcesContent":["import type { Config } from '../../config/schema.js';\nimport {\n buildExtensionMetadataSnapshot,\n resolveExtensionLoaderOptionsFromConfig,\n} from '../../extensions/extension-metadata-snapshot.js';\nimport type { ExtensionMetadataSnapshot } from '../../extensions/extension-metadata-snapshot.js';\nimport type { ManifestRegistryEntry } from '../../extensions/manifest-registry.js';\nimport type { ChannelContributionDeclaration } from '../../extensions/types/manifest.js';\n\nimport type { ChannelCatalog, ChannelCatalogEntry } from './channel-catalog-types.js';\n\ntype BuildChannelCatalogOptions = {\n locale?: string;\n};\n\nconst DEFAULT_CONFIG_SCHEMA: Record<string, unknown> = {\n type: 'object',\n additionalProperties: true,\n};\n\nfunction normalizeChannelId(raw: string): string {\n return raw.trim().toLowerCase();\n}\n\nfunction normalizeLocale(raw: string | undefined): string | undefined {\n const value = raw?.trim().toLowerCase().replace('_', '-');\n return value || undefined;\n}\n\nfunction localeCandidates(raw: string | undefined): string[] {\n const locale = normalizeLocale(raw);\n if (!locale) return [];\n const base = locale.split('-')[0];\n return base && base !== locale ? [locale, base] : [locale];\n}\n\nfunction normalizeConfigPath(channelId: string, raw: string | undefined): `channels.${string}` {\n const expected = `channels.${channelId}` as const;\n if (!raw) return expected;\n const trimmed = raw.trim();\n if (!trimmed.startsWith('channels.')) return expected;\n return trimmed as `channels.${string}`;\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\nfunction hasNonEmptyString(value: unknown): boolean {\n return typeof value === 'string' && value.trim().length > 0;\n}\n\nfunction hasConfiguredTelegramCredential(raw: unknown): boolean {\n if (!isRecord(raw)) return false;\n const accounts = raw.accounts;\n if (!isRecord(accounts)) return false;\n return Object.values(accounts).some((account) => {\n if (!isRecord(account) || account.enabled === false) return false;\n return hasNonEmptyString(account.botToken) || hasNonEmptyString(account.tokenFile);\n });\n}\n\nfunction hasConfiguredWeixinAccount(raw: unknown): boolean {\n if (!isRecord(raw)) return false;\n if (raw.enabled === true) return true;\n const accounts = raw.accounts;\n if (!isRecord(accounts)) return false;\n return Object.values(accounts).some((account) => isRecord(account) && account.enabled !== false);\n}\n\nfunction withoutUndefined(value: Record<string, unknown>): Record<string, unknown> {\n return Object.fromEntries(Object.entries(value).filter(([, item]) => item !== undefined));\n}\n\nfunction mergeObjectMap<T extends Record<string, unknown>>(base: T | undefined, override: T | undefined): T | undefined {\n if (!base && !override) return undefined;\n if (!base) return override ? withoutUndefined(override) as T : undefined;\n if (!override) return base;\n const out: Record<string, unknown> = { ...base };\n for (const [key, value] of Object.entries(override)) {\n if (value === undefined) continue;\n out[key] = isRecord(out[key]) && isRecord(value)\n ? { ...out[key], ...withoutUndefined(value) }\n : value;\n }\n return out as T;\n}\n\nfunction mergeRecordDeep(base: Record<string, unknown>, override: Record<string, unknown>): Record<string, unknown> {\n const out: Record<string, unknown> = { ...base };\n for (const [key, value] of Object.entries(override)) {\n if (value === undefined) continue;\n out[key] = isRecord(out[key]) && isRecord(value)\n ? mergeRecordDeep(out[key], value)\n : value;\n }\n return out;\n}\n\nfunction mergeJsonSchema(base: Record<string, unknown> | undefined, override: Record<string, unknown> | undefined) {\n if (!base && !override) return undefined;\n if (!base) return override ? withoutUndefined(override) : undefined;\n if (!override) return base;\n return mergeRecordDeep(base, override);\n}\n\nfunction mergeChannelUi(\n base: ChannelContributionDeclaration['ui'],\n override: ChannelContributionDeclaration['ui'],\n): ChannelContributionDeclaration['ui'] {\n if (!base && !override) return undefined;\n return {\n ...(base ?? {}),\n ...(override ?? {}),\n card: mergeObjectMap(base?.card, override?.card),\n modal: mergeObjectMap(base?.modal, override?.modal),\n };\n}\n\nfunction localizeContribution(\n contribution: ChannelContributionDeclaration,\n locale: string | undefined,\n): ChannelContributionDeclaration {\n const i18n = contribution.i18n;\n if (!i18n) return contribution;\n const override = localeCandidates(locale).map((key) => i18n[key]).find(Boolean);\n if (!override) return contribution;\n return {\n ...contribution,\n label: override.label ?? contribution.label,\n description: override.description ?? contribution.description,\n configSchema: mergeJsonSchema(contribution.configSchema, override.configSchema),\n uiHints: mergeObjectMap(contribution.uiHints, override.uiHints),\n actions: mergeObjectMap(contribution.actions, override.actions),\n ui: mergeChannelUi(contribution.ui, override.ui),\n };\n}\n\nfunction toCatalogEntry(params: {\n extension: ManifestRegistryEntry;\n channelId: string;\n contribution: ChannelContributionDeclaration;\n locale?: string;\n}): ChannelCatalogEntry {\n const contribution = localizeContribution(params.contribution, params.locale);\n const id = normalizeChannelId(params.channelId);\n return {\n id,\n extensionId: params.extension.id,\n source: params.extension.source,\n path: params.extension.path,\n label: contribution.label,\n description: contribution.description,\n docsPath: contribution.docsPath,\n order: contribution.order ?? 999,\n configPath: normalizeConfigPath(id, contribution.configPath),\n capabilities: contribution.capabilities ?? {},\n configSchema: contribution.configSchema ?? DEFAULT_CONFIG_SCHEMA,\n uiHints: contribution.uiHints ?? {},\n actions: contribution.actions ?? {},\n ui: contribution.ui,\n };\n}\n\nexport function buildChannelCatalogFromSnapshot(\n snapshot: ExtensionMetadataSnapshot,\n options: BuildChannelCatalogOptions = {},\n): ChannelCatalog {\n const byId = new Map<string, ChannelCatalogEntry>();\n for (const extension of snapshot.manifestRegistry.getAllEntries()) {\n const contributions = extension.manifest.channelContributions ?? {};\n for (const [channelId, contribution] of Object.entries(contributions)) {\n const entry = toCatalogEntry({ extension, channelId, contribution, locale: options.locale });\n byId.set(entry.id, entry);\n }\n }\n const entries = Array.from(byId.values()).toSorted((a, b) => {\n if (a.order !== b.order) return a.order - b.order;\n return a.id.localeCompare(b.id);\n });\n return { entries, byId };\n}\n\nexport function buildChannelCatalogForConfig(config: Config, options: BuildChannelCatalogOptions = {}): ChannelCatalog {\n const snapshot = buildExtensionMetadataSnapshot(resolveExtensionLoaderOptionsFromConfig(config), config);\n return buildChannelCatalogFromSnapshot(snapshot, options);\n}\n\nexport function isChannelConfigured(config: Config, channelId: string): boolean {\n const id = normalizeChannelId(channelId);\n const raw = (config.channels as Record<string, unknown> | undefined)?.[id];\n if (!raw) return false;\n if (id === 'telegram') return hasConfiguredTelegramCredential(raw);\n if (id === 'weixin') return hasConfiguredWeixinAccount(raw);\n return isRecord(raw) ? raw.enabled === true || Object.keys(raw).length > 0 : true;\n}\n\nexport function getConfiguredChannelIds(config: Config): string[] {\n return Object.keys(config.channels ?? {})\n .map(normalizeChannelId)\n .filter((id) => id && isChannelConfigured(config, id));\n}\n"],"mappings":";;;AAoBA,SAAS,mBAAmB,KAAqB;AAC/C,QAAO,IAAI,MAAM,CAAC,aAAa;;AAGjC,SAAS,gBAAgB,KAA6C;AAEpE,QADc,KAAK,MAAM,CAAC,aAAa,CAAC,QAAQ,KAAK,IAAI,IACzC,KAAA;;AAGlB,SAAS,iBAAiB,KAAmC;CAC3D,MAAM,SAAS,gBAAgB,IAAI;AACnC,KAAI,CAAC,OAAQ,QAAO,EAAE;CACtB,MAAM,OAAO,OAAO,MAAM,IAAI,CAAC;AAC/B,QAAO,QAAQ,SAAS,SAAS,CAAC,QAAQ,KAAK,GAAG,CAAC,OAAO;;AAG5D,SAAS,oBAAoB,WAAmB,KAA+C;CAC7F,MAAM,WAAW,YAAY;AAC7B,KAAI,CAAC,IAAK,QAAO;CACjB,MAAM,UAAU,IAAI,MAAM;AAC1B,KAAI,CAAC,QAAQ,WAAW,YAAY,CAAE,QAAO;AAC7C,QAAO;;AAGT,SAAS,SAAS,OAAkD;AA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UAAU;CACxC,MAAM,MAAO,OAAO,WAAmD;AACvE,KAAI,CAAC,IAAK,QAAO;AACjB,KAAI,OAAO,WAAY,QAAO,gCAAgC,IAAI;AAClE,KAAI,OAAO,SAAU,QAAO,2BAA2B,IAAI;AAC3D,QAAO,SAAS,IAAI,GAAG,IAAI,YAAY,QAAQ,OAAO,KAAK,IAAI,CAAC,SAAS,IAAI;;AAG/E,SAAgB,wBAAwB,QAA0B;AAChE,QAAO,OAAO,KAAK,OAAO,YAAY,EAAE,CAAC,CACtC,IAAI,mBAAmB,CACvB,QAAQ,OAAO,MAAM,oBAAoB,QAAQ,GAAG,CAAC;;;;mCApMD;AAWnD,yBAAiD;EACrD,MAAM;EACN,sBAAsB;EACvB"}
|
|
1
|
+
{"version":3,"file":"channel-catalog-service.js","names":[],"sources":["../../../../src/channels/catalog/channel-catalog-service.ts"],"sourcesContent":["import type { Config } from '../../config/schema.js';\nimport {\n buildExtensionMetadataSnapshot,\n resolveExtensionLoaderOptionsFromConfig,\n} from '../../extensions/extension-metadata-snapshot.js';\nimport type { ExtensionMetadataSnapshot } from '../../extensions/extension-metadata-snapshot.js';\nimport type { ManifestRegistryEntry } from '../../extensions/manifest-registry.js';\nimport type { ChannelContributionDeclaration } from '../../extensions/types/manifest.js';\n\nimport type { ChannelCatalog, ChannelCatalogEntry } from './channel-catalog-types.js';\n\ntype BuildChannelCatalogOptions = {\n locale?: string;\n};\n\nconst DEFAULT_CONFIG_SCHEMA: Record<string, unknown> = {\n type: 'object',\n additionalProperties: true,\n};\n\nfunction normalizeChannelId(raw: string): string {\n return raw.trim().toLowerCase();\n}\n\nfunction normalizeLocale(raw: string | undefined): string | undefined {\n const value = raw?.trim().toLowerCase().replace('_', '-');\n return value || undefined;\n}\n\nfunction localeCandidates(raw: string | undefined): string[] {\n const locale = normalizeLocale(raw);\n if (!locale) return [];\n const base = locale.split('-')[0];\n return base && base !== locale ? [locale, base] : [locale];\n}\n\nfunction normalizeConfigPath(channelId: string, raw: string | undefined): `channels.${string}` {\n const expected = `channels.${channelId}` as const;\n if (!raw) return expected;\n const trimmed = raw.trim();\n if (!trimmed.startsWith('channels.')) return expected;\n return trimmed as `channels.${string}`;\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\nfunction hasNonEmptyString(value: unknown): boolean {\n return typeof value === 'string' && value.trim().length > 0;\n}\n\nfunction hasConfiguredTelegramCredential(raw: unknown): boolean {\n if (!isRecord(raw)) return false;\n const accounts = raw.accounts;\n if (!isRecord(accounts)) return false;\n return Object.values(accounts).some((account) => {\n if (!isRecord(account) || account.enabled === false) return false;\n return hasNonEmptyString(account.botToken) || hasNonEmptyString(account.tokenFile);\n });\n}\n\nfunction hasConfiguredWeixinAccount(raw: unknown): boolean {\n if (!isRecord(raw)) return false;\n if (raw.enabled === true) return true;\n const accounts = raw.accounts;\n if (!isRecord(accounts)) return false;\n return Object.values(accounts).some((account) => isRecord(account) && account.enabled !== false);\n}\n\nfunction hasConfiguredFeishuCredential(raw: unknown): boolean {\n if (!isRecord(raw)) return false;\n const hasRootCredentials = hasNonEmptyString(raw.appId) && hasNonEmptyString(raw.appSecret);\n if (hasRootCredentials) return true;\n const accounts = raw.accounts;\n if (!isRecord(accounts)) return false;\n return Object.values(accounts).some((account) => {\n if (!isRecord(account) || account.enabled === false) return false;\n const appId = hasNonEmptyString(account.appId) ? account.appId : raw.appId;\n const appSecret = hasNonEmptyString(account.appSecret) ? account.appSecret : raw.appSecret;\n return hasNonEmptyString(appId) && hasNonEmptyString(appSecret);\n });\n}\n\nfunction withoutUndefined(value: Record<string, unknown>): Record<string, unknown> {\n return Object.fromEntries(Object.entries(value).filter(([, item]) => item !== undefined));\n}\n\nfunction mergeObjectMap<T extends Record<string, unknown>>(base: T | undefined, override: T | undefined): T | undefined {\n if (!base && !override) return undefined;\n if (!base) return override ? withoutUndefined(override) as T : undefined;\n if (!override) return base;\n const out: Record<string, unknown> = { ...base };\n for (const [key, value] of Object.entries(override)) {\n if (value === undefined) continue;\n out[key] = isRecord(out[key]) && isRecord(value)\n ? { ...out[key], ...withoutUndefined(value) }\n : value;\n }\n return out as T;\n}\n\nfunction mergeRecordDeep(base: Record<string, unknown>, override: Record<string, unknown>): Record<string, unknown> {\n const out: Record<string, unknown> = { ...base };\n for (const [key, value] of Object.entries(override)) {\n if (value === undefined) continue;\n out[key] = isRecord(out[key]) && isRecord(value)\n ? mergeRecordDeep(out[key], value)\n : value;\n }\n return out;\n}\n\nfunction mergeJsonSchema(base: Record<string, unknown> | undefined, override: Record<string, unknown> | undefined) {\n if (!base && !override) return undefined;\n if (!base) return override ? withoutUndefined(override) : undefined;\n if (!override) return base;\n return mergeRecordDeep(base, override);\n}\n\nfunction mergeChannelUi(\n base: ChannelContributionDeclaration['ui'],\n override: ChannelContributionDeclaration['ui'],\n): ChannelContributionDeclaration['ui'] {\n if (!base && !override) return undefined;\n return {\n ...(base ?? {}),\n ...(override ?? {}),\n card: mergeObjectMap(base?.card, override?.card),\n modal: mergeObjectMap(base?.modal, override?.modal),\n };\n}\n\nfunction localizeContribution(\n contribution: ChannelContributionDeclaration,\n locale: string | undefined,\n): ChannelContributionDeclaration {\n const i18n = contribution.i18n;\n if (!i18n) return contribution;\n const override = localeCandidates(locale).map((key) => i18n[key]).find(Boolean);\n if (!override) return contribution;\n return {\n ...contribution,\n label: override.label ?? contribution.label,\n description: override.description ?? contribution.description,\n configSchema: mergeJsonSchema(contribution.configSchema, override.configSchema),\n uiHints: mergeObjectMap(contribution.uiHints, override.uiHints),\n actions: mergeObjectMap(contribution.actions, override.actions),\n ui: mergeChannelUi(contribution.ui, override.ui),\n };\n}\n\nfunction toCatalogEntry(params: {\n extension: ManifestRegistryEntry;\n channelId: string;\n contribution: ChannelContributionDeclaration;\n locale?: string;\n}): ChannelCatalogEntry {\n const contribution = localizeContribution(params.contribution, params.locale);\n const id = normalizeChannelId(params.channelId);\n return {\n id,\n extensionId: params.extension.id,\n source: params.extension.source,\n path: params.extension.path,\n label: contribution.label,\n description: contribution.description,\n docsPath: contribution.docsPath,\n order: contribution.order ?? 999,\n configPath: normalizeConfigPath(id, contribution.configPath),\n capabilities: contribution.capabilities ?? {},\n configSchema: contribution.configSchema ?? DEFAULT_CONFIG_SCHEMA,\n uiHints: contribution.uiHints ?? {},\n actions: contribution.actions ?? {},\n ui: contribution.ui,\n };\n}\n\nexport function buildChannelCatalogFromSnapshot(\n snapshot: ExtensionMetadataSnapshot,\n options: BuildChannelCatalogOptions = {},\n): ChannelCatalog {\n const byId = new Map<string, ChannelCatalogEntry>();\n for (const extension of snapshot.manifestRegistry.getAllEntries()) {\n const contributions = extension.manifest.channelContributions ?? {};\n for (const [channelId, contribution] of Object.entries(contributions)) {\n const entry = toCatalogEntry({ extension, channelId, contribution, locale: options.locale });\n byId.set(entry.id, entry);\n }\n }\n const entries = Array.from(byId.values()).toSorted((a, b) => {\n if (a.order !== b.order) return a.order - b.order;\n return a.id.localeCompare(b.id);\n });\n return { entries, byId };\n}\n\nexport function buildChannelCatalogForConfig(config: Config, options: BuildChannelCatalogOptions = {}): ChannelCatalog {\n const snapshot = buildExtensionMetadataSnapshot(resolveExtensionLoaderOptionsFromConfig(config), config);\n return buildChannelCatalogFromSnapshot(snapshot, options);\n}\n\nexport function isChannelConfigured(config: Config, channelId: string): boolean {\n const id = normalizeChannelId(channelId);\n const raw = (config.channels as Record<string, unknown> | undefined)?.[id];\n if (!raw) return false;\n if (id === 'telegram') return hasConfiguredTelegramCredential(raw);\n if (id === 'weixin') return hasConfiguredWeixinAccount(raw);\n if (id === 'feishu' || id === 'lark') return hasConfiguredFeishuCredential(raw);\n return isRecord(raw) ? raw.enabled === true || Object.keys(raw).length > 0 : true;\n}\n\nexport function getConfiguredChannelIds(config: Config): string[] {\n return Object.keys(config.channels ?? {})\n .map(normalizeChannelId)\n .filter((id) => id && isChannelConfigured(config, id));\n}\n"],"mappings":";;;AAoBA,SAAS,mBAAmB,KAAqB;AAC/C,Q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AAC3D,KAAI,OAAO,YAAY,OAAO,OAAQ,QAAO,8BAA8B,IAAI;AAC/E,QAAO,SAAS,IAAI,GAAG,IAAI,YAAY,QAAQ,OAAO,KAAK,IAAI,CAAC,SAAS,IAAI;;AAG/E,SAAgB,wBAAwB,QAA0B;AAChE,QAAO,OAAO,KAAK,OAAO,YAAY,EAAE,CAAC,CACtC,IAAI,mBAAmB,CACvB,QAAQ,OAAO,MAAM,oBAAoB,QAAQ,GAAG,CAAC;;;;mCAnND;AAWnD,yBAAiD;EACrD,MAAM;EACN,sBAAsB;EACvB"}
|
|
@@ -176,6 +176,8 @@ export interface ChannelRuntimeActionResult {
|
|
|
176
176
|
ok: boolean;
|
|
177
177
|
payload?: ChannelRuntimeActionPayload;
|
|
178
178
|
message?: string;
|
|
179
|
+
/** Internal gateway-side config replacement; never returned to the browser. */
|
|
180
|
+
nextConfig?: Config;
|
|
179
181
|
}
|
|
180
182
|
/** Gateway/CLI control-plane actions declared by extension manifests. */
|
|
181
183
|
export interface ChannelRuntimeActionAdapter {
|