pi-ate-workflow 0.1.0 → 0.2.1

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/research-utils.ts CHANGED
@@ -1,107 +1,118 @@
1
- /**
2
- * workflow: 研究管道工具函数
3
- *
4
- * 通用工具:slugify、urlToId、parseFrontmatter、getTimestamp
5
- * 路径函数:getResearchDir、getDirectionsDir
6
- */
7
-
8
- import * as path from "node:path";
9
- import { createHash } from "node:crypto";
10
-
11
- /**
12
- * 获取全局研究目录。
13
- * 路径:{cwd}/docs/research/
14
- */
15
- export function getResearchDir(cwd: string): string {
16
- return path.join(cwd, "docs", "research");
17
- }
18
-
19
- /**
20
- * 获取按主题分的方向目录。
21
- * 路径:{cwd}/docs/research/directions/{slug}/
22
- */
23
- export function getDirectionsDir(cwd: string, slug: string): string {
24
- return path.join(getResearchDir(cwd), "directions", slug);
25
- }
26
-
27
- /**
28
- * 旧函数保留别名(向后兼容)
29
- * @deprecated 使用 getResearchDir + getDirectionsDir
30
- */
31
- export function getTopicDir(cwd: string, _slug: string): string {
32
- return getResearchDir(cwd);
33
- }
34
-
35
- /**
36
- * 解析 YAML-like frontmatter。
37
- */
38
- export function parseFrontmatter(content: string): Record<string, any> {
39
- const fmMatch = content.match(/^---\s*\n([\s\S]*?)\n---\s*\n/);
40
- if (!fmMatch) return {};
41
-
42
- const fm = fmMatch[1];
43
- const result: Record<string, any> = {};
44
-
45
- for (const line of fm.split("\n")) {
46
- const trimmed = line.trim();
47
- if (!trimmed || trimmed.startsWith("#")) continue;
48
-
49
- const colonIdx = trimmed.indexOf(":");
50
- if (colonIdx <= 0) continue;
51
-
52
- const key = trimmed.slice(0, colonIdx).trim();
53
- let value: string = trimmed.slice(colonIdx + 1).trim();
54
-
55
- if ((value.startsWith('"') && value.endsWith('"')) ||
56
- (value.startsWith("'") && value.endsWith("'"))) {
57
- value = value.slice(1, -1);
58
- }
59
-
60
- if (/^\d+$/.test(value)) {
61
- value = parseInt(value, 10);
62
- } else if (/^\d+\.\d+$/.test(value)) {
63
- value = parseFloat(value);
64
- } else if (value === "true") {
65
- value = true;
66
- } else if (value === "false") {
67
- value = false;
68
- }
69
-
70
- result[key] = value;
71
- }
72
-
73
- return result;
74
- }
75
-
76
- /**
77
- * 从 URL 生成唯一 ID:sha256(url)[:12]
78
- */
79
- export function urlToId(url: string): string {
80
- return createHash("sha256").update(url).digest("hex").slice(0, 12);
81
- }
82
-
83
- /**
84
- * 从主题文本生成 slug。
85
- */
86
- export function slugify(topic: string): string {
87
- return topic
88
- .toLowerCase()
89
- .trim()
90
- .replace(/\s+/g, "-")
91
- .replace(/[^a-z0-9\u4e00-\u9fff-]/g, "")
92
- .replace(/-+/g, "-")
93
- .replace(/^-|-$/g, "");
94
- }
95
-
96
- /**
97
- * 获取格式化时间戳:"2026-05-09T2000"
98
- */
99
- export function getTimestamp(): string {
100
- const now = new Date();
101
- const yyyy = now.getFullYear();
102
- const MM = String(now.getMonth() + 1).padStart(2, "0");
103
- const dd = String(now.getDate()).padStart(2, "0");
104
- const hh = String(now.getHours()).padStart(2, "0");
105
- const mm = String(now.getMinutes()).padStart(2, "0");
106
- return `${yyyy}-${MM}-${dd}T${hh}${mm}`;
107
- }
1
+ /**
2
+ * workflow: 研究管道工具函数
3
+ *
4
+ * 通用工具:slugify、urlToId、parseFrontmatter、getTimestamp
5
+ * 路径函数:getResearchDir、getDirectionsDir
6
+ */
7
+
8
+ import * as path from "node:path";
9
+ import { createHash } from "node:crypto";
10
+
11
+ /**
12
+ * 获取全局研究目录。
13
+ * 路径:{cwd}/docs/research/
14
+ */
15
+ export function getResearchDir(cwd: string): string {
16
+ return path.join(cwd, "docs", "research");
17
+ }
18
+
19
+ /**
20
+ * 获取按主题分的方向目录。
21
+ * 路径:{cwd}/docs/research/directions/{slug}/
22
+ */
23
+ export function getDirectionsDir(cwd: string, slug: string): string {
24
+ return path.join(getResearchDir(cwd), "directions", slug);
25
+ }
26
+
27
+ /**
28
+ * 旧函数保留别名(向后兼容)
29
+ * @deprecated 使用 getResearchDir + getDirectionsDir
30
+ */
31
+ export function getTopicDir(cwd: string, _slug: string): string {
32
+ return getResearchDir(cwd);
33
+ }
34
+
35
+ /**
36
+ * 解析 YAML-like frontmatter。
37
+ */
38
+ export function parseFrontmatter(content: string): Record<string, any> {
39
+ const fmMatch = content.match(/^---\s*\n([\s\S]*?)\n---\s*\n/);
40
+ if (!fmMatch) return {};
41
+
42
+ const fm = fmMatch[1];
43
+ const result: Record<string, any> = {};
44
+
45
+ for (const line of fm.split("\n")) {
46
+ const trimmed = line.trim();
47
+ if (!trimmed || trimmed.startsWith("#")) continue;
48
+
49
+ const colonIdx = trimmed.indexOf(":");
50
+ if (colonIdx <= 0) continue;
51
+
52
+ const key = trimmed.slice(0, colonIdx).trim();
53
+ let value: string | number | boolean = trimmed.slice(colonIdx + 1).trim();
54
+
55
+ if ((value.startsWith('"') && value.endsWith('"')) ||
56
+ (value.startsWith("'") && value.endsWith("'"))) {
57
+ value = value.slice(1, -1);
58
+ }
59
+
60
+ if (/^\d+$/.test(value)) {
61
+ value = parseInt(value, 10);
62
+ } else if (/^\d+\.\d+$/.test(value)) {
63
+ value = parseFloat(value);
64
+ } else if (value === "true") {
65
+ value = true;
66
+ } else if (value === "false") {
67
+ value = false;
68
+ }
69
+
70
+ result[key] = value;
71
+ }
72
+
73
+ return result;
74
+ }
75
+
76
+ /**
77
+ * 从 URL 生成唯一 ID:sha256(url)[:12]
78
+ */
79
+ export function urlToId(url: string): string {
80
+ return createHash("sha256").update(url).digest("hex").slice(0, 12);
81
+ }
82
+
83
+ /**
84
+ * 从主题文本生成 slug。
85
+ *
86
+ * 规则:去标点、空格转横线、保留中英文+数字、截断至 maxLength。
87
+ * 超长时追加 8 位 hash 防碰撞。
88
+ */
89
+ export function slugify(topic: string, maxLength = 40): string {
90
+ const raw = topic
91
+ .toLowerCase()
92
+ .trim()
93
+ .replace(/\s+/g, "-")
94
+ .replace(/[^a-z0-9\u4e00-\u9fff-]/g, "")
95
+ .replace(/-+/g, "-")
96
+ .replace(/^-|-$/g, "");
97
+
98
+ // 短 topic 直接返回
99
+ if (raw.length <= maxLength) return raw;
100
+
101
+ // 超 long:截断 + hash 后缀防碰撞
102
+ const hash = createHash("sha256").update(raw).digest("hex").slice(0, 8);
103
+ const truncated = raw.slice(0, maxLength - 9); // 留 1 横线 + 8 hash
104
+ return `${truncated}-${hash}`;
105
+ }
106
+
107
+ /**
108
+ * 获取格式化时间戳:"2026-05-09T2000"
109
+ */
110
+ export function getTimestamp(): string {
111
+ const now = new Date();
112
+ const yyyy = now.getFullYear();
113
+ const MM = String(now.getMonth() + 1).padStart(2, "0");
114
+ const dd = String(now.getDate()).padStart(2, "0");
115
+ const hh = String(now.getHours()).padStart(2, "0");
116
+ const mm = String(now.getMinutes()).padStart(2, "0");
117
+ return `${yyyy}-${MM}-${dd}T${hh}${mm}`;
118
+ }
package/research.ts CHANGED
@@ -1,52 +1,53 @@
1
- /**
2
- * workflow: 研究管道基础设施(barrel export)
3
- *
4
- * 子模块:
5
- * research-types.ts — 类型定义
6
- * research-utils.ts — 通用工具(slugify, urlToId, getResearchDir 等)
7
- * research-catalog.ts — catalog 管理
8
- * research-state.ts — 主题方向状态管理
9
- * research-analysis.ts — 全局文章分析状态
10
- * research-scan.ts — 文件扫描
11
- */
12
-
13
- export type {
14
- Article,
15
- ArticleAnalysis as ArticleAnalysisType,
16
- Direction,
17
- TopicResearchState,
18
- } from "./research-types";
19
-
20
- export {
21
- slugify,
22
- urlToId,
23
- parseFrontmatter,
24
- getTimestamp,
25
- getResearchDir,
26
- getDirectionsDir,
27
- getTopicDir,
28
- } from "./research-utils";
29
-
30
- export {
31
- loadCatalog,
32
- saveCatalog,
33
- } from "./research-catalog";
34
-
35
- export {
36
- loadTopicState,
37
- saveTopicState,
38
- loadDirectionState,
39
- saveDirectionState,
40
- } from "./research-state";
41
-
42
- export {
43
- loadAnalysis,
44
- saveAnalysis,
45
- defaultAnalysis,
46
- type ArticleAnalysis,
47
- type AnalysisState,
48
- } from "./research-analysis";
49
-
50
- export {
51
- scanNewSources,
52
- } from "./research-scan";
1
+ /**
2
+ * workflow: 研究管道基础设施(barrel export)
3
+ *
4
+ * 子模块:
5
+ * research-types.ts — 类型定义
6
+ * research-utils.ts — 通用工具(slugify, urlToId, getResearchDir 等)
7
+ * research-catalog.ts — catalog 管理
8
+ * research-state.ts — 主题方向状态管理
9
+ * research-analysis.ts — 全局文章分析状态
10
+ * research-scan.ts — 文件扫描
11
+ */
12
+
13
+ export type {
14
+ Article,
15
+ ArticleAnalysis as ArticleAnalysisType,
16
+ Direction,
17
+ TopicResearchState,
18
+ } from "./research-types";
19
+
20
+ export {
21
+ slugify,
22
+ urlToId,
23
+ parseFrontmatter,
24
+ getTimestamp,
25
+ getResearchDir,
26
+ getDirectionsDir,
27
+ getTopicDir,
28
+ } from "./research-utils";
29
+
30
+ export {
31
+ loadCatalog,
32
+ saveCatalog,
33
+ } from "./research-catalog";
34
+
35
+ export {
36
+ loadTopicState,
37
+ saveTopicState,
38
+ loadDirectionState,
39
+ saveDirectionState,
40
+ } from "./research-state";
41
+
42
+ export {
43
+ loadAnalysis,
44
+ saveAnalysis,
45
+ defaultAnalysis,
46
+ type ArticleAnalysis,
47
+ type AnalysisState,
48
+ } from "./research-analysis";
49
+
50
+ export {
51
+ scanNewSources,
52
+ scanTopicArticles,
53
+ } from "./research-scan";
@@ -0,0 +1,82 @@
1
+ /**
2
+ * 子代理默认模型管理
3
+ *
4
+ * 持久化到 settings.json 的 subagent.defaultModel 字段。
5
+ * 读取:getEffectiveConfig 三层合并(代码默认 → 全局 → 项目级)
6
+ * 写入:patchSettingsSectionWithBackup 带锁路径(禁止裸 readFileSync/writeFileSync)
7
+ * 未配置时使用主模型(settings.json 的 defaultProvider/defaultModel 组合)。
8
+ */
9
+
10
+ import {
11
+ getEffectiveConfig,
12
+ getSettingsValue,
13
+ patchSettingsSectionWithBackup,
14
+ } from "@pi-atelier/shared-utils";
15
+
16
+ /** subagent section 模型字段的 schema 默认值 */
17
+ const SUBAGENT_MODEL_DEFAULTS = {
18
+ defaultModel: "",
19
+ };
20
+
21
+ let subagentModel = "";
22
+ let subagentModelRestored = false;
23
+
24
+ /**
25
+ * 读取子代理默认模型。
26
+ * subagent.defaultModel 未配置时,回退 defaultProvider/defaultModel 组合。
27
+ */
28
+ function readModelFromSettings(cwd?: string): string {
29
+ try {
30
+ const { config } = getEffectiveConfig(
31
+ "subagent",
32
+ SUBAGENT_MODEL_DEFAULTS,
33
+ cwd || process.cwd(),
34
+ );
35
+ if (config.defaultModel) return config.defaultModel;
36
+ // 未配置子代理模型:组合 provider/model(读全局 settings)
37
+ const provider = getSettingsValue<string>("defaultProvider", "");
38
+ const model = getSettingsValue<string>("defaultModel", "");
39
+ if (provider && model) return `${provider}/${model}`;
40
+ return model;
41
+ } catch {
42
+ return "";
43
+ }
44
+ }
45
+
46
+ /**
47
+ * 将子代理模型写入 settings.json 的 subagent.defaultModel(带锁 + 备份)
48
+ */
49
+ function persistModelToSettings(model: string): void {
50
+ try {
51
+ patchSettingsSectionWithBackup(
52
+ "subagent",
53
+ { defaultModel: model },
54
+ SUBAGENT_MODEL_DEFAULTS,
55
+ );
56
+ } catch {
57
+ // 写入失败不阻塞主流程
58
+ }
59
+ }
60
+
61
+ export function getSubagentModel(): string {
62
+ return subagentModel;
63
+ }
64
+
65
+ export function setSubagentModel(model: string, cwd?: string): void {
66
+ subagentModel = model;
67
+ persistModelToSettings(model);
68
+ }
69
+
70
+ export function isSubagentModelRestored(): boolean {
71
+ return subagentModelRestored;
72
+ }
73
+
74
+ export function setSubagentModelRestored(v: boolean): void {
75
+ subagentModelRestored = v;
76
+ }
77
+
78
+ /** 从 settings.json 恢复模型设置(session_start 时调用) */
79
+ export function restoreSubagentModel(cwd?: string): void {
80
+ subagentModel = readModelFromSettings(cwd);
81
+ subagentModelRestored = true;
82
+ }
@@ -0,0 +1,132 @@
1
+ /**
2
+ * SubagentSession — 子代理执行生命周期的公共状态管理
3
+ *
4
+ * 封装两种 spawn 模式(visible / once)共享的逻辑:
5
+ * 1. 输出收集(collectTexts + formatOutput)
6
+ * 2. 退出控制(resolved 守卫 + 一次性 resolve)
7
+ * 3. 事件解析(parseStreamEvent / parseSessionLine)
8
+ *
9
+ * resolveOnce 时自动附加捕获到的 subSessionId(供父侧建立会话关联)。
10
+ */
11
+
12
+ import type { SubagentResult } from "./types";
13
+
14
+ export class SubagentSession {
15
+ /** 收集到的所有 assistant 文本块 */
16
+ private readonly allTexts: string[] = [];
17
+
18
+ /** 捕获到的子代理 session ID */
19
+ capturedSessionId: string | undefined;
20
+
21
+ /** 是否已 resolve(退出守卫) */
22
+ private resolved = false;
23
+
24
+ /** 外部 resolve 函数(Promise 构造器中赋值) */
25
+ private resolver!: (result: SubagentResult) => void;
26
+
27
+ /** 外部 Promise(调用者 await 这个) */
28
+ readonly result: Promise<SubagentResult>;
29
+
30
+ /** 实时事件回调 */
31
+ private readonly onEvent?: (event: any) => void;
32
+
33
+ /** 退出时的额外处理(如注入父会话) */
34
+ private readonly beforeResolve?: (result: SubagentResult) => void;
35
+
36
+ constructor(
37
+ opts: {
38
+ onEvent?: (event: any) => void;
39
+ beforeResolve?: (result: SubagentResult) => void;
40
+ } = {},
41
+ ) {
42
+ this.onEvent = opts.onEvent;
43
+ this.beforeResolve = opts.beforeResolve;
44
+ this.result = new Promise<SubagentResult>((resolve) => {
45
+ this.resolver = resolve;
46
+ });
47
+ }
48
+
49
+ // ─── 输出收集 ─────────────────────────────────────
50
+
51
+ /** 从 LLM message 中提取 assistant text 并收集 */
52
+ collectTexts(message: any): void {
53
+ if (message?.role !== "assistant") return;
54
+ for (const part of message.content ?? []) {
55
+ if (part.type === "text" && part.text.trim()) {
56
+ this.allTexts.push(part.text);
57
+ }
58
+ }
59
+ }
60
+
61
+ /** 格式化收集到的输出(去重 + 拼接) */
62
+ formatOutput(fallback: string): string {
63
+ return this.allTexts.length > 0
64
+ ? [...new Set(this.allTexts)].join("\n\n---\n\n")
65
+ : fallback;
66
+ }
67
+
68
+ // ─── 事件解析 ─────────────────────────────────────
69
+
70
+ /** 解析 JSON 事件行(once 模式:来自 stdout 流式 JSON) */
71
+ parseStreamEvent(event: any): void {
72
+ if (event.type === "session" && event.id && !this.capturedSessionId)
73
+ this.capturedSessionId = event.id;
74
+ if (event.type === "tool_execution_start")
75
+ this.onEvent?.({
76
+ type: "tool",
77
+ toolName: event.toolName,
78
+ toolArgs: event.args,
79
+ });
80
+ if (
81
+ event.type === "message_update" &&
82
+ event.assistantMessageEvent?.type === "text_delta"
83
+ )
84
+ this.onEvent?.({
85
+ type: "thinking",
86
+ text: event.assistantMessageEvent.delta,
87
+ });
88
+ if (event.type === "message_end") this.collectTexts(event.message);
89
+ if (event.type === "turn_end") {
90
+ this.collectTexts(event.message);
91
+ this.onEvent?.({ type: "message", message: event.message });
92
+ }
93
+ if (event.type === "agent_end" && Array.isArray(event.messages)) {
94
+ for (const msg of event.messages) this.collectTexts(msg);
95
+ }
96
+ }
97
+
98
+ /** 解析 session.jsonl 的一行(visible 模式:来自文件轮询) */
99
+ parseSessionLine(entry: any): void {
100
+ if (entry.type === "session" && entry.id)
101
+ this.capturedSessionId = entry.id;
102
+ if (entry.type === "message" && entry.message)
103
+ this.collectTexts(entry.message);
104
+ if (entry.type === "tool_execution_start")
105
+ this.onEvent?.({
106
+ type: "tool",
107
+ toolName: entry.toolName,
108
+ toolArgs: entry.args,
109
+ });
110
+ if (entry.type === "agent_end" && Array.isArray(entry.messages)) {
111
+ for (const msg of entry.messages) this.collectTexts(msg);
112
+ }
113
+ }
114
+
115
+ // ─── 退出控制 ─────────────────────────────────────
116
+
117
+ /** 一次性 resolve(防止重复调用,自动附加 subSessionId) */
118
+ resolveOnce(result: SubagentResult): void {
119
+ if (this.resolved) return;
120
+ this.resolved = true;
121
+ if (this.capturedSessionId && result.subSessionId === undefined) {
122
+ result.subSessionId = this.capturedSessionId;
123
+ }
124
+ this.beforeResolve?.(result);
125
+ this.resolver(result);
126
+ }
127
+
128
+ /** 当前是否已退出 */
129
+ get isDone(): boolean {
130
+ return this.resolved;
131
+ }
132
+ }