@uncarved/jade 0.5.0 → 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.
package/src/membrane.ts CHANGED
@@ -31,8 +31,11 @@ export class Scope {
31
31
  this.#disposers.push(owner ? { d, owner } : { d });
32
32
  }
33
33
 
34
- /** 中止 signal,逆序执行清理函数;每个最多等 DISPOSE_TIMEOUT_MS。返回清理时的错误,不抛出 */
35
- async close(timeoutMs = DISPOSE_TIMEOUT_MS): Promise<unknown[]> {
34
+ /**
35
+ * 中止 signal,逆序执行清理函数;每个最多等 timeoutMs,到了 deadline(Date.now() 的时刻)以后不再等。
36
+ * 每个清理函数都会被调用,没等到的在后台接着跑。返回清理时的错误,不抛出
37
+ */
38
+ async close(timeoutMs = DISPOSE_TIMEOUT_MS, deadline = Infinity): Promise<unknown[]> {
36
39
  if (this.#closed) return [];
37
40
  this.#closed = true;
38
41
  this.#ctrl.abort(new StaleContext(this.plugin));
@@ -42,8 +45,10 @@ export class Scope {
42
45
  let timer: ReturnType<typeof setTimeout> | undefined;
43
46
  try {
44
47
  const done = ambient.run(owner, d);
48
+ const wait = Math.max(0, Math.min(timeoutMs, deadline - Date.now()));
45
49
  const timeout = new Promise<never>((_, reject) => {
46
- timer = setTimeout(() => reject(new Error(`dispose timed out after ${timeoutMs} ms`)), timeoutMs);
50
+ const why = wait < timeoutMs ? "dispose did not finish before the close deadline" : `dispose timed out after ${timeoutMs} ms`;
51
+ timer = setTimeout(() => reject(new Error(why)), wait);
47
52
  });
48
53
  await Promise.race([done, timeout]);
49
54
  } catch (e) {
package/src/session.ts CHANGED
@@ -44,7 +44,7 @@ import {
44
44
  type ToolMeta,
45
45
  type UI,
46
46
  } from "./api.ts";
47
- import { ambient, invoke, Scope, type Owner } from "./membrane.ts";
47
+ import { ambient, DISPOSE_TIMEOUT_MS, invoke, Scope, type Owner } from "./membrane.ts";
48
48
  import { scopedSecrets } from "./secrets.ts";
49
49
 
50
50
  /** 核心自己交给内核的插件:兜底关卡 */
@@ -111,6 +111,16 @@ export const DELEGATION =
111
111
  /** 子会话的层数、同时数量的默认上限(7.2) */
112
112
  export const DEFAULT_MAX_DEPTH = 1;
113
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 };
114
124
 
115
125
  interface Turn {
116
126
  stop?: { reason: unknown };
@@ -122,7 +132,11 @@ class LiveSession implements Session {
122
132
  readonly parts: Part[] = [];
123
133
  rt!: Runtime;
124
134
  /** 排队的工作:一条输入,或者恢复(recover)。一次只跑一项,Runtime 同一时间只接受一个调用 */
125
- #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() };
126
140
  #after: { fn: () => void | Promise<void>; owner: Owner }[] = [];
127
141
  #pump: Promise<void> | undefined;
128
142
  /** 离开时的原因;有了以后不再接受输入 */
@@ -148,7 +162,7 @@ class LiveSession implements Session {
148
162
  #provider!: Provider;
149
163
  #plugins!: () => Plugin[];
150
164
 
151
- readonly #store: LogStore;
165
+ readonly #store: HostStore;
152
166
  /** 子会话的信息;顶层会话没有 */
153
167
  readonly child: Child | undefined;
154
168
  /** 第几层:顶层会话是 0 */
@@ -159,7 +173,7 @@ class LiveSession implements Session {
159
173
  ended: Promise<{ sessionId: string; seq: number }> | undefined;
160
174
  onEnd: (() => void) | undefined;
161
175
 
162
- 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) {
163
177
  this.id = id;
164
178
  this.#store = store;
165
179
  this.#report = report;
@@ -168,10 +182,16 @@ class LiveSession implements Session {
168
182
  if (child) this.depth = child.session.depth + 1;
169
183
  }
170
184
 
171
- get store(): LogStore {
185
+ /** 存储本身:读日志、开子会话、release 用。建 Runtime 用 runtimeStore() */
186
+ get store(): HostStore {
172
187
  return this.#store;
173
188
  }
174
189
 
190
+ /** 给现在要建的 Runtime 用的存储:这个 Runtime 被放弃以后,它的写入一律被拒 */
191
+ runtimeStore(): LogStore {
192
+ return fenced(this.#store, this.#fence);
193
+ }
194
+
175
195
  get provider(): Provider {
176
196
  return this.#provider;
177
197
  }
@@ -291,6 +311,24 @@ class LiveSession implements Session {
291
311
  while (this.#pump) await this.#pump;
292
312
  }
293
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
+
294
332
  /**
295
333
  * 和输入排同一个队:恢复可能要跑完一整轮,这期间插件发来的输入排在它后面,而不是撞上 RuntimeBusy。
296
334
  * 上次停在等待人工审批的(进程被杀、崩溃):内核再发一次 awaiting 通知,审批插件据此重新问(ctx.session.subscribe),
@@ -357,7 +395,7 @@ class LiveSession implements Session {
357
395
  await this.rt.detach();
358
396
  this.#loose = true;
359
397
  }
360
- 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 });
361
399
  this.#loose = false;
362
400
  this.#use(rt);
363
401
  } catch (e) {
@@ -369,7 +407,7 @@ class LiveSession implements Session {
369
407
  /** 结束会话(session.ended),子会话用完时。重挂到一半(旧实例已经 detach)时先恢复一个实例来写 */
370
408
  async close(): Promise<void> {
371
409
  if (this.#loose) {
372
- 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 }));
373
411
  this.#loose = false;
374
412
  }
375
413
  if (this.rt.phase !== "ended") await this.rt.close();
@@ -408,6 +446,7 @@ class LiveSession implements Session {
408
446
  await null; // 让调用方先拿到 send 的 Promise
409
447
  for (;;) {
410
448
  const job = this.#queue.shift();
449
+ this.#job = job;
411
450
  if (job) {
412
451
  try {
413
452
  if (this.#stale) {
@@ -419,6 +458,8 @@ class LiveSession implements Session {
419
458
  job.resolve();
420
459
  } catch (e) {
421
460
  job.reject(e);
461
+ } finally {
462
+ this.#job = undefined;
422
463
  }
423
464
  }
424
465
  if (this.#after.length > 0) await this.#runAfter();
@@ -537,7 +578,7 @@ export class Sessions implements SessionManager {
537
578
  const host = this.#host;
538
579
  const provider = host.service<Provider>("provider@1", host.core);
539
580
  if (!provider) throw new ServiceUnavailable("provider@1", "(none): no active plugin provides a model");
540
- 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")));
541
582
 
542
583
  if (opts.fork && opts.resume !== undefined) throw new Error("sessions.open: resume and fork cannot be used together");
543
584
  const s: LiveSession = new LiveSession(opts.resume ?? crypto.randomUUID(), store, host.report, () => this.#guarded(s));
@@ -552,8 +593,8 @@ export class Sessions implements SessionManager {
552
593
  for (const p of host.active()) if (p.module.session) await this.#join(s, p);
553
594
  const plugins = kernelPlugins();
554
595
  rt = opts.resume !== undefined || opts.fork
555
- ? await Runtime.resume({ store, provider, plugins, sessionId: s.id })
556
- : 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 });
557
598
  } catch (e) {
558
599
  // session() 里排进来的输入不会再执行了
559
600
  s.leave();
@@ -567,11 +608,44 @@ export class Sessions implements SessionManager {
567
608
  return s;
568
609
  }
569
610
 
570
- /** 子会话的上限(7.2):用户 config.json 的 "jade/core" */
571
- #limits(): { maxDepth: number; maxActive: number } {
611
+ /** 子会话的上限(7.2)和离开会话时最多等多久:用户 config.json 的 "jade/core" */
612
+ #limits(): { maxDepth: number; maxActive: number; closeTimeoutMs: number } {
572
613
  const c = this.#host.coreConfig();
573
614
  const n = (v: unknown, d: number, min: number) => (typeof v === "number" && Number.isInteger(v) && v >= min ? v : d);
574
- 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;
575
649
  }
576
650
 
577
651
  /** 开子会话(ctx.session.spawn):所有插件照常加入,Runtime.create 带 parent。不会成为当前会话 */
@@ -641,7 +715,7 @@ export class Sessions implements SessionManager {
641
715
  let rt: Runtime;
642
716
  try {
643
717
  for (const p of host.active()) if (p.module.session) await this.#join(s, p);
644
- 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 });
645
719
  } catch (e) {
646
720
  s.leave();
647
721
  await this.#closeParts(s);
@@ -677,13 +751,17 @@ export class Sessions implements SessionManager {
677
751
  if (s.ended) return s.ended;
678
752
  s.ended = (async () => {
679
753
  s.leave();
680
- for (const c of [...s.children]) await this.#end(c);
681
- 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);
682
758
  try {
759
+ if (abandoned) await s.rt.endTurn(abandoned);
683
760
  await s.close();
684
761
  } catch (e) {
685
762
  this.#host.report(`sub-agent session ${s.id}: could not end it: ${e instanceof Error ? e.message : String(e)}`);
686
763
  }
764
+ s.store.release?.(s.id);
687
765
  await this.#closeParts(s);
688
766
  s.child?.session.children.delete(s);
689
767
  s.onEnd?.();
@@ -972,21 +1050,29 @@ export class Sessions implements SessionManager {
972
1050
  /** 离开会话:中止正在跑的工作,等它停下,detach,关闭插件的会话作用域 */
973
1051
  async #leave(s: LiveSession): Promise<void> {
974
1052
  s.leave();
975
- // 它开的子会话一并结束:正在等子会话的工具调用随之结束
976
- for (const c of [...s.children]) await this.#end(c);
977
- 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);
978
1057
  try {
979
1058
  await s.detach();
980
1059
  } catch (e) {
981
1060
  this.#host.report(`session ${s.id}: detach failed: ${e instanceof Error ? e.message : String(e)}`);
982
1061
  }
1062
+ s.store.release?.(s.id);
983
1063
  await this.#closeParts(s);
984
1064
  }
985
1065
 
1066
+ /**
1067
+ * 逆序关闭各插件在这个会话里的作用域。每个清理函数照常最多等 DISPOSE_TIMEOUT_MS,
1068
+ * 但全部加起来最多等 closeTimeoutMs:几个插件的清理函数都卡住时,关闭不会一个个累加着等下去。
1069
+ * 这段从等会话停下之后才开始算,所以离开一个会话最多等 2 × closeTimeoutMs(另加写收尾事件的时间)
1070
+ */
986
1071
  async #closeParts(s: LiveSession): Promise<void> {
1072
+ const deadline = Date.now() + this.#limits().closeTimeoutMs;
987
1073
  for (const p of [...s.parts].reverse()) {
988
1074
  this.#host.untrack(p.owner.plugin, p.owner.scope);
989
- 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));
990
1076
  }
991
1077
  }
992
1078
  }
@@ -1061,6 +1147,24 @@ function liveHook(h: LocalHookSpec | RemoteHookSpec, owner: Owner): LocalHookSpe
1061
1147
  return { ...h, fn: wrapped } as LocalHookSpec;
1062
1148
  }
1063
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
+
1064
1168
  /** 会话是第几层子会话:沿着 session.started 里的 parent 往上数(内核保证引用能解析到,宪法 3.4) */
1065
1169
  async function depthOf(store: LogStore, sessionId: string): Promise<number> {
1066
1170
  let depth = 0;