@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/dist/session.js CHANGED
@@ -12,6 +12,12 @@ export const NO_APPROVAL_REASON = "No permission plugin is active in this sessio
12
12
  /** 有插件要人工审批、但没有审批插件来问时,这一轮结束的原因 */
13
13
  export const NO_APPROVER_ERROR = "A plugin asked for the user's approval, but no approval plugin is active in this session to ask.";
14
14
  const KERNEL_LAYER = { bundled: "distro", user: "user", project: "project" };
15
+ /** 核心放在子会话系统提示词最前面的委派说明(设计稿 live-tools-and-child-sessions 7.3) */
16
+ export const DELEGATION = "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. " +
17
+ "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.";
18
+ /** 子会话的层数、同时数量的默认上限(7.2) */
19
+ export const DEFAULT_MAX_DEPTH = 1;
20
+ export const DEFAULT_MAX_ACTIVE = 8;
15
21
  class LiveSession {
16
22
  id;
17
23
  parts = [];
@@ -31,16 +37,71 @@ class LiveSession {
31
37
  #attended;
32
38
  /** 插件订阅的运行时通知(ctx.session.subscribe) */
33
39
  #watchers = new Set();
40
+ /** 前端和核心订阅的运行时通知(Session.subscribe)。由会话自己持有、从当前的 Runtime 转发,重挂时不丢 */
41
+ #listeners = new Set();
42
+ #unsubscribe;
43
+ /** Runtime 建好了(attach 之后):session() 里登记的 afterTurn 等到这时才执行,那时 state() 才有 */
44
+ #attached = false;
45
+ /** 工具表变了,下一项工作开始前要重挂 Runtime */
46
+ #stale = false;
47
+ /** 重挂时旧实例已经 detach、新实例没建成:下次重挂不再 detach,离开时也不用 */
48
+ #loose = false;
49
+ #provider;
50
+ #plugins;
34
51
  #store;
35
- constructor(id, store, report, attended) {
52
+ /** 子会话的信息;顶层会话没有 */
53
+ child;
54
+ /** 第几层:顶层会话是 0 */
55
+ depth = 0;
56
+ /** 本会话开的、还没结束的子会话 */
57
+ children = new Set();
58
+ /** 子会话结束(Sessions.#end)的结果;结束时调用 onEnd(让出同时数量的名额) */
59
+ ended;
60
+ onEnd;
61
+ constructor(id, store, report, attended, child) {
36
62
  this.id = id;
37
63
  this.#store = store;
38
64
  this.#report = report;
39
65
  this.#attended = attended;
66
+ this.child = child;
67
+ if (child)
68
+ this.depth = child.session.depth + 1;
69
+ }
70
+ get store() {
71
+ return this.#store;
72
+ }
73
+ get provider() {
74
+ return this.#provider;
75
+ }
76
+ get left() {
77
+ return this.#left !== undefined;
78
+ }
79
+ /** 子会话只保留开它的插件要的工具(SpawnOptions.tools) */
80
+ keeps(t) {
81
+ const keep = this.child?.tools;
82
+ if (!keep)
83
+ return true;
84
+ try {
85
+ return keep(sessionTool(t)) === true;
86
+ }
87
+ catch {
88
+ return false;
89
+ }
40
90
  }
41
91
  history() {
42
92
  return readAll(this.#store, this.id);
43
93
  }
94
+ tool(name) {
95
+ for (const p of this.parts) {
96
+ if (p.owner.scope.closed)
97
+ continue;
98
+ const t = p.tools.find((x) => x.name === name);
99
+ if (!t || !this.keeps(t))
100
+ continue;
101
+ return sessionTool(t);
102
+ }
103
+ return undefined;
104
+ }
44
105
  get state() {
45
106
  return this.rt.state;
46
107
  }
@@ -116,7 +177,8 @@ class LiveSession {
116
177
  if (this.#left)
117
178
  return;
118
179
  this.#after.push({ fn, owner });
119
- this.#kick();
180
+ if (this.#attached)
181
+ this.#kick();
120
182
  }
121
183
  /** 离开会话:还没开始的输入全部拒绝、afterTurn 不再执行,再中止正在跑的一轮。之后的 send 直接拒绝 */
122
184
  leave() {
@@ -144,9 +206,28 @@ class LiveSession {
144
206
  this.#watchers.add(w);
145
207
  return () => void this.#watchers.delete(w);
146
208
  }
147
- /** Runtime 建好之后调用一次:把通知转给订阅的插件,以插件身份执行,出错只报告 */
148
- attach() {
149
- this.rt.subscribe((n) => {
209
+ /** Runtime 建好之后调用一次。provider、plugins 留着给重挂用:plugins 每次按现在的工具表生成内核插件 */
210
+ attach(rt, provider, plugins) {
211
+ this.#provider = provider;
212
+ this.#plugins = plugins;
213
+ this.#use(rt);
214
+ this.#attached = true;
215
+ if (this.#after.length > 0)
216
+ this.#kick();
217
+ }
218
+ /** 换上一个 Runtime:通知从它转给订阅者。插件的回调以插件身份执行;出错只报告 */
219
+ #use(rt) {
220
+ this.#unsubscribe?.();
221
+ this.rt = rt;
222
+ this.#unsubscribe = rt.subscribe((n) => {
223
+ for (const fn of this.#listeners) {
224
+ try {
225
+ fn(n);
226
+ }
227
+ catch {
228
+ // 和内核一样:订阅者的错误不影响运行
229
+ }
230
+ }
150
231
  for (const w of this.#watchers) {
151
232
  if (w.owner.scope.closed)
152
233
  continue;
@@ -159,6 +240,48 @@ class LiveSession {
159
240
  }
160
241
  });
161
242
  }
243
+ /** 工具表变了(会话中途注册、撤销工具,插件被隔离):下一项工作开始前重挂。几次改动合并成一次 */
244
+ invalidate() {
245
+ if (this.#attached && !this.#left)
246
+ this.#stale = true;
247
+ }
248
+ /**
249
+ * 重挂:detach 旧实例,按现在的工具表 resume 同一个会话(设计稿 live-tools-and-child-sessions 3.2)。
250
+ * 只在两项工作之间执行,内核这时不在跑。插件清单(id、版本)不变,内核不写 plugins.changed。
251
+ * 失败时这项工作失败,下一项工作再试
252
+ */
253
+ async #remount() {
254
+ this.#stale = false;
255
+ if (this.rt.phase === "ended")
256
+ return;
257
+ try {
258
+ if (!this.#loose) {
259
+ await this.rt.detach();
260
+ this.#loose = true;
261
+ }
262
+ const rt = await Runtime.resume({ store: this.#store, provider: this.#provider, plugins: this.#plugins(), sessionId: this.id });
263
+ this.#loose = false;
264
+ this.#use(rt);
265
+ }
266
+ catch (e) {
267
+ this.#stale = true;
268
+ throw new Error(`session ${this.id}: could not update its tools: ${e instanceof Error ? e.message : String(e)}`);
269
+ }
270
+ }
271
+ /** 结束会话(session.ended),子会话用完时。重挂到一半(旧实例已经 detach)时先恢复一个实例来写 */
272
+ async close() {
273
+ if (this.#loose) {
274
+ this.#use(await Runtime.resume({ store: this.#store, provider: this.#provider, plugins: this.#plugins(), sessionId: this.id }));
275
+ this.#loose = false;
276
+ }
277
+ if (this.rt.phase !== "ended")
278
+ await this.rt.close();
279
+ }
280
+ /** 宿主离开会话时 detach;重挂到一半(旧实例已经 detach)时不用再写 */
281
+ async detach() {
282
+ if (!this.#loose)
283
+ await this.rt.detach();
284
+ }
162
285
  abort(reason) {
163
286
  this.rt.abort(reason);
164
287
  // 停在等待人工审批时内核没有在跑,信号结束不了这一轮
@@ -168,7 +291,8 @@ class LiveSession {
168
291
  }
169
292
  }
170
293
  subscribe(fn) {
171
- return this.rt.subscribe(fn);
294
+ this.#listeners.add(fn);
295
+ return () => void this.#listeners.delete(fn);
172
296
  }
173
297
  #kick() {
174
298
  this.#pump ??= this.#run().finally(() => {
@@ -185,6 +309,12 @@ class LiveSession {
185
309
  const job = this.#queue.shift();
186
310
  if (job) {
187
311
  try {
312
+ if (this.#stale) {
313
+ await this.#remount();
314
+ // 重挂期间离开了会话:中止落在旧实例上,这项工作不再开始
315
+ if (this.#left)
316
+ throw this.#left;
317
+ }
188
318
  await job.run();
189
319
  job.resolve();
190
320
  }
@@ -218,6 +348,11 @@ export class Sessions {
218
348
  #store;
219
349
  /** 换会话串行进行 */
220
350
  #switching = Promise.resolve();
351
+ /** 正在运行的子会话数,和等着开的 */
352
+ #running = 0;
353
+ #waiting = [];
354
+ /** 子会话的对话框排成一队,一次一个(7.4) */
355
+ #dialogs = Promise.resolve();
221
356
  constructor(host) {
222
357
  this.#host = host;
223
358
  }
@@ -248,13 +383,24 @@ export class Sessions {
248
383
  if (!provider)
249
384
  throw new ServiceUnavailable("provider@1", "(none): no active plugin provides a model");
250
385
  const store = host.service("store@1", host.core) ?? (this.#store ??= new JsonlLogStore(path.join(host.home, "sessions")));
386
+ if (opts.fork && opts.resume !== undefined)
387
+ throw new Error("sessions.open: resume and fork cannot be used together");
251
388
  const s = new LiveSession(opts.resume ?? crypto.randomUUID(), store, host.report, () => this.#guarded(s));
389
+ // 复制出的会话:先写好日志,再和恢复一样打开。打开失败时留下的日志没人引用,不影响原会话
390
+ if (opts.fork)
391
+ await copyLog(store, opts.fork.session, opts.fork.before, s.id);
392
+ // 直接恢复一个子会话(例如按 id):层数从日志里的 parent 往上数
393
+ if (opts.resume !== undefined || opts.fork)
394
+ s.depth = await depthOf(store, s.id);
395
+ let rt;
396
+ const core = this.#corePlugin(s);
397
+ const kernelPlugins = () => [core, ...s.parts.map((p) => p.kernel())];
252
398
  try {
253
399
  for (const p of host.active())
254
400
  if (p.module.session)
255
401
  await this.#join(s, p);
256
- const plugins = [this.#corePlugin(s), ...s.parts.map((p) => p.kernel)];
257
- s.rt = opts.resume
402
+ const plugins = kernelPlugins();
403
+ rt = opts.resume !== undefined || opts.fork
258
404
  ? await Runtime.resume({ store, provider, plugins, sessionId: s.id })
259
405
  : await Runtime.create({ store, provider, plugins, sessionId: s.id });
260
406
  }
@@ -262,8 +408,8 @@ export class Sessions {
262
408
  await this.#closeParts(s);
263
409
  throw e;
264
410
  }
265
- s.attach();
266
- s.rt.subscribe((n) => {
411
+ s.attach(rt, provider, kernelPlugins);
412
+ s.subscribe((n) => {
267
413
  if (n.type === "hook-error")
268
414
  host.report(`plugin ${n.info.plugin} failed at ${n.info.point}: ${n.info.error instanceof Error ? n.info.error.message : String(n.info.error)}`);
269
415
  });
@@ -274,6 +420,162 @@ export class Sessions {
274
420
  await this.#leave(old);
275
421
  return s;
276
422
  }
423
+ /** 子会话的上限(7.2):用户 config.json 的 "jade/core" */
424
+ #limits() {
425
+ const c = this.#host.coreConfig();
426
+ const n = (v, d, min) => (typeof v === "number" && Number.isInteger(v) && v >= min ? v : d);
427
+ return { maxDepth: n(c.maxDepth, DEFAULT_MAX_DEPTH, 0), maxActive: n(c.maxActive, DEFAULT_MAX_ACTIVE, 1) };
428
+ }
429
+ /** 开子会话(ctx.session.spawn):所有插件照常加入,Runtime.create 带 parent。不会成为当前会话 */
430
+ async #spawn(parent, opts, by) {
431
+ if (!opts || typeof opts !== "object" || opts.parent?.sessionId !== parent.id || typeof opts.parent.eventId !== "string") {
432
+ throw new Error(`plugin ${by}: spawn needs parent: the ToolContext.parent of a tool call in this session`);
433
+ }
434
+ if (parent.left)
435
+ throw new Error(`session ${parent.id} was closed`);
436
+ const { maxDepth, maxActive } = this.#limits();
437
+ if (parent.depth + 1 > maxDepth) {
438
+ throw new Error(maxDepth === 0
439
+ ? `sub-agents are turned off ("jade/core": { "maxDepth": 0 } in config.json)`
440
+ : `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)`);
441
+ }
442
+ const signal = opts.signal instanceof AbortSignal ? opts.signal : undefined;
443
+ // 同时数量的上限:顶层会话开的等前面的结束;子会话开的直接报错,它自己占着名额,等下去可能谁都等不到
444
+ while (this.#running >= maxActive) {
445
+ if (parent.depth > 0)
446
+ throw new Error(`${maxActive} sub-agents are already running; a sub-agent cannot wait for a slot (raise "jade/core": { "maxActive" } in config.json)`);
447
+ await new Promise((resolve, reject) => {
448
+ const wake = () => {
449
+ signal?.removeEventListener("abort", stop);
450
+ resolve();
451
+ };
452
+ const stop = () => {
453
+ const i = this.#waiting.indexOf(wake);
454
+ if (i >= 0)
455
+ this.#waiting.splice(i, 1);
456
+ reject(signal.reason);
457
+ };
458
+ if (signal?.aborted)
459
+ return stop();
460
+ signal?.addEventListener("abort", stop, { once: true });
461
+ this.#waiting.push(wake);
462
+ });
463
+ }
464
+ if (signal?.aborted) {
465
+ // 被叫醒时已经中止:名额让给下一个等着的
466
+ this.#waiting.shift()?.();
467
+ throw signal.reason;
468
+ }
469
+ this.#running++;
470
+ let released = false;
471
+ const release = () => {
472
+ if (released)
473
+ return;
474
+ released = true;
475
+ this.#running--;
476
+ this.#waiting.shift()?.();
477
+ };
478
+ if (parent.left) {
479
+ release();
480
+ throw new Error(`session ${parent.id} was closed`);
481
+ }
482
+ const host = this.#host;
483
+ const provider = opts.provider ?? parent.provider;
484
+ const child = {
485
+ session: parent,
486
+ ref: { sessionId: opts.parent.sessionId, eventId: opts.parent.eventId },
487
+ by,
488
+ ...(typeof opts.label === "string" && opts.label ? { label: opts.label } : {}),
489
+ ...(typeof opts.tools === "function" ? { tools: opts.tools } : {}),
490
+ ...(typeof opts.system === "string" && opts.system ? { system: opts.system } : {}),
491
+ };
492
+ const s = new LiveSession(crypto.randomUUID(), parent.store, host.report, () => this.#guarded(s), child);
493
+ const core = this.#corePlugin(s);
494
+ const delegation = this.#delegation(child);
495
+ const kernelPlugins = () => [core, ...s.parts.map((p) => p.kernel()), delegation];
496
+ let rt;
497
+ try {
498
+ for (const p of host.active())
499
+ if (p.module.session)
500
+ await this.#join(s, p);
501
+ rt = await Runtime.create({ store: s.store, provider, plugins: kernelPlugins(), sessionId: s.id, parent: child.ref });
502
+ }
503
+ catch (e) {
504
+ await this.#closeParts(s);
505
+ release();
506
+ throw e;
507
+ }
508
+ s.attach(rt, provider, kernelPlugins);
509
+ s.subscribe((n) => {
510
+ if (n.type === "hook-error")
511
+ 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)}`);
512
+ });
513
+ s.onEnd = release;
514
+ // Runtime 建好了才算父会话的子会话:父会话离开时结束它要用 Runtime。开的期间父会话离开了:马上结束
515
+ parent.children.add(s);
516
+ if (parent.left) {
517
+ await this.#end(s);
518
+ throw new Error(`session ${parent.id} was closed`);
519
+ }
520
+ let closing;
521
+ return {
522
+ id: s.id,
523
+ send: (input) => s.send(input),
524
+ get state() {
525
+ return s.state;
526
+ },
527
+ subscribe: (fn) => s.subscribe(fn),
528
+ abort: (reason) => s.abort(new Error(reason ?? `stopped by plugin ${by}`)),
529
+ close: () => (closing ??= this.#end(s)),
530
+ };
531
+ }
532
+ /** 结束子会话:先结束它的子会话,中止正在跑的工作,写 session.ended,关闭插件的作用域。返回 ChildRef */
533
+ async #end(s) {
534
+ if (s.ended)
535
+ return s.ended;
536
+ s.ended = (async () => {
537
+ s.leave();
538
+ for (const c of [...s.children])
539
+ await this.#end(c);
540
+ await s.idle();
541
+ try {
542
+ await s.close();
543
+ }
544
+ catch (e) {
545
+ this.#host.report(`sub-agent session ${s.id}: could not end it: ${e instanceof Error ? e.message : String(e)}`);
546
+ }
547
+ await this.#closeParts(s);
548
+ s.child?.session.children.delete(s);
549
+ s.onEnd?.();
550
+ return { sessionId: s.id, seq: s.rt.state.lastSeq };
551
+ })();
552
+ return s.ended;
553
+ }
554
+ /**
555
+ * 子会话里的 ui@1:没有会话界面(状态栏、输入框);对话框在整个进程里排成一队,一次一个,标题前标上是哪个子 Agent(7.4)
556
+ */
557
+ #childUI(ui, s) {
558
+ const name = s.child?.label ?? "sub-agent";
559
+ const queued = (fn) => {
560
+ const run = this.#dialogs.then(fn);
561
+ this.#dialogs = run.catch(() => { });
562
+ return run;
563
+ };
564
+ return new Proxy(ui, {
565
+ get: (target, prop) => {
566
+ if (prop === "session")
567
+ return undefined;
568
+ if (prop === "select") {
569
+ return (req, signal) => queued(() => (signal?.aborted ? Promise.resolve(undefined) : target.select({ ...req, title: `[${name}] ${req.title}` }, signal)));
570
+ }
571
+ if (prop === "input") {
572
+ return (req, signal) => queued(() => (signal?.aborted ? Promise.resolve(undefined) : target.input({ ...req, title: `[${name}] ${req.title}` }, signal)));
573
+ }
574
+ const v = Reflect.get(target, prop);
575
+ return typeof v === "function" ? v.bind(target) : v;
576
+ },
577
+ });
578
+ }
277
579
  /** 一个插件加入会话:执行它的 session(),失败就撤销它这次的注册 */
278
580
  async #join(s, p) {
279
581
  const host = this.#host;
@@ -281,9 +583,13 @@ export class Sessions {
281
583
  const id = manifest.id;
282
584
  const scope = new Scope(id);
283
585
  const owner = { plugin: id, scope };
586
+ /** 这个插件的工具,已包装;加入成功后就是 part.tools */
284
587
  const tools = [];
285
588
  const hooks = [];
286
589
  let open = true;
590
+ let part;
591
+ /** 现在交给内核的工具里叫这个名字的是谁的(被隔离的插件的工具已经不交给内核,不算) */
592
+ const holder = (name) => s.parts.find((x) => !x.owner.scope.closed && x.tools.some((t) => t.name === name));
287
593
  const declared = (name, lists) => {
288
594
  if (scope.closed)
289
595
  throw new StaleContext(id);
@@ -300,6 +606,8 @@ export class Sessions {
300
606
  // 作用域已经关了:没有要清理的
301
607
  }
302
608
  }
609
+ /** 子会话里的 ui@1 换成排队、标名字的那份 */
610
+ const forSession = (name, h) => h && s.child && name === "ui@1" ? this.#childUI(h, s) : h;
303
611
  const uiCall = (fn) => {
304
612
  try {
305
613
  fn();
@@ -317,20 +625,23 @@ export class Sessions {
317
625
  secrets: scopedSecrets(host.secrets(id), () => scope.closed, id),
318
626
  ...(sessionUI
319
627
  ? {
320
- status: (text) => uiCall(() => sessionUI.status(text === undefined ? undefined : String(text))),
321
- ...(sessionUI.draft ? { input: sessionUI.draft } : {}),
628
+ status: (text) => uiCall(() => sessionUI.status(statusSegment(text))),
629
+ // 带样式的文字(Text)原样交给前端,由它决定怎么画
630
+ ...(sessionUI.panel ? { panel: (text) => uiCall(() => sessionUI.panel(text)) } : {}),
631
+ // 项目层插件拿不到输入框(第 7 节):克隆的仓库不能替用户写字
632
+ ...(sessionUI.draft && layer !== "project" ? { input: sessionUI.draft } : {}),
322
633
  }
323
634
  : {}),
324
635
  require: (name) => {
325
636
  declared(name, [manifest.requires]);
326
- const h = host.service(name, owner);
637
+ const h = forSession(name, host.service(name, owner));
327
638
  if (!h)
328
639
  throw new ServiceUnavailable(name, "(none)");
329
640
  return h;
330
641
  },
331
642
  service: (name) => {
332
643
  declared(name, [manifest.requires, manifest.optional]);
333
- return host.service(name, owner);
644
+ return forSession(name, host.service(name, owner));
334
645
  },
335
646
  effect: async (start) => {
336
647
  if (scope.closed)
@@ -339,6 +650,11 @@ export class Sessions {
339
650
  if (typeof d === "function")
340
651
  scope.add(d);
341
652
  },
653
+ report: (message) => {
654
+ if (scope.closed)
655
+ throw new StaleContext(id);
656
+ host.report(`${id}: ${String(message)}`);
657
+ },
342
658
  session: {
343
659
  id: s.id,
344
660
  afterTurn: (fn) => {
@@ -358,7 +674,14 @@ export class Sessions {
358
674
  throw new StaleContext(id);
359
675
  if (layer === "project")
360
676
  throw new Error(`plugin ${id}: project plugins cannot stop turns on the user's behalf`);
361
- s.abort(new Error(reason ?? `stopped by plugin ${id}`));
677
+ const why = new Error(reason ?? `stopped by plugin ${id}`);
678
+ s.abort(why);
679
+ // 子会话里替用户喊停(例如审批时按 Esc):用户要停的是整件事,顶层会话这一轮也停,不让父会话拿着结果接着干
680
+ let top = s;
681
+ while (top.child)
682
+ top = top.child.session;
683
+ if (top !== s)
684
+ top.abort(why);
362
685
  },
363
686
  state: () => {
364
687
  if (scope.closed)
@@ -375,12 +698,50 @@ export class Sessions {
375
698
  scope.add(off);
376
699
  return off;
377
700
  },
701
+ tool: (name) => {
702
+ if (scope.closed)
703
+ throw new StaleContext(id);
704
+ return s.tool(name);
705
+ },
706
+ ...(s.child ? { parent: { ...s.child.ref } } : {}),
707
+ depth: s.depth,
708
+ canSpawn: layer !== "project" && s.depth < this.#limits().maxDepth,
709
+ spawn: (opts) => {
710
+ if (scope.closed)
711
+ return Promise.reject(new StaleContext(id));
712
+ if (layer === "project")
713
+ return Promise.reject(new Error(`plugin ${id}: project plugins cannot open sub-agent sessions`));
714
+ return this.#spawn(s, opts, id);
715
+ },
378
716
  },
379
717
  kernel: {
380
718
  tool: (t) => {
719
+ if (scope.closed)
720
+ throw new StaleContext(id);
721
+ const tool = liveTool({ ...t, ...toolMeta(id, layer, t) }, owner);
722
+ if (!open) {
723
+ // session() 返回之后注册的从下一项工作起生效(重挂 Runtime)。重名的在这里拒绝,不能让重挂失败
724
+ if (!part)
725
+ throw new Error(`plugin ${id}: did not join session ${s.id}`);
726
+ const other = holder(tool.name);
727
+ if (other)
728
+ throw new Error(`plugin ${id}: tool ${tool.name} is already registered by ${other.source.manifest.id}`);
729
+ }
730
+ tools.push(tool);
381
731
  if (!open)
382
- throw new Error(`plugin ${id}: tools can only be registered while session() runs`);
383
- tools.push(t);
732
+ s.invalidate();
733
+ let done = false;
734
+ return () => {
735
+ if (done)
736
+ return;
737
+ done = true;
738
+ const i = tools.indexOf(tool);
739
+ if (i < 0)
740
+ return;
741
+ tools.splice(i, 1);
742
+ if (part)
743
+ s.invalidate();
744
+ };
384
745
  },
385
746
  hook: (h) => {
386
747
  if (!open)
@@ -404,32 +765,33 @@ export class Sessions {
404
765
  }
405
766
  open = false;
406
767
  // 内核构造 Runtime 时会因为重名工具、不合法的 hook 拒绝整个会话:提前检查,只排除这一个插件
407
- const taken = new Set(s.parts.flatMap((x) => x.kernel.tools?.map((t) => t.name) ?? []));
408
- const clash = tools.find((t) => taken.has(t.name));
409
- const problem = clash
410
- ? `tool ${clash.name} is already registered by ${s.parts.find((x) => x.kernel.tools?.some((t) => t.name === clash.name)).source.manifest.id}`
411
- : compatProblem(id, manifest.version, hooks);
768
+ const clash = tools.find((t) => holder(t.name));
769
+ const problem = clash ? `tool ${clash.name} is already registered by ${holder(clash.name).source.manifest.id}` : compatProblem(id, manifest.version, hooks);
412
770
  if (problem) {
413
771
  host.untrack(id, scope);
414
772
  await scope.close();
415
773
  host.report(`plugin ${id} did not join session ${s.id}: ${problem}`);
416
774
  return;
417
775
  }
418
- const part = {
776
+ const live = hooks.map((h) => liveHook(h, owner));
777
+ part = {
419
778
  source: p.source,
420
779
  owner,
421
780
  gates: hooks.filter((h) => h.kind === "gate" && h.point === "tool.gate").length,
422
- kernel: this.#confirmed(p, kernelPlugin({
781
+ tools,
782
+ kernel: () => this.#confirmed(p, kernelPlugin({
423
783
  id,
424
784
  version: manifest.version,
425
785
  layer: KERNEL_LAYER[layer],
426
786
  // 写日志的能力调用时才检查,推不出来(definePlugin 只补 hook 用到的);jade 的插件都可以写
427
787
  needs: ["log:record", "log:emit"],
428
- tools: tools.map((t) => liveTool(t, owner)),
429
- hooks: hooks.map((h) => liveHook(h, owner)),
788
+ tools: scope.closed ? [] : tools.filter((t) => s.keeps(t)),
789
+ hooks: live,
430
790
  })),
431
791
  };
432
792
  s.parts.push(part);
793
+ // 插件被隔离(作用域关闭):它的工具从下一项工作起不再给模型看
794
+ scope.add(() => s.invalidate());
433
795
  }
434
796
  /** 项目层插件交给内核的插件要用确认时拿到的 mark 标记,否则内核拒绝整个会话 */
435
797
  #confirmed(p, plugin) {
@@ -444,6 +806,9 @@ export class Sessions {
444
806
  * 获取失败也只当作没有:界面上的东西坏了不该让插件加入不了会话
445
807
  */
446
808
  #sessionUI(s, plugin, owner) {
809
+ // 子会话不是当前会话,没有自己的界面(4.2)
810
+ if (s.child)
811
+ return undefined;
447
812
  try {
448
813
  const ui = this.#host.service("ui@1", owner);
449
814
  return ui?.session?.({ session: s.id, plugin });
@@ -461,6 +826,21 @@ export class Sessions {
461
826
  const gate = (call) => this.#guarded(s) || call.tool.effect === "read" ? { decision: "abstain" } : { decision: "deny", reason: NO_APPROVAL_REASON };
462
827
  return kernelPlugin({ id: CORE_PLUGIN_ID, version: API_VERSION, layer: "distro", hooks: [{ kind: "gate", point: "tool.gate", fn: gate }] });
463
828
  }
829
+ /**
830
+ * 子会话的委派说明和开它的插件给的系统提示词(7.3)。context.build 按顺序执行,别的插件(jade/prompts)
831
+ * 把自己的段落放在已有段落之前,最后执行的才能放在最前面:所以单独一个插件,hook 的 order 设得很大
832
+ */
833
+ #delegation(child) {
834
+ const seg = (text, by) => ({ text, stability: "stable", origin: { by: "plugin", id: by }, trust: "trusted" });
835
+ const head = [seg(DELEGATION, CORE_PLUGIN_ID), ...(child.system ? [seg(child.system, child.by)] : [])];
836
+ return kernelPlugin({
837
+ id: `${CORE_PLUGIN_ID}/delegation`,
838
+ version: API_VERSION,
839
+ layer: "distro",
840
+ // order 大:任何层的插件之后执行
841
+ hooks: [{ kind: "transform", point: "context.build", order: 1_000_000, fn: (req) => ({ ...req, system: [...head, ...req.system] }) }],
842
+ });
843
+ }
464
844
  /** approval@1 的提供者(不能是项目层插件)在这个会话里有仍然有效的 tool.gate */
465
845
  #guarded(s) {
466
846
  const approval = this.#host.provider("approval@1");
@@ -469,9 +849,12 @@ export class Sessions {
469
849
  /** 离开会话:中止正在跑的工作,等它停下,detach,关闭插件的会话作用域 */
470
850
  async #leave(s) {
471
851
  s.leave();
852
+ // 它开的子会话一并结束:正在等子会话的工具调用随之结束
853
+ for (const c of [...s.children])
854
+ await this.#end(c);
472
855
  await s.idle();
473
856
  try {
474
- await s.rt.detach();
857
+ await s.detach();
475
858
  }
476
859
  catch (e) {
477
860
  this.#host.report(`session ${s.id}: detach failed: ${e instanceof Error ? e.message : String(e)}`);
@@ -495,6 +878,46 @@ function compatProblem(id, version, hooks) {
495
878
  return e instanceof Error ? e.message : String(e);
496
879
  }
497
880
  }
881
+ /** 状态栏的一段只留认得的字段:文字都换成字符串,不认得的 tone 去掉 */
882
+ function statusSegment(s) {
883
+ if (s === undefined || typeof s !== "object" || s === null)
884
+ return s === undefined ? undefined : String(s);
885
+ const tones = ["ok", "warn", "error", "accent"];
886
+ return {
887
+ text: String(s.text ?? ""),
888
+ ...(s.short !== undefined ? { short: String(s.short) } : {}),
889
+ ...(tones.includes(s.tone) ? { tone: s.tone } : {}),
890
+ ...(s.keep === true ? { keep: true } : {}),
891
+ };
892
+ }
893
+ /**
894
+ * 工具的 meta 只留认得的字段(字段名都是字符串),写错了抛错:插件加入会话失败,比别的插件悄悄认不出这个工具好查。
895
+ * 项目层插件的 shell 不算:审批按它把只读命令直接放行、只读的子 Agent 也留着这个工具,克隆的仓库不能自己声明这个。
896
+ * 去掉之后它就是普通的工具,照常经过审批
897
+ */
898
+ function toolMeta(plugin, layer, t) {
899
+ if (t.meta === undefined)
900
+ return {};
901
+ const m = t.meta;
902
+ if (typeof m !== "object" || m === null)
903
+ throw new Error(`plugin ${plugin}: tool ${t.name}: meta must be an object`);
904
+ const meta = {};
905
+ for (const k of ["writes", "shell"]) {
906
+ if (m[k] === undefined)
907
+ continue;
908
+ if (typeof m[k] !== "string" || !m[k])
909
+ throw new Error(`plugin ${plugin}: tool ${t.name}: meta.${k} must be the name of an input field`);
910
+ if (k === "shell" && layer === "project")
911
+ continue;
912
+ meta[k] = m[k];
913
+ }
914
+ return { meta };
915
+ }
916
+ /** 工具的声明部分(给插件看的 SessionTool),meta 是拷贝 */
917
+ function sessionTool(t) {
918
+ const { name, description, inputSchema, effect, concurrency, idempotent, meta } = t;
919
+ return { name, description, inputSchema, effect, concurrency, idempotent, ...(meta ? { meta: { ...meta } } : {}) };
920
+ }
498
921
  /** 插件的工具:以插件身份执行;插件被隔离后返回错误结果(由内核转成 tool_result) */
499
922
  function liveTool(t, owner) {
500
923
  return { ...t, execute: (input, ctx) => invoke(owner, `tool ${t.name}`, () => t.execute(input, ctx)) };
@@ -518,4 +941,36 @@ function liveHook(h, owner) {
518
941
  };
519
942
  return { ...h, fn: wrapped };
520
943
  }
944
+ /** 会话是第几层子会话:沿着 session.started 里的 parent 往上数(内核保证引用能解析到,宪法 3.4) */
945
+ async function depthOf(store, sessionId) {
946
+ let depth = 0;
947
+ let id = sessionId;
948
+ const seen = new Set();
949
+ while (id && !seen.has(id) && depth < 100) {
950
+ seen.add(id);
951
+ let parent;
952
+ for await (const e of store.read(id)) {
953
+ if (e.type === "session.started")
954
+ parent = e.data.parent?.sessionId;
955
+ break;
956
+ }
957
+ if (!parent)
958
+ break;
959
+ depth++;
960
+ id = parent;
961
+ }
962
+ return depth;
963
+ }
964
+ /**
965
+ * 把 from 的日志里 seq 小于 before 的事件写成新会话 to 的日志(OpenOptions.fork)。before 要是一条消息输入的 seq:
966
+ * 这样复制出的会话停在一轮结束之后、下一条消息之前,恢复时没有没做完的一轮
967
+ */
968
+ async function copyLog(store, from, before, to) {
969
+ const events = await readAll(store, from);
970
+ const at = events.find((e) => e.seq === before);
971
+ if (!at || at.type !== "input.received" || at.data.kind !== "message") {
972
+ throw new Error(`sessions.open: seq ${before} of session ${from} is not a message from the user`);
973
+ }
974
+ await store.append(to, events.filter((e) => e.seq < before));
975
+ }
521
976
  //# sourceMappingURL=session.js.map