@uncarved/jade 0.3.1 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (199) hide show
  1. package/dist/api.d.ts +1 -1
  2. package/dist/api.js +1 -1
  3. package/dist/host.d.ts +2 -0
  4. package/dist/host.js +39 -5
  5. package/dist/host.js.map +1 -1
  6. package/dist/remote.js +5 -0
  7. package/dist/remote.js.map +1 -1
  8. package/dist/session.d.ts +7 -0
  9. package/dist/session.js +482 -27
  10. package/dist/session.js.map +1 -1
  11. package/package.json +4 -4
  12. package/plugins/approval/index.ts +36 -14
  13. package/plugins/approval/policy.ts +15 -10
  14. package/plugins/approval/review.ts +9 -5
  15. package/plugins/checks/checks.ts +10 -7
  16. package/plugins/checks/index.ts +13 -13
  17. package/plugins/checks/plugin.json +1 -1
  18. package/plugins/checks/project.ts +37 -38
  19. package/plugins/commands/index.ts +27 -3
  20. package/plugins/compact/compact.ts +13 -5
  21. package/plugins/compact/index.ts +20 -3
  22. package/plugins/compact/style.ts +13 -14
  23. package/plugins/completions/index.ts +35 -0
  24. package/plugins/completions/plugin.json +7 -0
  25. package/plugins/copy/index.ts +46 -0
  26. package/plugins/copy/plugin.json +7 -0
  27. package/plugins/editor/index.ts +10 -4
  28. package/plugins/fs/diff.ts +7 -6
  29. package/plugins/fs/fs.ts +8 -4
  30. package/plugins/fs/grep.ts +42 -9
  31. package/plugins/fs/index.ts +2 -7
  32. package/plugins/fs/plugin.json +1 -1
  33. package/plugins/fs/renderers.ts +16 -15
  34. package/plugins/fs/style.ts +16 -15
  35. package/plugins/hooks/index.ts +3 -2
  36. package/plugins/keys/index.ts +5 -1
  37. package/plugins/mcp/index.ts +197 -78
  38. package/plugins/mcp/install.ts +5 -3
  39. package/plugins/mcp/mcp.ts +163 -11
  40. package/plugins/mcp/plugin.json +2 -1
  41. package/plugins/mcp/project.ts +47 -50
  42. package/plugins/memory/index.ts +4 -4
  43. package/plugins/memory/style.ts +13 -14
  44. package/plugins/mentions/candidates.ts +67 -0
  45. package/plugins/mentions/index.ts +12 -5
  46. package/plugins/mentions/plugin.json +1 -1
  47. package/plugins/mentions/style.ts +13 -14
  48. package/plugins/models/configure.ts +10 -9
  49. package/plugins/models/index.ts +27 -1
  50. package/plugins/modes/index.ts +13 -2
  51. package/plugins/print/index.ts +7 -4
  52. package/plugins/prompts/index.ts +0 -0
  53. package/plugins/renderers/index.ts +10 -5
  54. package/plugins/repeats/index.ts +8 -8
  55. package/plugins/schedule/index.ts +2 -0
  56. package/plugins/screenshot/browser.ts +10 -0
  57. package/plugins/sessions/index.ts +48 -2
  58. package/plugins/shell/index.ts +20 -25
  59. package/plugins/shell/plugin.json +1 -2
  60. package/plugins/shell/renderers.ts +9 -7
  61. package/plugins/shell/shell.ts +3 -1
  62. package/plugins/skills/index.ts +28 -19
  63. package/plugins/skills/project.ts +12 -7
  64. package/plugins/steer/index.ts +5 -4
  65. package/plugins/task/index.ts +80 -50
  66. package/plugins/task/plugin.json +6 -2
  67. package/plugins/task/style.ts +13 -14
  68. package/plugins/task/subagent.ts +67 -184
  69. package/plugins/todo/index.ts +39 -9
  70. package/plugins/tools/index.ts +9 -2
  71. package/plugins/tui/frontend.ts +139 -89
  72. package/plugins/tui/index.ts +2 -3
  73. package/plugins/tui/mentions.ts +11 -80
  74. package/plugins/tui/plugin.json +1 -1
  75. package/plugins/tui/screen.ts +55 -5
  76. package/plugins/tui/transcript.ts +17 -7
  77. package/plugins/tui/tui.ts +337 -101
  78. package/plugins/tui/vendor.ts +1 -1
  79. package/plugins/undo/checkpoint.ts +5 -3
  80. package/plugins/undo/index.ts +43 -14
  81. package/plugins/undo/style.ts +13 -14
  82. package/plugins/web/index.ts +7 -18
  83. package/plugins/web/plugin.json +1 -1
  84. package/plugins-dist/approval/index.js +363 -418
  85. package/plugins-dist/approval/policy.js +391 -508
  86. package/plugins-dist/approval/review.js +132 -158
  87. package/plugins-dist/approval/schema.js +50 -55
  88. package/plugins-dist/ask/index.js +115 -129
  89. package/plugins-dist/budget/index.js +27 -31
  90. package/plugins-dist/checks/checks.js +293 -329
  91. package/plugins-dist/checks/index.js +119 -139
  92. package/plugins-dist/checks/plugin.json +2 -1
  93. package/plugins-dist/checks/project.js +57 -65
  94. package/plugins-dist/commands/index.js +47 -29
  95. package/plugins-dist/compact/compact.js +233 -249
  96. package/plugins-dist/compact/index.js +98 -95
  97. package/plugins-dist/compact/style.js +9 -14
  98. package/plugins-dist/completions/index.js +30 -0
  99. package/plugins-dist/completions/plugin.json +9 -0
  100. package/plugins-dist/continue/index.js +40 -52
  101. package/plugins-dist/copy/index.js +40 -0
  102. package/plugins-dist/copy/plugin.json +9 -0
  103. package/plugins-dist/cost/index.js +98 -115
  104. package/plugins-dist/custom-commands/index.js +55 -72
  105. package/plugins-dist/editor/index.js +64 -72
  106. package/plugins-dist/fs/diff.js +111 -124
  107. package/plugins-dist/fs/fs.js +426 -469
  108. package/plugins-dist/fs/grep.js +262 -253
  109. package/plugins-dist/fs/index.js +20 -34
  110. package/plugins-dist/fs/plugin.json +1 -2
  111. package/plugins-dist/fs/renderers.js +100 -112
  112. package/plugins-dist/fs/style.js +11 -15
  113. package/plugins-dist/fs/sys.js +31 -43
  114. package/plugins-dist/hooks/index.js +107 -127
  115. package/plugins-dist/keys/index.js +27 -31
  116. package/plugins-dist/mcp/index.js +271 -199
  117. package/plugins-dist/mcp/install.js +123 -137
  118. package/plugins-dist/mcp/mcp.js +638 -577
  119. package/plugins-dist/mcp/plugin.json +3 -1
  120. package/plugins-dist/mcp/project.js +98 -115
  121. package/plugins-dist/memory/index.js +83 -88
  122. package/plugins-dist/memory/memory.js +111 -128
  123. package/plugins-dist/memory/style.js +9 -14
  124. package/plugins-dist/mentions/attach.js +91 -99
  125. package/plugins-dist/mentions/candidates.js +49 -0
  126. package/plugins-dist/mentions/index.js +71 -81
  127. package/plugins-dist/mentions/plugin.json +2 -1
  128. package/plugins-dist/mentions/style.js +9 -14
  129. package/plugins-dist/models/config.js +29 -43
  130. package/plugins-dist/models/configure.js +392 -473
  131. package/plugins-dist/models/context.js +14 -22
  132. package/plugins-dist/models/index.js +182 -189
  133. package/plugins-dist/models/provider.js +243 -307
  134. package/plugins-dist/models/saved.js +59 -71
  135. package/plugins-dist/modes/index.js +138 -165
  136. package/plugins-dist/plugins/index.js +34 -34
  137. package/plugins-dist/print/index.js +192 -175
  138. package/plugins-dist/prompts/index.js +81 -89
  139. package/plugins-dist/prompts/notes.js +31 -37
  140. package/plugins-dist/prompts/prompts.js +155 -193
  141. package/plugins-dist/prompts/results.js +40 -53
  142. package/plugins-dist/prompts/sys.js +39 -50
  143. package/plugins-dist/renderers/index.js +32 -32
  144. package/plugins-dist/repeats/index.js +131 -174
  145. package/plugins-dist/schedule/cron.js +49 -56
  146. package/plugins-dist/schedule/index.js +229 -247
  147. package/plugins-dist/schedule/store.js +93 -109
  148. package/plugins-dist/scratch/index.js +12 -18
  149. package/plugins-dist/screenshot/browser.js +136 -154
  150. package/plugins-dist/screenshot/index.js +37 -46
  151. package/plugins-dist/screenshot/sys.js +53 -65
  152. package/plugins-dist/screenshot/tool.js +98 -126
  153. package/plugins-dist/sessions/index.js +149 -117
  154. package/plugins-dist/shell/index.js +115 -135
  155. package/plugins-dist/shell/plugin.json +1 -2
  156. package/plugins-dist/shell/renderers.js +28 -33
  157. package/plugins-dist/shell/service.js +17 -23
  158. package/plugins-dist/shell/shell.js +307 -362
  159. package/plugins-dist/shell/sys.js +64 -79
  160. package/plugins-dist/skills/index.js +193 -211
  161. package/plugins-dist/skills/install.js +122 -149
  162. package/plugins-dist/skills/project.js +65 -73
  163. package/plugins-dist/skills/skills.js +135 -171
  164. package/plugins-dist/steer/index.js +108 -125
  165. package/plugins-dist/suggest/index.js +235 -259
  166. package/plugins-dist/task/index.js +130 -117
  167. package/plugins-dist/task/plugin.json +5 -2
  168. package/plugins-dist/task/style.js +9 -14
  169. package/plugins-dist/task/subagent.js +156 -279
  170. package/plugins-dist/todo/index.js +79 -63
  171. package/plugins-dist/tools/index.js +36 -42
  172. package/plugins-dist/tui/editor.js +145 -160
  173. package/plugins-dist/tui/frontend.js +639 -678
  174. package/plugins-dist/tui/history.js +34 -37
  175. package/plugins-dist/tui/index.js +16 -18
  176. package/plugins-dist/tui/markdown.js +203 -247
  177. package/plugins-dist/tui/mascot.js +266 -355
  178. package/plugins-dist/tui/mentions.js +67 -144
  179. package/plugins-dist/tui/plugin.json +1 -2
  180. package/plugins-dist/tui/render.js +35 -45
  181. package/plugins-dist/tui/screen.js +197 -180
  182. package/plugins-dist/tui/transcript.js +436 -468
  183. package/plugins-dist/tui/tui.js +1554 -1656
  184. package/plugins-dist/undo/checkpoint.js +95 -118
  185. package/plugins-dist/undo/index.js +185 -192
  186. package/plugins-dist/undo/snapshot.js +83 -99
  187. package/plugins-dist/undo/style.js +9 -14
  188. package/plugins-dist/update/index.js +26 -28
  189. package/plugins-dist/web/env.js +55 -68
  190. package/plugins-dist/web/index.js +80 -110
  191. package/plugins-dist/web/plugin.json +1 -2
  192. package/plugins-dist/web/renderers.js +4 -5
  193. package/plugins-dist/web/web.js +514 -593
  194. package/sdk/python/__pycache__/jade_plugin.cpython-312.pyc +0 -0
  195. package/sdk/python/jade_plugin.py +9 -2
  196. package/src/api.ts +1 -1
  197. package/src/host.ts +39 -4
  198. package/src/remote.ts +6 -1
  199. package/src/session.ts +489 -34
package/src/session.ts CHANGED
@@ -17,6 +17,7 @@ import {
17
17
  type Provider,
18
18
  type RemoteHookSpec,
19
19
  type RuntimeNotice,
20
+ type SessionRef,
20
21
  type State,
21
22
  type Tool,
22
23
  type UserInput,
@@ -30,10 +31,16 @@ import {
30
31
  type PluginModule,
31
32
  type PluginSource,
32
33
  type Secrets,
34
+ type ChildSession,
33
35
  type Session,
34
36
  type SessionContext,
35
37
  type SessionManager,
38
+ type SessionTool,
36
39
  type SessionUI,
40
+ type SpawnOptions,
41
+ type StatusSegment,
42
+ type Text,
43
+ type ToolMeta,
37
44
  type UI,
38
45
  } from "./api.ts";
39
46
  import { ambient, invoke, Scope, type Owner } from "./membrane.ts";
@@ -60,6 +67,8 @@ export interface SessionHost {
60
67
  service<T extends object>(name: string, caller: Owner): T | undefined;
61
68
  /** 服务的提供者 id */
62
69
  provider(name: string): string | undefined;
70
+ /** 核心自己的配置:用户 config.json 里的 "jade/core"(项目层的配置不能放宽这些上限) */
71
+ coreConfig(): Readonly<Record<string, unknown>>;
63
72
  /** 一个插件的密钥(第 8 节);会话 ctx 和进程 ctx 共享同一份 */
64
73
  secrets(plugin: string): Secrets;
65
74
  core: Owner;
@@ -76,9 +85,32 @@ interface Part {
76
85
  source: PluginSource;
77
86
  owner: Owner;
78
87
  gates: number;
79
- kernel: Plugin;
88
+ /** 现在的工具(已包装成以插件身份执行)。session() 返回之后注册、撤销的也改在这里,下一项工作开始前重挂 Runtime 生效 */
89
+ tools: Tool[];
90
+ /** 按现在的工具表生成交给内核的插件。插件被隔离后不再交出工具;id、版本不变,所以重挂不算插件变化 */
91
+ kernel(): Plugin;
80
92
  }
81
93
 
94
+ /** 子会话:谁开的、开它时要的东西(SpawnOptions) */
95
+ interface Child {
96
+ session: LiveSession;
97
+ ref: SessionRef;
98
+ /** 开它的插件 */
99
+ by: string;
100
+ label?: string;
101
+ tools?: (t: SessionTool) => boolean;
102
+ system?: string;
103
+ }
104
+
105
+ /** 核心放在子会话系统提示词最前面的委派说明(设计稿 live-tools-and-child-sessions 7.3) */
106
+ export const DELEGATION =
107
+ "You are a sub-agent: another agent delegated a task to you. You cannot see its conversation, so the task you are given is all you know about it. " +
108
+ "Nobody reads your intermediate messages; when you are done, reply with a self-contained report of what you did and found, including anything you could not do.";
109
+
110
+ /** 子会话的层数、同时数量的默认上限(7.2) */
111
+ export const DEFAULT_MAX_DEPTH = 1;
112
+ export const DEFAULT_MAX_ACTIVE = 8;
113
+
82
114
  interface Turn {
83
115
  stop?: { reason: unknown };
84
116
  wake?: () => void;
@@ -103,20 +135,75 @@ class LiveSession implements Session {
103
135
  #attended: () => boolean;
104
136
  /** 插件订阅的运行时通知(ctx.session.subscribe) */
105
137
  #watchers = new Set<{ fn: (n: RuntimeNotice) => void; owner: Owner }>();
138
+ /** 前端和核心订阅的运行时通知(Session.subscribe)。由会话自己持有、从当前的 Runtime 转发,重挂时不丢 */
139
+ #listeners = new Set<(n: RuntimeNotice) => void>();
140
+ #unsubscribe: (() => void) | undefined;
141
+ /** Runtime 建好了(attach 之后):session() 里登记的 afterTurn 等到这时才执行,那时 state() 才有 */
142
+ #attached = false;
143
+ /** 工具表变了,下一项工作开始前要重挂 Runtime */
144
+ #stale = false;
145
+ /** 重挂时旧实例已经 detach、新实例没建成:下次重挂不再 detach,离开时也不用 */
146
+ #loose = false;
147
+ #provider!: Provider;
148
+ #plugins!: () => Plugin[];
106
149
 
107
150
  readonly #store: LogStore;
151
+ /** 子会话的信息;顶层会话没有 */
152
+ readonly child: Child | undefined;
153
+ /** 第几层:顶层会话是 0 */
154
+ depth = 0;
155
+ /** 本会话开的、还没结束的子会话 */
156
+ readonly children = new Set<LiveSession>();
157
+ /** 子会话结束(Sessions.#end)的结果;结束时调用 onEnd(让出同时数量的名额) */
158
+ ended: Promise<{ sessionId: string; seq: number }> | undefined;
159
+ onEnd: (() => void) | undefined;
108
160
 
109
- constructor(id: string, store: LogStore, report: (m: string) => void, attended: () => boolean) {
161
+ constructor(id: string, store: LogStore, report: (m: string) => void, attended: () => boolean, child?: Child) {
110
162
  this.id = id;
111
163
  this.#store = store;
112
164
  this.#report = report;
113
165
  this.#attended = attended;
166
+ this.child = child;
167
+ if (child) this.depth = child.session.depth + 1;
168
+ }
169
+
170
+ get store(): LogStore {
171
+ return this.#store;
172
+ }
173
+
174
+ get provider(): Provider {
175
+ return this.#provider;
176
+ }
177
+
178
+ get left(): boolean {
179
+ return this.#left !== undefined;
180
+ }
181
+
182
+ /** 子会话只保留开它的插件要的工具(SpawnOptions.tools) */
183
+ keeps(t: Tool): boolean {
184
+ const keep = this.child?.tools;
185
+ if (!keep) return true;
186
+ try {
187
+ return keep(sessionTool(t)) === true;
188
+ } catch {
189
+ return false;
190
+ }
114
191
  }
115
192
 
116
193
  history(): Promise<LogEvent[]> {
117
194
  return readAll(this.#store, this.id);
118
195
  }
119
196
 
197
+ tool(name: string): SessionTool | undefined {
198
+ for (const p of this.parts) {
199
+ if (p.owner.scope.closed) continue;
200
+ const t = p.tools.find((x) => x.name === name);
201
+ if (!t || !this.keeps(t)) continue;
202
+ return sessionTool(t);
203
+ }
204
+ return undefined;
205
+ }
206
+
120
207
  get state(): State {
121
208
  return this.rt.state;
122
209
  }
@@ -187,7 +274,7 @@ class LiveSession implements Session {
187
274
  afterTurn(fn: () => void | Promise<void>, owner: Owner): void {
188
275
  if (this.#left) return;
189
276
  this.#after.push({ fn, owner });
190
- this.#kick();
277
+ if (this.#attached) this.#kick();
191
278
  }
192
279
 
193
280
  /** 离开会话:还没开始的输入全部拒绝、afterTurn 不再执行,再中止正在跑的一轮。之后的 send 直接拒绝 */
@@ -218,9 +305,27 @@ class LiveSession implements Session {
218
305
  return () => void this.#watchers.delete(w);
219
306
  }
220
307
 
221
- /** Runtime 建好之后调用一次:把通知转给订阅的插件,以插件身份执行,出错只报告 */
222
- attach(): void {
223
- this.rt.subscribe((n) => {
308
+ /** Runtime 建好之后调用一次。provider、plugins 留着给重挂用:plugins 每次按现在的工具表生成内核插件 */
309
+ attach(rt: Runtime, provider: Provider, plugins: () => Plugin[]): void {
310
+ this.#provider = provider;
311
+ this.#plugins = plugins;
312
+ this.#use(rt);
313
+ this.#attached = true;
314
+ if (this.#after.length > 0) this.#kick();
315
+ }
316
+
317
+ /** 换上一个 Runtime:通知从它转给订阅者。插件的回调以插件身份执行;出错只报告 */
318
+ #use(rt: Runtime): void {
319
+ this.#unsubscribe?.();
320
+ this.rt = rt;
321
+ this.#unsubscribe = rt.subscribe((n) => {
322
+ for (const fn of this.#listeners) {
323
+ try {
324
+ fn(n);
325
+ } catch {
326
+ // 和内核一样:订阅者的错误不影响运行
327
+ }
328
+ }
224
329
  for (const w of this.#watchers) {
225
330
  if (w.owner.scope.closed) continue;
226
331
  try {
@@ -232,6 +337,47 @@ class LiveSession implements Session {
232
337
  });
233
338
  }
234
339
 
340
+ /** 工具表变了(会话中途注册、撤销工具,插件被隔离):下一项工作开始前重挂。几次改动合并成一次 */
341
+ invalidate(): void {
342
+ if (this.#attached && !this.#left) this.#stale = true;
343
+ }
344
+
345
+ /**
346
+ * 重挂:detach 旧实例,按现在的工具表 resume 同一个会话(设计稿 live-tools-and-child-sessions 3.2)。
347
+ * 只在两项工作之间执行,内核这时不在跑。插件清单(id、版本)不变,内核不写 plugins.changed。
348
+ * 失败时这项工作失败,下一项工作再试
349
+ */
350
+ async #remount(): Promise<void> {
351
+ this.#stale = false;
352
+ if (this.rt.phase === "ended") return;
353
+ try {
354
+ if (!this.#loose) {
355
+ await this.rt.detach();
356
+ this.#loose = true;
357
+ }
358
+ const rt = await Runtime.resume({ store: this.#store, provider: this.#provider, plugins: this.#plugins(), sessionId: this.id });
359
+ this.#loose = false;
360
+ this.#use(rt);
361
+ } catch (e) {
362
+ this.#stale = true;
363
+ throw new Error(`session ${this.id}: could not update its tools: ${e instanceof Error ? e.message : String(e)}`);
364
+ }
365
+ }
366
+
367
+ /** 结束会话(session.ended),子会话用完时。重挂到一半(旧实例已经 detach)时先恢复一个实例来写 */
368
+ async close(): Promise<void> {
369
+ if (this.#loose) {
370
+ this.#use(await Runtime.resume({ store: this.#store, provider: this.#provider, plugins: this.#plugins(), sessionId: this.id }));
371
+ this.#loose = false;
372
+ }
373
+ if (this.rt.phase !== "ended") await this.rt.close();
374
+ }
375
+
376
+ /** 宿主离开会话时 detach;重挂到一半(旧实例已经 detach)时不用再写 */
377
+ async detach(): Promise<void> {
378
+ if (!this.#loose) await this.rt.detach();
379
+ }
380
+
235
381
  abort(reason?: unknown): void {
236
382
  this.rt.abort(reason);
237
383
  // 停在等待人工审批时内核没有在跑,信号结束不了这一轮
@@ -242,7 +388,8 @@ class LiveSession implements Session {
242
388
  }
243
389
 
244
390
  subscribe(fn: (n: RuntimeNotice) => void): () => void {
245
- return this.rt.subscribe(fn);
391
+ this.#listeners.add(fn);
392
+ return () => void this.#listeners.delete(fn);
246
393
  }
247
394
 
248
395
  #kick(): void {
@@ -260,6 +407,11 @@ class LiveSession implements Session {
260
407
  const job = this.#queue.shift();
261
408
  if (job) {
262
409
  try {
410
+ if (this.#stale) {
411
+ await this.#remount();
412
+ // 重挂期间离开了会话:中止落在旧实例上,这项工作不再开始
413
+ if (this.#left) throw this.#left;
414
+ }
263
415
  await job.run();
264
416
  job.resolve();
265
417
  } catch (e) {
@@ -290,6 +442,11 @@ export class Sessions implements SessionManager {
290
442
  #store: LogStore | undefined;
291
443
  /** 换会话串行进行 */
292
444
  #switching: Promise<unknown> = Promise.resolve();
445
+ /** 正在运行的子会话数,和等着开的 */
446
+ #running = 0;
447
+ #waiting: (() => void)[] = [];
448
+ /** 子会话的对话框排成一队,一次一个(7.4) */
449
+ #dialogs: Promise<unknown> = Promise.resolve();
293
450
 
294
451
  constructor(host: SessionHost) {
295
452
  this.#host = host;
@@ -324,19 +481,27 @@ export class Sessions implements SessionManager {
324
481
  if (!provider) throw new ServiceUnavailable("provider@1", "(none): no active plugin provides a model");
325
482
  const store = host.service<LogStore>("store@1", host.core) ?? (this.#store ??= new JsonlLogStore(path.join(host.home, "sessions")));
326
483
 
484
+ if (opts.fork && opts.resume !== undefined) throw new Error("sessions.open: resume and fork cannot be used together");
327
485
  const s: LiveSession = new LiveSession(opts.resume ?? crypto.randomUUID(), store, host.report, () => this.#guarded(s));
486
+ // 复制出的会话:先写好日志,再和恢复一样打开。打开失败时留下的日志没人引用,不影响原会话
487
+ if (opts.fork) await copyLog(store, opts.fork.session, opts.fork.before, s.id);
488
+ // 直接恢复一个子会话(例如按 id):层数从日志里的 parent 往上数
489
+ if (opts.resume !== undefined || opts.fork) s.depth = await depthOf(store, s.id);
490
+ let rt: Runtime;
491
+ const core = this.#corePlugin(s);
492
+ const kernelPlugins = () => [core, ...s.parts.map((p) => p.kernel())];
328
493
  try {
329
494
  for (const p of host.active()) if (p.module.session) await this.#join(s, p);
330
- const plugins = [this.#corePlugin(s), ...s.parts.map((p) => p.kernel)];
331
- s.rt = opts.resume
495
+ const plugins = kernelPlugins();
496
+ rt = opts.resume !== undefined || opts.fork
332
497
  ? await Runtime.resume({ store, provider, plugins, sessionId: s.id })
333
498
  : await Runtime.create({ store, provider, plugins, sessionId: s.id });
334
499
  } catch (e) {
335
500
  await this.#closeParts(s);
336
501
  throw e;
337
502
  }
338
- s.attach();
339
- s.rt.subscribe((n) => {
503
+ s.attach(rt, provider, kernelPlugins);
504
+ s.subscribe((n) => {
340
505
  if (n.type === "hook-error") host.report(`plugin ${n.info.plugin} failed at ${n.info.point}: ${n.info.error instanceof Error ? n.info.error.message : String(n.info.error)}`);
341
506
  });
342
507
  // 提交:新会话成为当前会话,然后旧会话离开
@@ -346,6 +511,157 @@ export class Sessions implements SessionManager {
346
511
  return s;
347
512
  }
348
513
 
514
+ /** 子会话的上限(7.2):用户 config.json 的 "jade/core" */
515
+ #limits(): { maxDepth: number; maxActive: number } {
516
+ const c = this.#host.coreConfig();
517
+ const n = (v: unknown, d: number, min: number) => (typeof v === "number" && Number.isInteger(v) && v >= min ? v : d);
518
+ return { maxDepth: n(c.maxDepth, DEFAULT_MAX_DEPTH, 0), maxActive: n(c.maxActive, DEFAULT_MAX_ACTIVE, 1) };
519
+ }
520
+
521
+ /** 开子会话(ctx.session.spawn):所有插件照常加入,Runtime.create 带 parent。不会成为当前会话 */
522
+ async #spawn(parent: LiveSession, opts: SpawnOptions, by: string): Promise<ChildSession> {
523
+ if (!opts || typeof opts !== "object" || opts.parent?.sessionId !== parent.id || typeof opts.parent.eventId !== "string") {
524
+ throw new Error(`plugin ${by}: spawn needs parent: the ToolContext.parent of a tool call in this session`);
525
+ }
526
+ if (parent.left) throw new Error(`session ${parent.id} was closed`);
527
+ const { maxDepth, maxActive } = this.#limits();
528
+ if (parent.depth + 1 > maxDepth) {
529
+ throw new Error(
530
+ maxDepth === 0
531
+ ? `sub-agents are turned off ("jade/core": { "maxDepth": 0 } in config.json)`
532
+ : `sub-agents can be nested at most ${maxDepth} level${maxDepth > 1 ? "s" : ""} deep; this session is already at level ${parent.depth} (raise "jade/core": { "maxDepth" } in config.json)`,
533
+ );
534
+ }
535
+ const signal = opts.signal instanceof AbortSignal ? opts.signal : undefined;
536
+ // 同时数量的上限:顶层会话开的等前面的结束;子会话开的直接报错,它自己占着名额,等下去可能谁都等不到
537
+ while (this.#running >= maxActive) {
538
+ if (parent.depth > 0) throw new Error(`${maxActive} sub-agents are already running; a sub-agent cannot wait for a slot (raise "jade/core": { "maxActive" } in config.json)`);
539
+ await new Promise<void>((resolve, reject) => {
540
+ const wake = () => {
541
+ signal?.removeEventListener("abort", stop);
542
+ resolve();
543
+ };
544
+ const stop = () => {
545
+ const i = this.#waiting.indexOf(wake);
546
+ if (i >= 0) this.#waiting.splice(i, 1);
547
+ reject(signal!.reason);
548
+ };
549
+ if (signal?.aborted) return stop();
550
+ signal?.addEventListener("abort", stop, { once: true });
551
+ this.#waiting.push(wake);
552
+ });
553
+ }
554
+ if (signal?.aborted) {
555
+ // 被叫醒时已经中止:名额让给下一个等着的
556
+ this.#waiting.shift()?.();
557
+ throw signal.reason;
558
+ }
559
+ this.#running++;
560
+ let released = false;
561
+ const release = () => {
562
+ if (released) return;
563
+ released = true;
564
+ this.#running--;
565
+ this.#waiting.shift()?.();
566
+ };
567
+ if (parent.left) {
568
+ release();
569
+ throw new Error(`session ${parent.id} was closed`);
570
+ }
571
+ const host = this.#host;
572
+ const provider = opts.provider ?? parent.provider;
573
+ const child: Child = {
574
+ session: parent,
575
+ ref: { sessionId: opts.parent.sessionId, eventId: opts.parent.eventId },
576
+ by,
577
+ ...(typeof opts.label === "string" && opts.label ? { label: opts.label } : {}),
578
+ ...(typeof opts.tools === "function" ? { tools: opts.tools } : {}),
579
+ ...(typeof opts.system === "string" && opts.system ? { system: opts.system } : {}),
580
+ };
581
+ const s: LiveSession = new LiveSession(crypto.randomUUID(), parent.store, host.report, () => this.#guarded(s), child);
582
+ const core = this.#corePlugin(s);
583
+ const delegation = this.#delegation(child);
584
+ const kernelPlugins = () => [core, ...s.parts.map((p) => p.kernel()), delegation];
585
+ let rt: Runtime;
586
+ try {
587
+ for (const p of host.active()) if (p.module.session) await this.#join(s, p);
588
+ rt = await Runtime.create({ store: s.store, provider, plugins: kernelPlugins(), sessionId: s.id, parent: child.ref });
589
+ } catch (e) {
590
+ await this.#closeParts(s);
591
+ release();
592
+ throw e;
593
+ }
594
+ s.attach(rt, provider, kernelPlugins);
595
+ s.subscribe((n) => {
596
+ if (n.type === "hook-error") host.report(`plugin ${n.info.plugin} failed at ${n.info.point} in a sub-agent: ${n.info.error instanceof Error ? n.info.error.message : String(n.info.error)}`);
597
+ });
598
+ s.onEnd = release;
599
+ // Runtime 建好了才算父会话的子会话:父会话离开时结束它要用 Runtime。开的期间父会话离开了:马上结束
600
+ parent.children.add(s);
601
+ if (parent.left) {
602
+ await this.#end(s);
603
+ throw new Error(`session ${parent.id} was closed`);
604
+ }
605
+ let closing: Promise<{ sessionId: string; seq: number }> | undefined;
606
+ return {
607
+ id: s.id,
608
+ send: (input) => s.send(input),
609
+ get state() {
610
+ return s.state;
611
+ },
612
+ subscribe: (fn) => s.subscribe(fn),
613
+ abort: (reason) => s.abort(new Error(reason ?? `stopped by plugin ${by}`)),
614
+ close: () => (closing ??= this.#end(s)),
615
+ };
616
+ }
617
+
618
+ /** 结束子会话:先结束它的子会话,中止正在跑的工作,写 session.ended,关闭插件的作用域。返回 ChildRef */
619
+ async #end(s: LiveSession): Promise<{ sessionId: string; seq: number }> {
620
+ if (s.ended) return s.ended;
621
+ s.ended = (async () => {
622
+ s.leave();
623
+ for (const c of [...s.children]) await this.#end(c);
624
+ await s.idle();
625
+ try {
626
+ await s.close();
627
+ } catch (e) {
628
+ this.#host.report(`sub-agent session ${s.id}: could not end it: ${e instanceof Error ? e.message : String(e)}`);
629
+ }
630
+ await this.#closeParts(s);
631
+ s.child?.session.children.delete(s);
632
+ s.onEnd?.();
633
+ return { sessionId: s.id, seq: s.rt.state.lastSeq };
634
+ })();
635
+ return s.ended;
636
+ }
637
+
638
+ /**
639
+ * 子会话里的 ui@1:没有会话界面(状态栏、输入框);对话框在整个进程里排成一队,一次一个,标题前标上是哪个子 Agent(7.4)
640
+ */
641
+ #childUI(ui: UI, s: LiveSession): UI {
642
+ const name = s.child?.label ?? "sub-agent";
643
+ const queued = <T>(fn: () => Promise<T>): Promise<T> => {
644
+ const run = this.#dialogs.then(fn);
645
+ this.#dialogs = run.catch(() => {});
646
+ return run;
647
+ };
648
+ return new Proxy(ui, {
649
+ get: (target, prop) => {
650
+ if (prop === "session") return undefined;
651
+ if (prop === "select") {
652
+ return (req: Parameters<UI["select"]>[0], signal?: AbortSignal) =>
653
+ queued(() => (signal?.aborted ? Promise.resolve(undefined) : target.select({ ...req, title: `[${name}] ${req.title}` }, signal)));
654
+ }
655
+ if (prop === "input") {
656
+ return (req: Parameters<UI["input"]>[0], signal?: AbortSignal) =>
657
+ queued(() => (signal?.aborted ? Promise.resolve(undefined) : target.input({ ...req, title: `[${name}] ${req.title}` }, signal)));
658
+ }
659
+ const v = Reflect.get(target, prop);
660
+ return typeof v === "function" ? v.bind(target) : v;
661
+ },
662
+ });
663
+ }
664
+
349
665
  /** 一个插件加入会话:执行它的 session(),失败就撤销它这次的注册 */
350
666
  async #join(s: LiveSession, p: { source: PluginSource; module: PluginModule; owner: Owner; mark?: (p: Plugin) => Plugin }): Promise<void> {
351
667
  const host = this.#host;
@@ -353,9 +669,13 @@ export class Sessions implements SessionManager {
353
669
  const id = manifest.id;
354
670
  const scope = new Scope(id);
355
671
  const owner: Owner = { plugin: id, scope };
672
+ /** 这个插件的工具,已包装;加入成功后就是 part.tools */
356
673
  const tools: Tool[] = [];
357
674
  const hooks: (LocalHookSpec | RemoteHookSpec)[] = [];
358
675
  let open = true;
676
+ let part: Part | undefined;
677
+ /** 现在交给内核的工具里叫这个名字的是谁的(被隔离的插件的工具已经不交给内核,不算) */
678
+ const holder = (name: string) => s.parts.find((x) => !x.owner.scope.closed && x.tools.some((t) => t.name === name));
359
679
  const declared = (name: string, lists: (readonly string[] | undefined)[]) => {
360
680
  if (scope.closed) throw new StaleContext(id);
361
681
  if (!lists.some((l) => l?.includes(name))) throw new Error(`plugin ${id}: ${name} is not declared in plugin.json`);
@@ -369,6 +689,9 @@ export class Sessions implements SessionManager {
369
689
  // 作用域已经关了:没有要清理的
370
690
  }
371
691
  }
692
+ /** 子会话里的 ui@1 换成排队、标名字的那份 */
693
+ const forSession = <T extends object>(name: string, h: T | undefined): T | undefined =>
694
+ h && s.child && name === "ui@1" ? (this.#childUI(h as unknown as UI, s) as unknown as T) : h;
372
695
  const uiCall = (fn: () => void) => {
373
696
  try {
374
697
  fn();
@@ -385,25 +708,32 @@ export class Sessions implements SessionManager {
385
708
  secrets: scopedSecrets(host.secrets(id), () => scope.closed, id),
386
709
  ...(sessionUI
387
710
  ? {
388
- status: (text: string | undefined) => uiCall(() => sessionUI.status(text === undefined ? undefined : String(text))),
389
- ...(sessionUI.draft ? { input: sessionUI.draft } : {}),
711
+ status: (text: string | StatusSegment | undefined) => uiCall(() => sessionUI.status(statusSegment(text))),
712
+ // 带样式的文字(Text)原样交给前端,由它决定怎么画
713
+ ...(sessionUI.panel ? { panel: (text: Text | undefined) => uiCall(() => sessionUI.panel!(text)) } : {}),
714
+ // 项目层插件拿不到输入框(第 7 节):克隆的仓库不能替用户写字
715
+ ...(sessionUI.draft && layer !== "project" ? { input: sessionUI.draft } : {}),
390
716
  }
391
717
  : {}),
392
718
  require: <T extends object>(name: string): T => {
393
719
  declared(name, [manifest.requires]);
394
- const h = host.service<T>(name, owner);
720
+ const h = forSession<T>(name, host.service<T>(name, owner));
395
721
  if (!h) throw new ServiceUnavailable(name, "(none)");
396
722
  return h;
397
723
  },
398
724
  service: <T extends object>(name: string): T | undefined => {
399
725
  declared(name, [manifest.requires, manifest.optional]);
400
- return host.service<T>(name, owner);
726
+ return forSession<T>(name, host.service<T>(name, owner));
401
727
  },
402
728
  effect: async (start) => {
403
729
  if (scope.closed) throw new StaleContext(id);
404
730
  const d = await ambient.run(owner, start);
405
731
  if (typeof d === "function") scope.add(d);
406
732
  },
733
+ report: (message) => {
734
+ if (scope.closed) throw new StaleContext(id);
735
+ host.report(`${id}: ${String(message)}`);
736
+ },
407
737
  session: {
408
738
  id: s.id,
409
739
  afterTurn: (fn) => {
@@ -418,7 +748,12 @@ export class Sessions implements SessionManager {
418
748
  abort: (reason) => {
419
749
  if (scope.closed) throw new StaleContext(id);
420
750
  if (layer === "project") throw new Error(`plugin ${id}: project plugins cannot stop turns on the user's behalf`);
421
- s.abort(new Error(reason ?? `stopped by plugin ${id}`));
751
+ const why = new Error(reason ?? `stopped by plugin ${id}`);
752
+ s.abort(why);
753
+ // 子会话里替用户喊停(例如审批时按 Esc):用户要停的是整件事,顶层会话这一轮也停,不让父会话拿着结果接着干
754
+ let top = s;
755
+ while (top.child) top = top.child.session;
756
+ if (top !== s) top.abort(why);
422
757
  },
423
758
  state: () => {
424
759
  if (scope.closed) throw new StaleContext(id);
@@ -432,11 +767,40 @@ export class Sessions implements SessionManager {
432
767
  scope.add(off);
433
768
  return off;
434
769
  },
770
+ tool: (name) => {
771
+ if (scope.closed) throw new StaleContext(id);
772
+ return s.tool(name);
773
+ },
774
+ ...(s.child ? { parent: { ...s.child.ref } } : {}),
775
+ depth: s.depth,
776
+ canSpawn: layer !== "project" && s.depth < this.#limits().maxDepth,
777
+ spawn: (opts) => {
778
+ if (scope.closed) return Promise.reject(new StaleContext(id));
779
+ if (layer === "project") return Promise.reject(new Error(`plugin ${id}: project plugins cannot open sub-agent sessions`));
780
+ return this.#spawn(s, opts, id);
781
+ },
435
782
  },
436
783
  kernel: {
437
784
  tool: (t) => {
438
- if (!open) throw new Error(`plugin ${id}: tools can only be registered while session() runs`);
439
- tools.push(t);
785
+ if (scope.closed) throw new StaleContext(id);
786
+ const tool = liveTool({ ...t, ...toolMeta(id, layer, t) }, owner);
787
+ if (!open) {
788
+ // session() 返回之后注册的从下一项工作起生效(重挂 Runtime)。重名的在这里拒绝,不能让重挂失败
789
+ if (!part) throw new Error(`plugin ${id}: did not join session ${s.id}`);
790
+ const other = holder(tool.name);
791
+ if (other) throw new Error(`plugin ${id}: tool ${tool.name} is already registered by ${other.source.manifest.id}`);
792
+ }
793
+ tools.push(tool);
794
+ if (!open) s.invalidate();
795
+ let done = false;
796
+ return () => {
797
+ if (done) return;
798
+ done = true;
799
+ const i = tools.indexOf(tool);
800
+ if (i < 0) return;
801
+ tools.splice(i, 1);
802
+ if (part) s.invalidate();
803
+ };
440
804
  },
441
805
  hook: (h) => {
442
806
  if (!open) throw new Error(`plugin ${id}: hooks can only be registered while session() runs`);
@@ -458,32 +822,34 @@ export class Sessions implements SessionManager {
458
822
  }
459
823
  open = false;
460
824
  // 内核构造 Runtime 时会因为重名工具、不合法的 hook 拒绝整个会话:提前检查,只排除这一个插件
461
- const taken = new Set(s.parts.flatMap((x) => x.kernel.tools?.map((t) => t.name) ?? []));
462
- const clash = tools.find((t) => taken.has(t.name));
463
- const problem = clash
464
- ? `tool ${clash.name} is already registered by ${s.parts.find((x) => x.kernel.tools?.some((t) => t.name === clash.name))!.source.manifest.id}`
465
- : compatProblem(id, manifest.version, hooks);
825
+ const clash = tools.find((t) => holder(t.name));
826
+ const problem = clash ? `tool ${clash.name} is already registered by ${holder(clash.name)!.source.manifest.id}` : compatProblem(id, manifest.version, hooks);
466
827
  if (problem) {
467
828
  host.untrack(id, scope);
468
829
  await scope.close();
469
830
  host.report(`plugin ${id} did not join session ${s.id}: ${problem}`);
470
831
  return;
471
832
  }
472
- const part: Part = {
833
+ const live = hooks.map((h) => liveHook(h, owner));
834
+ part = {
473
835
  source: p.source,
474
836
  owner,
475
837
  gates: hooks.filter((h) => h.kind === "gate" && h.point === "tool.gate").length,
476
- kernel: this.#confirmed(p, kernelPlugin({
477
- id,
478
- version: manifest.version,
479
- layer: KERNEL_LAYER[layer],
480
- // 写日志的能力调用时才检查,推不出来(definePlugin 只补 hook 用到的);jade 的插件都可以写
481
- needs: ["log:record", "log:emit"],
482
- tools: tools.map((t) => liveTool(t, owner)),
483
- hooks: hooks.map((h) => liveHook(h, owner)),
484
- })),
838
+ tools,
839
+ kernel: () =>
840
+ this.#confirmed(p, kernelPlugin({
841
+ id,
842
+ version: manifest.version,
843
+ layer: KERNEL_LAYER[layer],
844
+ // 写日志的能力调用时才检查,推不出来(definePlugin 只补 hook 用到的);jade 的插件都可以写
845
+ needs: ["log:record", "log:emit"],
846
+ tools: scope.closed ? [] : tools.filter((t) => s.keeps(t)),
847
+ hooks: live,
848
+ })),
485
849
  };
486
850
  s.parts.push(part);
851
+ // 插件被隔离(作用域关闭):它的工具从下一项工作起不再给模型看
852
+ scope.add(() => s.invalidate());
487
853
  }
488
854
 
489
855
  /** 项目层插件交给内核的插件要用确认时拿到的 mark 标记,否则内核拒绝整个会话 */
@@ -498,6 +864,8 @@ export class Sessions implements SessionManager {
498
864
  * 获取失败也只当作没有:界面上的东西坏了不该让插件加入不了会话
499
865
  */
500
866
  #sessionUI(s: LiveSession, plugin: string, owner: Owner): SessionUI | undefined {
867
+ // 子会话不是当前会话,没有自己的界面(4.2)
868
+ if (s.child) return undefined;
501
869
  try {
502
870
  const ui = this.#host.service<UI>("ui@1", owner);
503
871
  return ui?.session?.({ session: s.id, plugin });
@@ -517,6 +885,22 @@ export class Sessions implements SessionManager {
517
885
  return kernelPlugin({ id: CORE_PLUGIN_ID, version: API_VERSION, layer: "distro", hooks: [{ kind: "gate", point: "tool.gate", fn: gate }] });
518
886
  }
519
887
 
888
+ /**
889
+ * 子会话的委派说明和开它的插件给的系统提示词(7.3)。context.build 按顺序执行,别的插件(jade/prompts)
890
+ * 把自己的段落放在已有段落之前,最后执行的才能放在最前面:所以单独一个插件,hook 的 order 设得很大
891
+ */
892
+ #delegation(child: Child): Plugin {
893
+ const seg = (text: string, by: string) => ({ text, stability: "stable" as const, origin: { by: "plugin" as const, id: by }, trust: "trusted" as const });
894
+ const head = [seg(DELEGATION, CORE_PLUGIN_ID), ...(child.system ? [seg(child.system, child.by)] : [])];
895
+ return kernelPlugin({
896
+ id: `${CORE_PLUGIN_ID}/delegation`,
897
+ version: API_VERSION,
898
+ layer: "distro",
899
+ // order 大:任何层的插件之后执行
900
+ hooks: [{ kind: "transform", point: "context.build", order: 1_000_000, fn: (req) => ({ ...req, system: [...head, ...req.system] }) }],
901
+ });
902
+ }
903
+
520
904
  /** approval@1 的提供者(不能是项目层插件)在这个会话里有仍然有效的 tool.gate */
521
905
  #guarded(s: LiveSession): boolean {
522
906
  const approval = this.#host.provider("approval@1");
@@ -526,9 +910,11 @@ export class Sessions implements SessionManager {
526
910
  /** 离开会话:中止正在跑的工作,等它停下,detach,关闭插件的会话作用域 */
527
911
  async #leave(s: LiveSession): Promise<void> {
528
912
  s.leave();
913
+ // 它开的子会话一并结束:正在等子会话的工具调用随之结束
914
+ for (const c of [...s.children]) await this.#end(c);
529
915
  await s.idle();
530
916
  try {
531
- await s.rt.detach();
917
+ await s.detach();
532
918
  } catch (e) {
533
919
  this.#host.report(`session ${s.id}: detach failed: ${e instanceof Error ? e.message : String(e)}`);
534
920
  }
@@ -552,6 +938,43 @@ function compatProblem(id: string, version: string, hooks: (LocalHookSpec | Remo
552
938
  }
553
939
  }
554
940
 
941
+ /** 状态栏的一段只留认得的字段:文字都换成字符串,不认得的 tone 去掉 */
942
+ function statusSegment(s: string | StatusSegment | undefined): string | StatusSegment | undefined {
943
+ if (s === undefined || typeof s !== "object" || s === null) return s === undefined ? undefined : String(s);
944
+ const tones = ["ok", "warn", "error", "accent"];
945
+ return {
946
+ text: String(s.text ?? ""),
947
+ ...(s.short !== undefined ? { short: String(s.short) } : {}),
948
+ ...(tones.includes(s.tone as string) ? { tone: s.tone } : {}),
949
+ ...(s.keep === true ? { keep: true } : {}),
950
+ };
951
+ }
952
+
953
+ /**
954
+ * 工具的 meta 只留认得的字段(字段名都是字符串),写错了抛错:插件加入会话失败,比别的插件悄悄认不出这个工具好查。
955
+ * 项目层插件的 shell 不算:审批按它把只读命令直接放行、只读的子 Agent 也留着这个工具,克隆的仓库不能自己声明这个。
956
+ * 去掉之后它就是普通的工具,照常经过审批
957
+ */
958
+ function toolMeta(plugin: string, layer: PluginSource["layer"], t: { name: string; meta?: unknown }): { meta?: ToolMeta } {
959
+ if (t.meta === undefined) return {};
960
+ const m = t.meta as Record<string, unknown> | null;
961
+ if (typeof m !== "object" || m === null) throw new Error(`plugin ${plugin}: tool ${t.name}: meta must be an object`);
962
+ const meta: ToolMeta = {};
963
+ for (const k of ["writes", "shell"] as const) {
964
+ if (m[k] === undefined) continue;
965
+ if (typeof m[k] !== "string" || !m[k]) throw new Error(`plugin ${plugin}: tool ${t.name}: meta.${k} must be the name of an input field`);
966
+ if (k === "shell" && layer === "project") continue;
967
+ meta[k] = m[k];
968
+ }
969
+ return { meta };
970
+ }
971
+
972
+ /** 工具的声明部分(给插件看的 SessionTool),meta 是拷贝 */
973
+ function sessionTool(t: Tool & { meta?: ToolMeta }): SessionTool {
974
+ const { name, description, inputSchema, effect, concurrency, idempotent, meta } = t;
975
+ return { name, description, inputSchema, effect, concurrency, idempotent, ...(meta ? { meta: { ...meta } } : {}) };
976
+ }
977
+
555
978
  /** 插件的工具:以插件身份执行;插件被隔离后返回错误结果(由内核转成 tool_result) */
556
979
  function liveTool(t: Tool, owner: Owner): Tool {
557
980
  return { ...t, execute: (input, ctx) => invoke(owner, `tool ${t.name}`, () => t.execute(input, ctx)) };
@@ -575,3 +998,35 @@ function liveHook(h: LocalHookSpec | RemoteHookSpec, owner: Owner): LocalHookSpe
575
998
  };
576
999
  return { ...h, fn: wrapped } as LocalHookSpec;
577
1000
  }
1001
+
1002
+ /** 会话是第几层子会话:沿着 session.started 里的 parent 往上数(内核保证引用能解析到,宪法 3.4) */
1003
+ async function depthOf(store: LogStore, sessionId: string): Promise<number> {
1004
+ let depth = 0;
1005
+ let id: string | undefined = sessionId;
1006
+ const seen = new Set<string>();
1007
+ while (id && !seen.has(id) && depth < 100) {
1008
+ seen.add(id);
1009
+ let parent: string | undefined;
1010
+ for await (const e of store.read(id)) {
1011
+ if (e.type === "session.started") parent = (e.data as { parent?: SessionRef }).parent?.sessionId;
1012
+ break;
1013
+ }
1014
+ if (!parent) break;
1015
+ depth++;
1016
+ id = parent;
1017
+ }
1018
+ return depth;
1019
+ }
1020
+
1021
+ /**
1022
+ * 把 from 的日志里 seq 小于 before 的事件写成新会话 to 的日志(OpenOptions.fork)。before 要是一条消息输入的 seq:
1023
+ * 这样复制出的会话停在一轮结束之后、下一条消息之前,恢复时没有没做完的一轮
1024
+ */
1025
+ async function copyLog(store: LogStore, from: string, before: number, to: string): Promise<void> {
1026
+ const events = await readAll(store, from);
1027
+ const at = events.find((e) => e.seq === before);
1028
+ if (!at || at.type !== "input.received" || (at.data as UserInput).kind !== "message") {
1029
+ throw new Error(`sessions.open: seq ${before} of session ${from} is not a message from the user`);
1030
+ }
1031
+ await store.append(to, events.filter((e) => e.seq < before));
1032
+ }