@uncarved/jade 0.4.3 → 0.5.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 (41) hide show
  1. package/README.md +39 -1
  2. package/dist/api.d.ts +1 -1
  3. package/dist/api.js +1 -1
  4. package/dist/membrane.d.ts +5 -2
  5. package/dist/membrane.js +8 -3
  6. package/dist/membrane.js.map +1 -1
  7. package/dist/session.d.ts +14 -3
  8. package/dist/session.js +164 -22
  9. package/dist/session.js.map +1 -1
  10. package/package.json +4 -4
  11. package/plugins/keys/index.ts +2 -2
  12. package/plugins/memory/index.ts +6 -4
  13. package/plugins/memory/memory.ts +101 -31
  14. package/plugins/models/index.ts +67 -9
  15. package/plugins/models/provider.ts +81 -24
  16. package/plugins/serve/index.ts +236 -0
  17. package/plugins/serve/plugin.json +8 -0
  18. package/plugins/shell/index.ts +35 -1
  19. package/plugins/shell/shell.ts +5 -0
  20. package/plugins/task/index.ts +3 -1
  21. package/plugins/task/subagent.ts +49 -3
  22. package/plugins/tui/frontend.ts +73 -4
  23. package/plugins/tui/screen.ts +23 -0
  24. package/plugins/tui/tui.ts +176 -11
  25. package/plugins-dist/keys/index.js +1 -1
  26. package/plugins-dist/memory/index.js +7 -3
  27. package/plugins-dist/memory/memory.js +81 -34
  28. package/plugins-dist/models/index.js +62 -7
  29. package/plugins-dist/models/provider.js +47 -14
  30. package/plugins-dist/serve/index.js +244 -0
  31. package/plugins-dist/serve/plugin.json +14 -0
  32. package/plugins-dist/shell/index.js +33 -0
  33. package/plugins-dist/shell/shell.js +3 -0
  34. package/plugins-dist/task/index.js +3 -1
  35. package/plugins-dist/task/subagent.js +47 -2
  36. package/plugins-dist/tui/frontend.js +67 -3
  37. package/plugins-dist/tui/screen.js +3 -0
  38. package/plugins-dist/tui/tui.js +132 -9
  39. package/src/api.ts +1 -1
  40. package/src/membrane.ts +8 -3
  41. package/src/session.ts +181 -25
package/src/session.ts CHANGED
@@ -35,6 +35,7 @@ import {
35
35
  type Session,
36
36
  type SessionContext,
37
37
  type SessionManager,
38
+ type StartedSession,
38
39
  type SessionTool,
39
40
  type SessionUI,
40
41
  type SpawnOptions,
@@ -43,7 +44,7 @@ import {
43
44
  type ToolMeta,
44
45
  type UI,
45
46
  } from "./api.ts";
46
- import { ambient, invoke, Scope, type Owner } from "./membrane.ts";
47
+ import { ambient, DISPOSE_TIMEOUT_MS, invoke, Scope, type Owner } from "./membrane.ts";
47
48
  import { scopedSecrets } from "./secrets.ts";
48
49
 
49
50
  /** 核心自己交给内核的插件:兜底关卡 */
@@ -110,6 +111,16 @@ export const DELEGATION =
110
111
  /** 子会话的层数、同时数量的默认上限(7.2) */
111
112
  export const DEFAULT_MAX_DEPTH = 1;
112
113
  export const DEFAULT_MAX_ACTIVE = 8;
114
+ /** 离开会话时最多等它停下多久(毫秒)。不理会中止信号的工具、插件不能让关闭一直卡住 */
115
+ export const DEFAULT_CLOSE_TIMEOUT_MS = 10_000;
116
+
117
+ /**
118
+ * store@1 的契约:内核的 LogStore,加一个可选的 release(宿主离开会话时调用),存储可以丢掉为它缓存的状态,
119
+ * 之后再写也必须照常工作。这是 jade 和存储之间的约定,不属于内核(宪法 4.3)
120
+ */
121
+ export type HostStore = LogStore & { release?(sessionId: string): void };
122
+
123
+ type Job = { run: () => Promise<void>; resolve: () => void; reject: (e: unknown) => void };
113
124
 
114
125
  interface Turn {
115
126
  stop?: { reason: unknown };
@@ -121,7 +132,11 @@ class LiveSession implements Session {
121
132
  readonly parts: Part[] = [];
122
133
  rt!: Runtime;
123
134
  /** 排队的工作:一条输入,或者恢复(recover)。一次只跑一项,Runtime 同一时间只接受一个调用 */
124
- #queue: { run: () => Promise<void>; resolve: () => void; reject: (e: unknown) => void }[] = [];
135
+ #queue: Job[] = [];
136
+ /** 正在跑的那一项工作 */
137
+ #job: Job | undefined;
138
+ /** 现在的 Runtime 写日志经过的围栏。放弃一个 Runtime(abandon)时关上它的围栏,下一个 Runtime 用新的 */
139
+ #fence: Fence = { writing: new Set() };
125
140
  #after: { fn: () => void | Promise<void>; owner: Owner }[] = [];
126
141
  #pump: Promise<void> | undefined;
127
142
  /** 离开时的原因;有了以后不再接受输入 */
@@ -147,7 +162,7 @@ class LiveSession implements Session {
147
162
  #provider!: Provider;
148
163
  #plugins!: () => Plugin[];
149
164
 
150
- readonly #store: LogStore;
165
+ readonly #store: HostStore;
151
166
  /** 子会话的信息;顶层会话没有 */
152
167
  readonly child: Child | undefined;
153
168
  /** 第几层:顶层会话是 0 */
@@ -158,7 +173,7 @@ class LiveSession implements Session {
158
173
  ended: Promise<{ sessionId: string; seq: number }> | undefined;
159
174
  onEnd: (() => void) | undefined;
160
175
 
161
- constructor(id: string, store: LogStore, report: (m: string) => void, attended: () => boolean, child?: Child) {
176
+ constructor(id: string, store: HostStore, report: (m: string) => void, attended: () => boolean, child?: Child) {
162
177
  this.id = id;
163
178
  this.#store = store;
164
179
  this.#report = report;
@@ -167,10 +182,16 @@ class LiveSession implements Session {
167
182
  if (child) this.depth = child.session.depth + 1;
168
183
  }
169
184
 
170
- get store(): LogStore {
185
+ /** 存储本身:读日志、开子会话、release 用。建 Runtime 用 runtimeStore() */
186
+ get store(): HostStore {
171
187
  return this.#store;
172
188
  }
173
189
 
190
+ /** 给现在要建的 Runtime 用的存储:这个 Runtime 被放弃以后,它的写入一律被拒 */
191
+ runtimeStore(): LogStore {
192
+ return fenced(this.#store, this.#fence);
193
+ }
194
+
174
195
  get provider(): Provider {
175
196
  return this.#provider;
176
197
  }
@@ -290,6 +311,24 @@ class LiveSession implements Session {
290
311
  while (this.#pump) await this.#pump;
291
312
  }
292
313
 
314
+ /**
315
+ * 离开后等不到它停下(工具、插件不理会中止信号):不再等这个 Runtime 了。它还卡在那里,之后它写日志一律被拒,
316
+ * 迟到的结果写不进去;它的通知不再转发。正在等这项工作的调用方立即得到 reason。
317
+ * 然后按日志恢复一个新的 Runtime 接手(和进程在这里退出后再恢复一样),由它写收尾的事件(detach、close)
318
+ */
319
+ async abandon(reason: Error): Promise<void> {
320
+ const old = this.#fence;
321
+ old.gone = reason;
322
+ this.#fence = { writing: new Set() };
323
+ this.#job?.reject(reason);
324
+ this.#unsubscribe?.();
325
+ this.#unsubscribe = undefined;
326
+ // 关围栏之前已经开始的写入(例如同一批里别的工具刚好完成)先写完,接手的才开始写:同一时间只有一个写入者(宪法 4.3)
327
+ await Promise.allSettled(old.writing);
328
+ this.#use(await Runtime.resume({ store: this.runtimeStore(), provider: this.#provider, plugins: this.#plugins(), sessionId: this.id }));
329
+ this.#loose = false;
330
+ }
331
+
293
332
  /**
294
333
  * 和输入排同一个队:恢复可能要跑完一整轮,这期间插件发来的输入排在它后面,而不是撞上 RuntimeBusy。
295
334
  * 上次停在等待人工审批的(进程被杀、崩溃):内核再发一次 awaiting 通知,审批插件据此重新问(ctx.session.subscribe),
@@ -356,7 +395,7 @@ class LiveSession implements Session {
356
395
  await this.rt.detach();
357
396
  this.#loose = true;
358
397
  }
359
- const rt = await Runtime.resume({ store: this.#store, provider: this.#provider, plugins: this.#plugins(), sessionId: this.id });
398
+ const rt = await Runtime.resume({ store: this.runtimeStore(), provider: this.#provider, plugins: this.#plugins(), sessionId: this.id });
360
399
  this.#loose = false;
361
400
  this.#use(rt);
362
401
  } catch (e) {
@@ -368,7 +407,7 @@ class LiveSession implements Session {
368
407
  /** 结束会话(session.ended),子会话用完时。重挂到一半(旧实例已经 detach)时先恢复一个实例来写 */
369
408
  async close(): Promise<void> {
370
409
  if (this.#loose) {
371
- this.#use(await Runtime.resume({ store: this.#store, provider: this.#provider, plugins: this.#plugins(), sessionId: this.id }));
410
+ this.#use(await Runtime.resume({ store: this.runtimeStore(), provider: this.#provider, plugins: this.#plugins(), sessionId: this.id }));
372
411
  this.#loose = false;
373
412
  }
374
413
  if (this.rt.phase !== "ended") await this.rt.close();
@@ -407,6 +446,7 @@ class LiveSession implements Session {
407
446
  await null; // 让调用方先拿到 send 的 Promise
408
447
  for (;;) {
409
448
  const job = this.#queue.shift();
449
+ this.#job = job;
410
450
  if (job) {
411
451
  try {
412
452
  if (this.#stale) {
@@ -418,6 +458,8 @@ class LiveSession implements Session {
418
458
  job.resolve();
419
459
  } catch (e) {
420
460
  job.reject(e);
461
+ } finally {
462
+ this.#job = undefined;
421
463
  }
422
464
  }
423
465
  if (this.#after.length > 0) await this.#runAfter();
@@ -441,6 +483,8 @@ class LiveSession implements Session {
441
483
  export class Sessions implements SessionManager {
442
484
  readonly #host: SessionHost;
443
485
  #current: LiveSession | undefined;
486
+ /** start 开的会话和交出去的句柄 */
487
+ #started = new Map<LiveSession, StartedSession>();
444
488
  #store: LogStore | undefined;
445
489
  /** 换会话串行进行 */
446
490
  #switching: Promise<unknown> = Promise.resolve();
@@ -469,19 +513,72 @@ export class Sessions implements SessionManager {
469
513
  return run;
470
514
  }
471
515
 
472
- /** 当前会话离开(detach,仍可恢复) */
516
+ /** 当前会话离开(detach,仍可恢复);start 开的会话一并离开 */
473
517
  async close(): Promise<void> {
474
518
  await this.#switching;
475
519
  const old = this.#current;
476
520
  this.#current = undefined;
477
521
  if (old) await this.#leave(old);
522
+ for (const h of [...this.#started.values()]) await h.close();
523
+ }
524
+
525
+ /** 和当前会话并存的会话(无头前端同时跑多个会话):不成为当前会话,各自 close */
526
+ start(opts: OpenOptions = {}): Promise<StartedSession> {
527
+ const run = this.#switching.then(() => this.#start(opts));
528
+ this.#switching = run.catch(() => {});
529
+ return run;
530
+ }
531
+
532
+ async #start(opts: OpenOptions): Promise<StartedSession> {
533
+ // 同一个会话的日志不能同时挂两个 Runtime
534
+ if (opts.resume !== undefined && (opts.resume === this.#current?.id || this.#isStarted(opts.resume))) {
535
+ throw new Error(`session ${opts.resume} is already open`);
536
+ }
537
+ const s = await this.#build(opts);
538
+ let closing: Promise<void> | undefined;
539
+ const handle: StartedSession = {
540
+ id: s.id,
541
+ get state() {
542
+ return s.state;
543
+ },
544
+ send: (input) => s.send(input),
545
+ idle: () => s.idle(),
546
+ recover: () => s.recover(),
547
+ abort: (reason) => s.abort(reason),
548
+ subscribe: (fn) => s.subscribe(fn),
549
+ history: () => s.history(),
550
+ tool: (name) => s.tool(name),
551
+ close: () =>
552
+ (closing ??= (async () => {
553
+ this.#started.delete(s);
554
+ await this.#leave(s);
555
+ })()),
556
+ };
557
+ this.#started.set(s, handle);
558
+ return handle;
559
+ }
560
+
561
+ #isStarted(id: string): boolean {
562
+ return [...this.#started.keys()].some((s) => s.id === id);
478
563
  }
479
564
 
480
565
  async #open(opts: OpenOptions): Promise<Session> {
566
+ // 同一个会话的日志不能同时挂两个 Runtime:start 开着的不能再成为当前会话
567
+ if (opts.resume !== undefined && this.#isStarted(opts.resume)) throw new Error(`session ${opts.resume} is already open`);
568
+ const s = await this.#build(opts);
569
+ // 提交:新会话成为当前会话,然后旧会话离开
570
+ const old = this.#current;
571
+ this.#current = s;
572
+ if (old) await this.#leave(old);
573
+ return s;
574
+ }
575
+
576
+ /** 建好一个会话(全部插件加入、Runtime 建好)。任何一步失败,新会话的作用域全部撤销 */
577
+ async #build(opts: OpenOptions): Promise<LiveSession> {
481
578
  const host = this.#host;
482
579
  const provider = host.service<Provider>("provider@1", host.core);
483
580
  if (!provider) throw new ServiceUnavailable("provider@1", "(none): no active plugin provides a model");
484
- const store = host.service<LogStore>("store@1", host.core) ?? (this.#store ??= new JsonlLogStore(path.join(host.home, "sessions")));
581
+ const store = host.service<HostStore>("store@1", host.core) ?? (this.#store ??= new JsonlLogStore(path.join(host.home, "sessions")));
485
582
 
486
583
  if (opts.fork && opts.resume !== undefined) throw new Error("sessions.open: resume and fork cannot be used together");
487
584
  const s: LiveSession = new LiveSession(opts.resume ?? crypto.randomUUID(), store, host.report, () => this.#guarded(s));
@@ -496,8 +593,8 @@ export class Sessions implements SessionManager {
496
593
  for (const p of host.active()) if (p.module.session) await this.#join(s, p);
497
594
  const plugins = kernelPlugins();
498
595
  rt = opts.resume !== undefined || opts.fork
499
- ? await Runtime.resume({ store, provider, plugins, sessionId: s.id })
500
- : await Runtime.create({ store, provider, plugins, sessionId: s.id });
596
+ ? await Runtime.resume({ store: s.runtimeStore(), provider, plugins, sessionId: s.id })
597
+ : await Runtime.create({ store: s.runtimeStore(), provider, plugins, sessionId: s.id });
501
598
  } catch (e) {
502
599
  // session() 里排进来的输入不会再执行了
503
600
  s.leave();
@@ -508,18 +605,47 @@ export class Sessions implements SessionManager {
508
605
  s.subscribe((n) => {
509
606
  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)}`);
510
607
  });
511
- // 提交:新会话成为当前会话,然后旧会话离开
512
- const old = this.#current;
513
- this.#current = s;
514
- if (old) await this.#leave(old);
515
608
  return s;
516
609
  }
517
610
 
518
- /** 子会话的上限(7.2):用户 config.json 的 "jade/core" */
519
- #limits(): { maxDepth: number; maxActive: number } {
611
+ /** 子会话的上限(7.2)和离开会话时最多等多久:用户 config.json 的 "jade/core" */
612
+ #limits(): { maxDepth: number; maxActive: number; closeTimeoutMs: number } {
520
613
  const c = this.#host.coreConfig();
521
614
  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) };
615
+ return {
616
+ maxDepth: n(c.maxDepth, DEFAULT_MAX_DEPTH, 0),
617
+ maxActive: n(c.maxActive, DEFAULT_MAX_ACTIVE, 1),
618
+ closeTimeoutMs: n(c.closeTimeoutMs, DEFAULT_CLOSE_TIMEOUT_MS, 0),
619
+ };
620
+ }
621
+
622
+ /**
623
+ * 等离开的会话停下,最多 closeTimeoutMs。等不到就放弃它的 Runtime、换一个接手(LiveSession.abandon),返回原因。
624
+ * 还没结果的工具多半不理会中止信号(宪法 I-9):归到提供它的插件,记一次故障(5.4 的连续故障计数)。
625
+ * 和插件加入会话失败一样只记故障、不隔离:一条命令卡住不该让整个插件在这个进程里停掉
626
+ */
627
+ async #stopped(s: LiveSession): Promise<Error | undefined> {
628
+ const { closeTimeoutMs: ms } = this.#limits();
629
+ let timer: ReturnType<typeof setTimeout> | undefined;
630
+ const stopped = await Promise.race([
631
+ s.idle().then(() => true),
632
+ new Promise<boolean>((resolve) => (timer = setTimeout(() => resolve(false), ms))),
633
+ ]);
634
+ clearTimeout(timer);
635
+ if (stopped) return undefined;
636
+ const names = s.rt?.state.phase === "tools" ? [...new Set(s.rt.state.batch.filter((c) => c.decision === "allow" && !c.result).map((c) => c.name))] : [];
637
+ const blamed = names.map((name) => ({ name, plugin: s.parts.find((p) => p.tools.some((t) => t.name === name))?.source.manifest.id }));
638
+ const who = blamed.length > 0 ? blamed.map((b) => `tool ${b.name}${b.plugin ? ` of plugin ${b.plugin}` : ""}`).join(", ") : "a tool or plugin";
639
+ const why = `session ${s.id} did not stop within ${ms} ms of being closed (${who} ignored the abort signal); stopped waiting for it, it can be resumed later`;
640
+ this.#host.report(why);
641
+ for (const b of blamed) if (b.plugin) this.#host.fault(b.plugin, `tool ${b.name} did not stop within ${ms} ms when its session was closed`);
642
+ const reason = new Error(why);
643
+ try {
644
+ await s.abandon(reason);
645
+ } catch (e) {
646
+ this.#host.report(`session ${s.id}: could not take it over after it did not stop: ${e instanceof Error ? e.message : String(e)}`);
647
+ }
648
+ return reason;
523
649
  }
524
650
 
525
651
  /** 开子会话(ctx.session.spawn):所有插件照常加入,Runtime.create 带 parent。不会成为当前会话 */
@@ -589,7 +715,7 @@ export class Sessions implements SessionManager {
589
715
  let rt: Runtime;
590
716
  try {
591
717
  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 });
718
+ rt = await Runtime.create({ store: s.runtimeStore(), provider, plugins: kernelPlugins(), sessionId: s.id, parent: child.ref });
593
719
  } catch (e) {
594
720
  s.leave();
595
721
  await this.#closeParts(s);
@@ -625,13 +751,17 @@ export class Sessions implements SessionManager {
625
751
  if (s.ended) return s.ended;
626
752
  s.ended = (async () => {
627
753
  s.leave();
628
- for (const c of [...s.children]) await this.#end(c);
629
- await s.idle();
754
+ // 子会话同时结束:各自最多等 closeTimeoutMs,不一个个累加
755
+ await Promise.all([...s.children].map((c) => this.#end(c)));
756
+ // 等不到它停下时由接手的 Runtime 结束这一轮(aborted,没结果的调用记为错误)再写 session.ended,和正常结束的日志一样收尾
757
+ const abandoned = await this.#stopped(s);
630
758
  try {
759
+ if (abandoned) await s.rt.endTurn(abandoned);
631
760
  await s.close();
632
761
  } catch (e) {
633
762
  this.#host.report(`sub-agent session ${s.id}: could not end it: ${e instanceof Error ? e.message : String(e)}`);
634
763
  }
764
+ s.store.release?.(s.id);
635
765
  await this.#closeParts(s);
636
766
  s.child?.session.children.delete(s);
637
767
  s.onEnd?.();
@@ -920,21 +1050,29 @@ export class Sessions implements SessionManager {
920
1050
  /** 离开会话:中止正在跑的工作,等它停下,detach,关闭插件的会话作用域 */
921
1051
  async #leave(s: LiveSession): Promise<void> {
922
1052
  s.leave();
923
- // 它开的子会话一并结束:正在等子会话的工具调用随之结束
924
- for (const c of [...s.children]) await this.#end(c);
925
- await s.idle();
1053
+ // 它开的子会话一并结束(同时进行):正在等子会话的工具调用随之结束
1054
+ await Promise.all([...s.children].map((c) => this.#end(c)));
1055
+ // 等不到它停下时由接手的 Runtime 写 session.detached;没结果的调用留着,恢复时记为中断(宪法 4.5)
1056
+ await this.#stopped(s);
926
1057
  try {
927
1058
  await s.detach();
928
1059
  } catch (e) {
929
1060
  this.#host.report(`session ${s.id}: detach failed: ${e instanceof Error ? e.message : String(e)}`);
930
1061
  }
1062
+ s.store.release?.(s.id);
931
1063
  await this.#closeParts(s);
932
1064
  }
933
1065
 
1066
+ /**
1067
+ * 逆序关闭各插件在这个会话里的作用域。每个清理函数照常最多等 DISPOSE_TIMEOUT_MS,
1068
+ * 但全部加起来最多等 closeTimeoutMs:几个插件的清理函数都卡住时,关闭不会一个个累加着等下去。
1069
+ * 这段从等会话停下之后才开始算,所以离开一个会话最多等 2 × closeTimeoutMs(另加写收尾事件的时间)
1070
+ */
934
1071
  async #closeParts(s: LiveSession): Promise<void> {
1072
+ const deadline = Date.now() + this.#limits().closeTimeoutMs;
935
1073
  for (const p of [...s.parts].reverse()) {
936
1074
  this.#host.untrack(p.owner.plugin, p.owner.scope);
937
- for (const e of await p.owner.scope.close()) this.#host.report(e instanceof Error ? e.message : String(e));
1075
+ for (const e of await p.owner.scope.close(DISPOSE_TIMEOUT_MS, deadline)) this.#host.report(e instanceof Error ? e.message : String(e));
938
1076
  }
939
1077
  }
940
1078
  }
@@ -1009,6 +1147,24 @@ function liveHook(h: LocalHookSpec | RemoteHookSpec, owner: Owner): LocalHookSpe
1009
1147
  return { ...h, fn: wrapped } as LocalHookSpec;
1010
1148
  }
1011
1149
 
1150
+ /** 一个 Runtime 的围栏:gone 有值以后它的写入一律被拒;writing 是还没写完的写入 */
1151
+ type Fence = { gone?: Error; writing: Set<Promise<void>> };
1152
+
1153
+ /** 围栏关上以后拒绝写入,读照常 */
1154
+ function fenced(store: LogStore, fence: Fence): LogStore {
1155
+ return {
1156
+ append: (sessionId, events) => {
1157
+ if (fence.gone) return Promise.reject(fence.gone);
1158
+ const p = store.append(sessionId, events);
1159
+ fence.writing.add(p);
1160
+ const done = () => void fence.writing.delete(p);
1161
+ p.then(done, done);
1162
+ return p;
1163
+ },
1164
+ read: (sessionId, fromSeq) => store.read(sessionId, fromSeq),
1165
+ };
1166
+ }
1167
+
1012
1168
  /** 会话是第几层子会话:沿着 session.started 里的 parent 往上数(内核保证引用能解析到,宪法 3.4) */
1013
1169
  async function depthOf(store: LogStore, sessionId: string): Promise<number> {
1014
1170
  let depth = 0;