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