@astralyn/pi 1.4.4 → 1.4.6

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 (230) hide show
  1. package/CHANGELOG.md +34 -0
  2. package/README.md +1 -0
  3. package/dist/bundle/chunks/chunk-5M3YJ54Z.js +82 -0
  4. package/dist/bundle/chunks/chunk-6QGV3IWD.js +6 -0
  5. package/dist/bundle/chunks/chunk-ALHAFUHP.js +7 -0
  6. package/dist/bundle/chunks/chunk-AXFWZIHH.js +4 -0
  7. package/dist/bundle/chunks/chunk-EYKC6ESU.js +2 -0
  8. package/dist/bundle/chunks/chunk-KDO6L76C.js +230 -0
  9. package/dist/bundle/chunks/chunk-RBTJBQWX.js +1500 -0
  10. package/dist/bundle/chunks/chunk-RLNMABLM.js +9 -0
  11. package/dist/bundle/chunks/cli-FH77R7JR.js +51 -0
  12. package/dist/bundle/chunks/execute-5ZQUS52M.js +505 -0
  13. package/dist/bundle/chunks/runtime-R5CMHJ5P.js +2 -0
  14. package/dist/bundle/chunks/virtual-modules-KCQU7LOC.js +2 -0
  15. package/dist/bundle/cli.js +1 -1
  16. package/dist/bundle/index.js +1 -1
  17. package/dist/bundle/rpc-entry.js +1 -1
  18. package/dist/core/agent-session.d.ts.map +1 -1
  19. package/dist/core/agent-session.js +2 -0
  20. package/dist/core/agent-session.js.map +1 -1
  21. package/dist/core/extensions/index.d.ts +1 -1
  22. package/dist/core/extensions/index.d.ts.map +1 -1
  23. package/dist/core/extensions/index.js.map +1 -1
  24. package/dist/core/extensions/runner.d.ts +2 -0
  25. package/dist/core/extensions/runner.d.ts.map +1 -1
  26. package/dist/core/extensions/runner.js +18 -0
  27. package/dist/core/extensions/runner.js.map +1 -1
  28. package/dist/core/extensions/types.d.ts +6 -0
  29. package/dist/core/extensions/types.d.ts.map +1 -1
  30. package/dist/core/extensions/types.js.map +1 -1
  31. package/dist/core/isolated-session.d.ts +23 -0
  32. package/dist/core/isolated-session.d.ts.map +1 -0
  33. package/dist/core/isolated-session.js +55 -0
  34. package/dist/core/isolated-session.js.map +1 -0
  35. package/dist/core/model-config.d.ts +1 -3
  36. package/dist/core/model-config.d.ts.map +1 -1
  37. package/dist/core/model-config.js +1 -3
  38. package/dist/core/model-config.js.map +1 -1
  39. package/dist/core/settings-manager.d.ts +4 -0
  40. package/dist/core/settings-manager.d.ts.map +1 -1
  41. package/dist/core/settings-manager.js +38 -0
  42. package/dist/core/settings-manager.js.map +1 -1
  43. package/dist/core/settings-schema.d.ts +1 -0
  44. package/dist/core/settings-schema.d.ts.map +1 -1
  45. package/dist/core/settings-schema.js +3 -0
  46. package/dist/core/settings-schema.js.map +1 -1
  47. package/dist/core/tasks/codec.d.ts +12 -0
  48. package/dist/core/tasks/codec.d.ts.map +1 -0
  49. package/dist/core/tasks/codec.js +139 -0
  50. package/dist/core/tasks/codec.js.map +1 -0
  51. package/dist/core/tasks/execution.d.ts +64 -0
  52. package/dist/core/tasks/execution.d.ts.map +1 -0
  53. package/dist/core/tasks/execution.js +272 -0
  54. package/dist/core/tasks/execution.js.map +1 -0
  55. package/dist/core/tasks/output.d.ts +12 -5
  56. package/dist/core/tasks/output.d.ts.map +1 -1
  57. package/dist/core/tasks/output.js +38 -37
  58. package/dist/core/tasks/output.js.map +1 -1
  59. package/dist/core/tasks/presentation.d.ts +14 -5
  60. package/dist/core/tasks/presentation.d.ts.map +1 -1
  61. package/dist/core/tasks/presentation.js +56 -185
  62. package/dist/core/tasks/presentation.js.map +1 -1
  63. package/dist/core/tasks/runtime.d.ts +9 -9
  64. package/dist/core/tasks/runtime.d.ts.map +1 -1
  65. package/dist/core/tasks/runtime.js +63 -252
  66. package/dist/core/tasks/runtime.js.map +1 -1
  67. package/dist/core/tasks/scheduler.d.ts +16 -0
  68. package/dist/core/tasks/scheduler.d.ts.map +1 -0
  69. package/dist/core/tasks/scheduler.js +42 -0
  70. package/dist/core/tasks/scheduler.js.map +1 -0
  71. package/dist/core/tasks/session.d.ts +1 -0
  72. package/dist/core/tasks/session.d.ts.map +1 -1
  73. package/dist/core/tasks/session.js +15 -27
  74. package/dist/core/tasks/session.js.map +1 -1
  75. package/dist/core/tasks/store.js +4 -4
  76. package/dist/core/tasks/store.js.map +1 -1
  77. package/dist/core/tasks/types.d.ts +63 -49
  78. package/dist/core/tasks/types.d.ts.map +1 -1
  79. package/dist/core/tasks/types.js +3 -9
  80. package/dist/core/tasks/types.js.map +1 -1
  81. package/dist/core/tools/render-utils.d.ts +6 -4
  82. package/dist/core/tools/render-utils.d.ts.map +1 -1
  83. package/dist/core/tools/render-utils.js +34 -14
  84. package/dist/core/tools/render-utils.js.map +1 -1
  85. package/dist/core/tools/shell-execution.js +4 -4
  86. package/dist/core/tools/shell-execution.js.map +1 -1
  87. package/dist/core/tools/shell-tool.d.ts.map +1 -1
  88. package/dist/core/tools/shell-tool.js +23 -30
  89. package/dist/core/tools/shell-tool.js.map +1 -1
  90. package/dist/core/usage-totals.d.ts +1 -3
  91. package/dist/core/usage-totals.d.ts.map +1 -1
  92. package/dist/core/usage-totals.js +17 -8
  93. package/dist/core/usage-totals.js.map +1 -1
  94. package/dist/extensions/agent/activity.d.ts +13 -0
  95. package/dist/extensions/agent/activity.d.ts.map +1 -0
  96. package/dist/extensions/agent/activity.js +75 -0
  97. package/dist/extensions/agent/activity.js.map +1 -0
  98. package/dist/extensions/agent/index.d.ts +4 -0
  99. package/dist/extensions/agent/index.d.ts.map +1 -0
  100. package/dist/extensions/agent/index.js +11 -0
  101. package/dist/extensions/agent/index.js.map +1 -0
  102. package/dist/extensions/agent/progress.d.ts +31 -0
  103. package/dist/extensions/agent/progress.d.ts.map +1 -0
  104. package/dist/extensions/agent/progress.js +145 -0
  105. package/dist/extensions/agent/progress.js.map +1 -0
  106. package/dist/extensions/agent/render.d.ts +6 -0
  107. package/dist/extensions/agent/render.d.ts.map +1 -0
  108. package/dist/extensions/agent/render.js +120 -0
  109. package/dist/extensions/agent/render.js.map +1 -0
  110. package/dist/extensions/agent/report.d.ts +9 -0
  111. package/dist/extensions/agent/report.d.ts.map +1 -0
  112. package/dist/extensions/agent/report.js +40 -0
  113. package/dist/extensions/agent/report.js.map +1 -0
  114. package/dist/extensions/agent/settings-panel.d.ts +43 -0
  115. package/dist/extensions/agent/settings-panel.d.ts.map +1 -0
  116. package/dist/extensions/agent/settings-panel.js +125 -0
  117. package/dist/extensions/agent/settings-panel.js.map +1 -0
  118. package/dist/extensions/agent/settings.d.ts +15 -0
  119. package/dist/extensions/agent/settings.d.ts.map +1 -0
  120. package/dist/extensions/agent/settings.js +201 -0
  121. package/dist/extensions/agent/settings.js.map +1 -0
  122. package/dist/extensions/agent/tool.d.ts +13 -0
  123. package/dist/extensions/agent/tool.d.ts.map +1 -0
  124. package/dist/extensions/agent/tool.js +84 -0
  125. package/dist/extensions/agent/tool.js.map +1 -0
  126. package/dist/extensions/agent/types.d.ts +43 -0
  127. package/dist/extensions/agent/types.d.ts.map +1 -0
  128. package/dist/extensions/agent/types.js +6 -0
  129. package/dist/extensions/agent/types.js.map +1 -0
  130. package/dist/extensions/agent/worker.d.ts +16 -0
  131. package/dist/extensions/agent/worker.d.ts.map +1 -0
  132. package/dist/extensions/agent/worker.js +68 -0
  133. package/dist/extensions/agent/worker.js.map +1 -0
  134. package/dist/extensions/codemode/execute.js +1 -1
  135. package/dist/extensions/codemode/execute.js.map +1 -1
  136. package/dist/extensions/codemode/execute.lazy.d.ts +2 -2
  137. package/dist/extensions/codemode/execute.lazy.d.ts.map +1 -1
  138. package/dist/extensions/codemode/execute.lazy.js +2 -2
  139. package/dist/extensions/codemode/execute.lazy.js.map +1 -1
  140. package/dist/extensions/index.d.ts.map +1 -1
  141. package/dist/extensions/index.js +2 -0
  142. package/dist/extensions/index.js.map +1 -1
  143. package/dist/extensions/mcp/cli.lazy.d.ts +2 -2
  144. package/dist/extensions/mcp/cli.lazy.d.ts.map +1 -1
  145. package/dist/extensions/mcp/cli.lazy.js +2 -2
  146. package/dist/extensions/mcp/cli.lazy.js.map +1 -1
  147. package/dist/extensions/mcp/index.d.ts.map +1 -1
  148. package/dist/extensions/mcp/index.js +2 -2
  149. package/dist/extensions/mcp/index.js.map +1 -1
  150. package/dist/extensions/mcp/runtime.lazy.d.ts +2 -2
  151. package/dist/extensions/mcp/runtime.lazy.d.ts.map +1 -1
  152. package/dist/extensions/mcp/runtime.lazy.js +2 -2
  153. package/dist/extensions/mcp/runtime.lazy.js.map +1 -1
  154. package/dist/extensions/provider/compat-fields.js +1 -1
  155. package/dist/extensions/provider/compat-fields.js.map +1 -1
  156. package/dist/extensions/tasks/tool/actions.d.ts.map +1 -1
  157. package/dist/extensions/tasks/tool/actions.js +1 -9
  158. package/dist/extensions/tasks/tool/actions.js.map +1 -1
  159. package/dist/extensions/tasks/tool/schema.js +1 -1
  160. package/dist/extensions/tasks/tool/schema.js.map +1 -1
  161. package/dist/extensions/tasks/tool/types.d.ts +2 -8
  162. package/dist/extensions/tasks/tool/types.d.ts.map +1 -1
  163. package/dist/extensions/tasks/tool/types.js +0 -2
  164. package/dist/extensions/tasks/tool/types.js.map +1 -1
  165. package/dist/extensions/tasks/ui/completion-render.d.ts.map +1 -1
  166. package/dist/extensions/tasks/ui/completion-render.js +27 -26
  167. package/dist/extensions/tasks/ui/completion-render.js.map +1 -1
  168. package/dist/extensions/tasks/ui/inspector.d.ts +5 -3
  169. package/dist/extensions/tasks/ui/inspector.d.ts.map +1 -1
  170. package/dist/extensions/tasks/ui/inspector.js +18 -6
  171. package/dist/extensions/tasks/ui/inspector.js.map +1 -1
  172. package/dist/extensions/tasks/ui/layout.d.ts.map +1 -1
  173. package/dist/extensions/tasks/ui/layout.js +111 -75
  174. package/dist/extensions/tasks/ui/layout.js.map +1 -1
  175. package/dist/extensions/tasks/ui/list.d.ts.map +1 -1
  176. package/dist/extensions/tasks/ui/list.js +43 -28
  177. package/dist/extensions/tasks/ui/list.js.map +1 -1
  178. package/dist/extensions/tasks/ui/manager.d.ts.map +1 -1
  179. package/dist/extensions/tasks/ui/manager.js +8 -2
  180. package/dist/extensions/tasks/ui/manager.js.map +1 -1
  181. package/dist/extensions/tasks/ui/model.d.ts +4 -0
  182. package/dist/extensions/tasks/ui/model.d.ts.map +1 -1
  183. package/dist/extensions/tasks/ui/model.js +12 -1
  184. package/dist/extensions/tasks/ui/model.js.map +1 -1
  185. package/dist/extensions/tasks/ui/render.js +3 -4
  186. package/dist/extensions/tasks/ui/render.js.map +1 -1
  187. package/dist/extensions/tasks/ui/task-view.d.ts +0 -5
  188. package/dist/extensions/tasks/ui/task-view.d.ts.map +1 -1
  189. package/dist/extensions/tasks/ui/task-view.js +0 -7
  190. package/dist/extensions/tasks/ui/task-view.js.map +1 -1
  191. package/dist/extensions/tasks/ui/tree.js +1 -1
  192. package/dist/extensions/tasks/ui/tree.js.map +1 -1
  193. package/dist/extensions/tasks/ui/views.d.ts +10 -6
  194. package/dist/extensions/tasks/ui/views.d.ts.map +1 -1
  195. package/dist/extensions/tasks/ui/views.js +64 -28
  196. package/dist/extensions/tasks/ui/views.js.map +1 -1
  197. package/dist/index.d.ts +2 -1
  198. package/dist/index.d.ts.map +1 -1
  199. package/dist/index.js.map +1 -1
  200. package/dist/modes/interactive/components/keybinding-hints.d.ts.map +1 -1
  201. package/dist/modes/interactive/components/keybinding-hints.js +2 -1
  202. package/dist/modes/interactive/components/keybinding-hints.js.map +1 -1
  203. package/dist/modes/interactive/components/model-selector.d.ts.map +1 -1
  204. package/dist/modes/interactive/components/model-selector.js +7 -4
  205. package/dist/modes/interactive/components/model-selector.js.map +1 -1
  206. package/dist/modes/interactive/components/thinking-selector.d.ts.map +1 -1
  207. package/dist/modes/interactive/components/thinking-selector.js +10 -3
  208. package/dist/modes/interactive/components/thinking-selector.js.map +1 -1
  209. package/docs/bundled/README.md +1 -0
  210. package/docs/bundled/extensions/agent.md +68 -0
  211. package/docs/bundled/extensions/statusline.md +1 -1
  212. package/docs/bundled/tasks.md +15 -14
  213. package/docs/docs.json +4 -0
  214. package/docs/extensions.md +33 -6
  215. package/docs/sdk.md +2 -2
  216. package/docs/session-format.md +27 -23
  217. package/npm-shrinkwrap.json +2 -2
  218. package/package.json +1 -1
  219. package/schemas/settings.schema.json +12 -0
  220. package/dist/bundle/chunks/chunk-SBVVM3NV.js +0 -2361
  221. package/dist/bundle/chunks/chunk-VGSZTBVJ.js +0 -2
  222. package/dist/bundle/chunks/virtual-modules-ETYFHSUG.js +0 -2
  223. package/dist/core/tasks/history.d.ts +0 -4
  224. package/dist/core/tasks/history.d.ts.map +0 -1
  225. package/dist/core/tasks/history.js +0 -121
  226. package/dist/core/tasks/history.js.map +0 -1
  227. package/dist/extensions/codemode/search.d.ts +0 -33
  228. package/dist/extensions/codemode/search.d.ts.map +0 -1
  229. package/dist/extensions/codemode/search.js +0 -117
  230. package/dist/extensions/codemode/search.js.map +0 -1
@@ -1,40 +1,49 @@
1
1
  import { randomUUID } from "node:crypto";
2
+ import { Execution, errorText } from "./execution.js";
2
3
  import { TASKS_WAIT_DEFAULT_MS, TASKS_WAIT_MAX_MS } from "./limits.js";
3
- import { boundText, finiteLimit, readOutputSlice, retainResult, sliceText, TASK_TITLE_BYTES } from "./output.js";
4
- import { changed, snapshotOf, TaskStore } from "./store.js";
5
- import { TASK_BACKGROUND_REJECTION, TaskExecutionError, TaskLookupError, } from "./types.js";
6
- function errorText(error) {
7
- try {
8
- return boundText(error instanceof Error ? error.message : String(error), 4096);
9
- }
10
- catch {
11
- return "Task execution failed (unprintable error)";
12
- }
13
- }
4
+ import { boundFacts, boundInput, boundText, finiteLimit, readOutputSlice, sliceText, TASK_LABEL_BYTES, TASK_TITLE_BYTES, } from "./output.js";
5
+ import { TaskScheduler } from "./scheduler.js";
6
+ import { snapshotOf, TaskStore } from "./store.js";
7
+ import { TASK_BACKGROUND_REJECTION, TASK_KIND_PATTERN, TaskLookupError, } from "./types.js";
14
8
  /** Session-local supervision. Executors own their processes, items and output files. */
15
9
  export class TaskRuntime {
16
- get closed() {
17
- return this._closed;
18
- }
19
- get session() {
20
- return this.options.session;
21
- }
22
10
  constructor(options = {}) {
23
11
  this.executions = new Map();
12
+ this.scheduler = new TaskScheduler();
24
13
  this.listeners = new Set();
25
14
  this._closed = false;
26
15
  this.pauses = 0;
27
16
  this.options = options;
28
17
  this.configuredEnabled = options.enabled ?? false;
29
- this.maxActive = Math.max(1, finiteLimit(options.maxActive, 8, 128));
18
+ this.maxBackground = Math.max(1, finiteLimit(options.maxBackground, 8, 128));
30
19
  this.maxHistory = finiteLimit(options.maxHistory, 32, 1024);
31
20
  // Separate foreground and background histories, plus the protected-record allowance.
32
- this.maxRetained = this.maxActive + 2 * Math.max(1, this.maxHistory) + this.maxHistory;
21
+ this.maxRetained = this.maxBackground + 2 * Math.max(1, this.maxHistory) + this.maxHistory;
33
22
  this.store = new TaskStore(this.maxHistory, this.maxRetained, () => this.closed, options.onCleanupError);
23
+ const runtime = this;
24
+ this.host = {
25
+ get closed() {
26
+ return runtime.closed;
27
+ },
28
+ emit: () => this.emit(),
29
+ settle: (task, usage) => this.options.onSettled?.(task, usage),
30
+ released: (execution) => {
31
+ this.executions.delete(execution.task.id);
32
+ this.scheduler.release(execution);
33
+ this.store.trim();
34
+ this.emit();
35
+ },
36
+ };
37
+ }
38
+ get closed() {
39
+ return this._closed;
40
+ }
41
+ get session() {
42
+ return this.options.session;
34
43
  }
35
44
  /**
36
- * Rehydrate terminal version-2 custom data only, newest endedAt in each history
37
- * (later input wins ties). Existing runtime records win ID collisions. No execution, accounting,
45
+ * Rehydrate terminal snapshots only, newest endedAt in each history (later input wins
46
+ * ties). Existing runtime records win ID collisions. No execution, accounting,
38
47
  * notification, or deletion ownership is restored. Foreground records take their output
39
48
  * from the branch's tool results. The host supplies the current branch; closed services
40
49
  * ignore restoration.
@@ -49,7 +58,7 @@ export class TaskRuntime {
49
58
  this.configuredEnabled = enabled;
50
59
  this.emit();
51
60
  }
52
- /** Foreground work is bounded by its caller; only background work holds a slot. */
61
+ /** Foreground work is bounded by its caller; only background work, queued or running, holds a slot. */
53
62
  backgroundActive() {
54
63
  let count = 0;
55
64
  for (const record of this.store.records.values())
@@ -58,7 +67,7 @@ export class TaskRuntime {
58
67
  return count;
59
68
  }
60
69
  limitError() {
61
- return new Error(`Background task limit reached (${this.maxActive}); stop or wait for a background task, or run in the foreground.`);
70
+ return new Error(`Background task limit reached (${this.maxBackground}); stop or wait for a background task, or run in the foreground.`);
62
71
  }
63
72
  async execute(execution) {
64
73
  // Admission and registration happen synchronously, before invoking user code or awaiting anything.
@@ -69,7 +78,7 @@ export class TaskRuntime {
69
78
  if (execution.background) {
70
79
  if (!this.enabled)
71
80
  throw new Error("Background execution is not available in this host");
72
- if (this.backgroundActive() >= this.maxActive)
81
+ if (this.backgroundActive() >= this.maxBackground)
73
82
  throw this.limitError();
74
83
  if (this.store.records.size + this.store.cleanups.size >= this.maxRetained) {
75
84
  throw new Error("Task history retention limit reached; deliver pending notifications or release pinned or claimed records");
@@ -77,31 +86,28 @@ export class TaskRuntime {
77
86
  }
78
87
  if (execution.signal?.aborted)
79
88
  throw execution.signal.reason ?? new Error("Execution aborted");
80
- if (!/^[a-z][a-z0-9-]{0,63}$/.test(execution.kind))
89
+ if (!TASK_KIND_PATTERN.test(execution.kind))
81
90
  throw new Error("Invalid task source");
91
+ const concurrency = execution.concurrency;
92
+ if (concurrency && (!concurrency.key || !Number.isSafeInteger(concurrency.limit) || concurrency.limit < 1))
93
+ throw new Error("Invalid task concurrency");
82
94
  const anchorId = this.options.anchor?.() ?? null;
83
95
  if (anchorId !== null && Buffer.byteLength(anchorId) > 8192)
84
96
  throw new Error("Task branch anchor is too large");
85
97
  const task = {
86
98
  id: `${execution.kind}-${randomUUID()}`,
87
99
  kind: execution.kind,
100
+ label: boundText(execution.label ?? execution.kind, TASK_LABEL_BYTES),
88
101
  title: boundText(execution.title, TASK_TITLE_BYTES),
102
+ output: execution.output ?? "log",
103
+ ...(execution.input ? { input: boundInput(execution.input) } : {}),
104
+ ...(execution.facts?.length ? { facts: boundFacts(execution.facts) } : {}),
89
105
  toolCallId: boundText(execution.toolCallId, 512),
90
106
  anchorId,
91
107
  mode: execution.background ? "background" : "foreground",
92
108
  status: "queued",
93
109
  startedAt: Date.now(),
94
- command: execution.command === undefined ? undefined : boundText(execution.command, 8192),
95
- commandTruncated: execution.command === undefined ? undefined : boundText(execution.command, 8192) !== execution.command,
96
- cwd: execution.cwd === undefined ? undefined : boundText(execution.cwd, 4096),
97
110
  };
98
- let resolveCaller;
99
- let rejectCaller;
100
- const caller = new Promise((resolve, reject) => {
101
- resolveCaller = resolve;
102
- rejectCaller = reject;
103
- });
104
- let resolveDone;
105
111
  const record = {
106
112
  task,
107
113
  settled: false,
@@ -111,182 +117,18 @@ export class TaskRuntime {
111
117
  deliveryHolds: 0,
112
118
  waiters: new Set(),
113
119
  };
114
- const active = {
115
- controller: new AbortController(),
116
- accepted: false,
117
- handedOff: false,
118
- detachRequested: execution.background ?? false,
119
- modeListeners: new Set(),
120
- removeParent: () => { },
121
- handoff: () => {
122
- if (!active.accepted ||
123
- !active.detachRequested ||
124
- record.settled ||
125
- active.handedOff ||
126
- this.closed ||
127
- !record.visible ||
128
- active.controller.signal.aborted)
129
- return;
130
- active.handedOff = true;
131
- task.mode = "background";
132
- changed(record);
133
- active.removeParent();
134
- resolveCaller({ kind: "background", task: snapshotOf(record) });
135
- this.emit();
136
- },
137
- done: new Promise((resolve) => {
138
- resolveDone = resolve;
139
- }),
140
- };
141
- const parentSignal = execution.signal;
142
- let onUpdate = execution.background ? undefined : execution.onUpdate;
143
- const parentAbort = () => {
144
- if (!active.detachRequested || !active.accepted)
145
- this.cancel(record);
146
- };
147
- parentSignal?.addEventListener("abort", parentAbort, { once: true });
148
- active.removeParent = () => {
149
- parentSignal?.removeEventListener("abort", parentAbort);
150
- onUpdate = undefined;
151
- };
120
+ const active = new Execution(this.host, record, execution);
152
121
  this.store.records.set(task.id, record);
153
122
  this.executions.set(task.id, active);
154
- const control = {
155
- id: task.id,
156
- signal: active.controller.signal,
157
- get mode() {
158
- return task.mode;
159
- },
160
- onModeChange: (listener) => {
161
- if (record.settled || this.closed)
162
- return () => { };
163
- active.modeListeners.add(listener);
164
- return () => {
165
- active.modeListeners.delete(listener);
166
- };
167
- },
168
- requestCancel: () => this.cancel(record),
169
- accept: () => {
170
- if (record.settled || active.accepted || this.closed || active.controller.signal.aborted)
171
- return;
172
- active.accepted = true;
173
- if (task.status === "queued")
174
- task.status = "running";
175
- changed(record);
176
- if (active.detachRequested)
177
- active.removeParent();
178
- // Let an already available final result win over a handoff.
179
- queueMicrotask(() => queueMicrotask(active.handoff));
180
- this.emit();
181
- },
182
- publish: (result) => {
183
- if (record.settled || this.closed)
184
- return;
185
- retainResult(task, result);
186
- changed(record);
187
- if (result.usage !== undefined)
188
- active.publishedUsage = structuredClone(result.usage);
189
- if (!active.detachRequested && !active.handedOff) {
190
- try {
191
- onUpdate?.(result);
192
- }
193
- catch {
194
- /* UI observers cannot stop execution. */
195
- }
196
- }
197
- this.emit();
198
- },
199
- setOutputPath: (path, cleanup) => {
200
- if (record.settled) {
201
- if (cleanup)
202
- throw new Error("Task execution has settled");
203
- return;
204
- }
205
- if (record.cleanup)
206
- throw new Error("Managed output is already registered");
207
- // Never truncate a real filesystem path into a different path.
208
- if (Buffer.byteLength(path) > 8192)
209
- throw new Error("Task output path is too large");
210
- record.cleanup = cleanup;
211
- task.outputPath = path;
212
- changed(record);
213
- this.emit();
214
- },
215
- };
216
- const finish = (completion, error) => {
217
- if (record.settled)
218
- return;
219
- record.settled = true;
220
- active.modeListeners.clear();
221
- active.removeParent();
222
- task.endedAt = Date.now();
223
- const failed = completion === undefined;
224
- task.status =
225
- completion?.status ??
226
- (error instanceof TaskExecutionError
227
- ? error.status
228
- : active.controller.signal.aborted
229
- ? "cancelled"
230
- : failed
231
- ? "failed"
232
- : "completed");
233
- if (completion) {
234
- retainResult(task, completion.result);
235
- if (completion.error !== undefined)
236
- task.error = boundText(completion.error, 4096);
237
- if (completion.exitCode !== undefined)
238
- task.exitCode = completion.exitCode;
239
- }
240
- if (failed) {
241
- task.error = errorText(error);
242
- retainResult(task, { content: [{ type: "text", text: task.error }, ...(task.result?.content ?? [])], details: undefined }, task.resultTruncated);
243
- }
244
- changed(record);
245
- let settlementWarning;
246
- try {
247
- this.options.onSettled?.(snapshotOf(record), completion?.usage ?? completion?.result.usage ?? active.publishedUsage);
248
- }
249
- catch (accountingError) {
250
- const warning = `Usage settlement failed: ${errorText(accountingError)}`;
251
- settlementWarning = warning;
252
- task.error = boundText([task.error, warning].filter(Boolean).join("\n"), 8192);
253
- retainResult(task, { content: [{ type: "text", text: warning }, ...(task.result?.content ?? [])], details: undefined }, task.resultTruncated);
254
- changed(record);
255
- }
256
- active.publishedUsage = undefined;
257
- // Delivery becomes eligible only after settlement is persisted.
258
- record.delivery = active.handedOff ? "pending" : "delivered";
259
- if (!active.handedOff) {
260
- if (failed)
261
- rejectCaller(error);
262
- else {
263
- const { usage: _usage, ...result } = completion.result;
264
- if (settlementWarning)
265
- result.content = [{ type: "text", text: settlementWarning }, ...result.content];
266
- resolveCaller({ kind: "result", result, status: task.status, error: task.error });
267
- }
268
- }
269
- for (const waiter of [...record.waiters])
270
- waiter();
271
- resolveDone();
272
- this.executions.delete(task.id);
273
- this.store.trim();
274
- this.emit();
275
- };
276
- // The rejection handler is installed immediately, including for synchronous preflight throws.
277
- try {
278
- const running = execution.run(control);
279
- void Promise.resolve(running).then((result) => finish(result), (error) => finish(undefined, error));
280
- }
281
- catch (error) {
282
- finish(undefined, error);
283
- }
123
+ this.scheduler.schedule(active);
124
+ // Queued background work returns at once; started work hands off after its own accept().
125
+ if (active.queued)
126
+ active.handoff();
284
127
  this.emit();
285
- return caller;
128
+ return active.caller;
286
129
  }
287
130
  detachable(record) {
288
- const active = this.executions.get(record.task.id);
289
- return !!active && !record.settled && !active.detachRequested && !active.controller.signal.aborted;
131
+ return this.executions.get(record.task.id)?.detachable ?? false;
290
132
  }
291
133
  detachForeground() {
292
134
  if (!this.enabled)
@@ -296,52 +138,33 @@ export class TaskRuntime {
296
138
  .sort((left, right) => left.task.startedAt - right.task.startedAt);
297
139
  if (!eligible.length)
298
140
  return 0;
299
- const free = this.maxActive - this.backgroundActive();
141
+ const free = this.maxBackground - this.backgroundActive();
300
142
  if (free <= 0)
301
143
  throw this.limitError();
302
- const records = eligible.slice(0, free);
303
- for (const record of records)
304
- this.prepareDetach(record);
305
- for (const record of records)
306
- this.finishDetach(record);
144
+ const executions = eligible.slice(0, free).map((record) => this.executions.get(record.task.id));
145
+ for (const execution of executions)
146
+ execution.requestDetach();
147
+ for (const execution of executions)
148
+ execution.completeDetach();
307
149
  this.emit();
308
- return records.length;
150
+ return executions.length;
309
151
  }
310
152
  canDetach(id) {
311
153
  const record = this.lookup(id);
312
- return this.enabled && this.backgroundActive() < this.maxActive && this.detachable(record);
154
+ return this.enabled && this.backgroundActive() < this.maxBackground && this.detachable(record);
313
155
  }
314
156
  detach(id) {
315
157
  const record = this.lookup(id);
316
158
  if (!this.enabled || !this.detachable(record))
317
159
  return false;
318
- if (this.backgroundActive() >= this.maxActive)
160
+ if (this.backgroundActive() >= this.maxBackground)
319
161
  throw this.limitError();
320
- this.prepareDetach(record);
321
- this.finishDetach(record);
162
+ const execution = this.executions.get(record.task.id);
163
+ execution.requestDetach();
164
+ execution.completeDetach();
322
165
  this.emit();
323
166
  return true;
324
167
  }
325
- prepareDetach(record) {
326
- const active = this.executions.get(record.task.id);
327
- active.detachRequested = true;
328
- record.task.mode = "background";
329
- changed(record);
330
- if (active.accepted)
331
- active.removeParent();
332
- }
333
- finishDetach(record) {
334
- const active = this.executions.get(record.task.id);
335
- active.handoff();
336
- for (const listener of active.modeListeners) {
337
- try {
338
- listener(record.task.mode);
339
- }
340
- catch {
341
- /* Executors own their diagnostics. */
342
- }
343
- }
344
- }
345
168
  list() {
346
169
  return [...this.store.records.values()].filter((record) => record.visible).map(snapshotOf);
347
170
  }
@@ -382,12 +205,7 @@ export class TaskRuntime {
382
205
  }
383
206
  }
384
207
  resultText(task) {
385
- return boundText(task.result?.content
386
- .filter((block) => block.type === "text")
387
- .map((block) => block.text)
388
- .join("\n") ||
389
- task.error ||
390
- "No output yet.");
208
+ return task.result?.text || task.error || "No output yet.";
391
209
  }
392
210
  /** One event-driven waiter can observe a whole waitAny cohort without per-task timers. */
393
211
  waitForRecords(records, timeoutMs, signal, interruptSignal) {
@@ -453,14 +271,7 @@ export class TaskRuntime {
453
271
  return this.cancel(this.lookup(id));
454
272
  }
455
273
  cancel(record) {
456
- const active = this.executions.get(record.task.id);
457
- if (!active || record.settled || active.controller.signal.aborted)
458
- return false;
459
- record.task.status = "stopping";
460
- changed(record);
461
- active.controller.abort();
462
- this.emit();
463
- return true;
274
+ return this.executions.get(record.task.id)?.cancel() ?? false;
464
275
  }
465
276
  subscribe(listener) {
466
277
  if (this.closed)
@@ -550,7 +361,7 @@ export class TaskRuntime {
550
361
  this._closed = true;
551
362
  this.listeners.clear();
552
363
  for (const record of this.store.records.values()) {
553
- this.executions.get(record.task.id)?.removeParent();
364
+ this.executions.get(record.task.id)?.releaseParent();
554
365
  this.cancel(record);
555
366
  for (const waiter of [...record.waiters])
556
367
  waiter();
@@ -1 +1 @@
1
- {"version":3,"file":"runtime.js","sourceRoot":"","sources":["../../../src/core/tasks/runtime.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AAGzC,OAAO,EAAE,qBAAqB,EAAE,iBAAiB,EAAE,MAAM,aAAa,CAAC;AACvE,OAAO,EAAE,SAAS,EAAE,WAAW,EAAE,eAAe,EAAE,YAAY,EAAE,SAAS,EAAE,gBAAgB,EAAE,MAAM,aAAa,CAAC;AACjH,OAAO,EAAE,OAAO,EAAE,UAAU,EAAmB,SAAS,EAAE,MAAM,YAAY,CAAC;AAC7E,OAAO,EACN,yBAAyB,EAIzB,kBAAkB,EAClB,eAAe,GAOf,MAAM,YAAY,CAAC;AAcpB,SAAS,SAAS,CAAC,KAAc;IA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AAE,CAAC;QAClB,IAAI,CAAC,IAAI,EAAE,CAAC;QACZ,MAAM,IAAI,CAAC,KAAK,CAAC,OAAO,EAAE,IAAI,CAAC,CAAC;IACjC,CAAC;IAEO,KAAK,CAAC,KAAK,CAAC,OAAqB,EAAE,OAAe;QACzD,IAAI,KAAgD,CAAC;QACrD,IAAI,CAAC;YACJ,MAAM,OAAO,CAAC,IAAI,CAAC;gBAClB,OAAO,CAAC,GAAG,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC,MAAM,EAAE,EAAE,CAAC,IAAI,CAAC,UAAU,CAAC,GAAG,CAAC,MAAM,CAAC,IAAI,CAAC,EAAE,CAAC,EAAE,IAAI,CAAC,CAAC,CAAC,IAAI,CAAC,GAAG,EAAE,CACzF,OAAO,CAAC,GAAG,CAAC,IAAI,CAAC,KAAK,CAAC,QAAQ,CAAC,CAChC;gBACD,IAAI,OAAO,CAAO,CAAC,OAAO,EAAE,EAAE;oBAC7B,KAAK,GAAG,UAAU,CAAC,OAAO,EAAE,WAAW,CAAC,OAAO,EAAE,IAAI,EAAE,MAAM,CAAC,CAAC,CAAC;gBACjE,CAAC,CAAC;aACF,CAAC,CAAC;QACJ,CAAC;gBAAS,CAAC;YACV,IAAI,KAAK,KAAK,SAAS;gBAAE,YAAY,CAAC,KAAK,CAAC,CAAC;QAC9C,CAAC;IACF,CAAC;IAEO,IAAI;QACX,IAAI,IAAI,CAAC,MAAM;YAAE,OAAO;QACxB,KAAK,MAAM,QAAQ,IAAI,CAAC,GAAG,IAAI,CAAC,SAAS,CAAC,EAAE,CAAC;YAC5C,IAAI,IAAI,CAAC,MAAM;gBAAE,MAAM;YACvB,IAAI,CAAC;gBACJ,QAAQ,EAAE,CAAC;YACZ,CAAC;YAAC,MAAM,CAAC;gBACR,iDAAiD;YAClD,CAAC;QACF,CAAC;IACF,CAAC;CACD","sourcesContent":["import { randomUUID } from \"node:crypto\";\nimport type { AgentToolResult } from \"@earendil-works/pi-agent-core\";\nimport type { Usage } from \"@earendil-works/pi-ai/compat\";\nimport { TASKS_WAIT_DEFAULT_MS, TASKS_WAIT_MAX_MS } from \"./limits.ts\";\nimport { boundText, finiteLimit, readOutputSlice, retainResult, sliceText, TASK_TITLE_BYTES } from \"./output.ts\";\nimport { changed, snapshotOf, type TaskRecord, TaskStore } from \"./store.ts\";\nimport {\n\tTASK_BACKGROUND_REJECTION,\n\ttype TaskCompletion,\n\ttype TaskControl,\n\ttype TaskExecution,\n\tTaskExecutionError,\n\tTaskLookupError,\n\ttype TaskMode,\n\ttype TaskRead,\n\ttype TaskRuntimeOptions,\n\ttype TaskSnapshot,\n\ttype TasksContext,\n\ttype TaskToolOutcome,\n} from \"./types.ts\";\n\ninterface ActiveTask {\n\tcontroller: AbortController;\n\taccepted: boolean;\n\thandedOff: boolean;\n\tdetachRequested: boolean;\n\tpublishedUsage?: Usage;\n\tmodeListeners: Set<(mode: TaskMode) => void>;\n\tremoveParent(): void;\n\thandoff(): void;\n\tdone: Promise<void>;\n}\n\nfunction errorText(error: unknown): string {\n\ttry {\n\t\treturn boundText(error instanceof Error ? error.message : String(error), 4096);\n\t} catch {\n\t\treturn \"Task execution failed (unprintable error)\";\n\t}\n}\n\n/** Session-local supervision. Executors own their processes, items and output files. */\nexport class TaskRuntime implements TasksContext {\n\tprivate readonly store: TaskStore;\n\tprivate readonly executions = new Map<string, ActiveTask>();\n\tprivate readonly listeners = new Set<() => void>();\n\tprivate readonly maxActive: number;\n\tprivate readonly maxHistory: number;\n\tprivate readonly maxRetained: number;\n\tprivate configuredEnabled: boolean;\n\tprivate _closed = false;\n\n\tget closed(): boolean {\n\t\treturn this._closed;\n\t}\n\n\tget session(): TaskRuntimeOptions[\"session\"] {\n\t\treturn this.options.session;\n\t}\n\n\tprivate pauses = 0;\n\n\tprivate readonly options: TaskRuntimeOptions;\n\n\tconstructor(options: TaskRuntimeOptions = {}) {\n\t\tthis.options = options;\n\t\tthis.configuredEnabled = options.enabled ?? false;\n\t\tthis.maxActive = Math.max(1, finiteLimit(options.maxActive, 8, 128));\n\t\tthis.maxHistory = finiteLimit(options.maxHistory, 32, 1024);\n\t\t// Separate foreground and background histories, plus the protected-record allowance.\n\t\tthis.maxRetained = this.maxActive + 2 * Math.max(1, this.maxHistory) + this.maxHistory;\n\t\tthis.store = new TaskStore(this.maxHistory, this.maxRetained, () => this.closed, options.onCleanupError);\n\t}\n\n\t/**\n\t * Rehydrate terminal version-2 custom data only, newest endedAt in each history\n\t * (later input wins ties). Existing runtime records win ID collisions. No execution, accounting,\n\t * notification, or deletion ownership is restored. Foreground records take their output\n\t * from the branch's tool results. The host supplies the current branch; closed services\n\t * ignore restoration.\n\t */\n\trestoreHistory(\n\t\trecords: readonly unknown[],\n\t\ttoolResults?: ReadonlyMap<string, AgentToolResult<unknown>[\"content\"]>,\n\t): void {\n\t\tthis.store.restoreHistory(records, toolResults);\n\t}\n\n\tget enabled(): boolean {\n\t\treturn this.configuredEnabled && !this.closed && this.options.backgroundAllowed !== false;\n\t}\n\n\tsetEnabled(enabled: boolean): void {\n\t\tthis.configuredEnabled = enabled;\n\t\tthis.emit();\n\t}\n\n\t/** Foreground work is bounded by its caller; only background work holds a slot. */\n\tprivate backgroundActive(): number {\n\t\tlet count = 0;\n\t\tfor (const record of this.store.records.values())\n\t\t\tif (!record.settled && record.task.mode === \"background\") count++;\n\t\treturn count;\n\t}\n\n\tprivate limitError(): Error {\n\t\treturn new Error(\n\t\t\t`Background task limit reached (${this.maxActive}); stop or wait for a background task, or run in the foreground.`,\n\t\t);\n\t}\n\n\tasync execute<T>(execution: TaskExecution<T>): Promise<TaskToolOutcome<T>> {\n\t\t// Admission and registration happen synchronously, before invoking user code or awaiting anything.\n\t\tif (execution.background && this.options.backgroundAllowed === false) throw new Error(TASK_BACKGROUND_REJECTION);\n\t\tif (this.closed) throw new Error(\"Task service is closed\");\n\t\tif (execution.background) {\n\t\t\tif (!this.enabled) throw new Error(\"Background execution is not available in this host\");\n\t\t\tif (this.backgroundActive() >= this.maxActive) throw this.limitError();\n\t\t\tif (this.store.records.size + this.store.cleanups.size >= this.maxRetained) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t\"Task history retention limit reached; deliver pending notifications or release pinned or claimed records\",\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t\tif (execution.signal?.aborted) throw execution.signal.reason ?? new Error(\"Execution aborted\");\n\t\tif (!/^[a-z][a-z0-9-]{0,63}$/.test(execution.kind)) throw new Error(\"Invalid task source\");\n\t\tconst anchorId = this.options.anchor?.() ?? null;\n\t\tif (anchorId !== null && Buffer.byteLength(anchorId) > 8192) throw new Error(\"Task branch anchor is too large\");\n\t\tconst task: TaskSnapshot = {\n\t\t\tid: `${execution.kind}-${randomUUID()}`,\n\t\t\tkind: execution.kind,\n\t\t\ttitle: boundText(execution.title, TASK_TITLE_BYTES),\n\t\t\ttoolCallId: boundText(execution.toolCallId, 512),\n\t\t\tanchorId,\n\t\t\tmode: execution.background ? \"background\" : \"foreground\",\n\t\t\tstatus: \"queued\",\n\t\t\tstartedAt: Date.now(),\n\t\t\tcommand: execution.command === undefined ? undefined : boundText(execution.command, 8192),\n\t\t\tcommandTruncated:\n\t\t\t\texecution.command === undefined ? undefined : boundText(execution.command, 8192) !== execution.command,\n\t\t\tcwd: execution.cwd === undefined ? undefined : boundText(execution.cwd, 4096),\n\t\t};\n\t\tlet resolveCaller!: (outcome: TaskToolOutcome<T>) => void;\n\t\tlet rejectCaller!: (error: unknown) => void;\n\t\tconst caller = new Promise<TaskToolOutcome<T>>((resolve, reject) => {\n\t\t\tresolveCaller = resolve;\n\t\t\trejectCaller = reject;\n\t\t});\n\t\tlet resolveDone!: () => void;\n\t\tconst record: TaskRecord = {\n\t\t\ttask,\n\t\t\tsettled: false,\n\t\t\tvisible: true,\n\t\t\tdelivery: \"none\",\n\t\t\tpins: 0,\n\t\t\tdeliveryHolds: 0,\n\t\t\twaiters: new Set(),\n\t\t};\n\t\tconst active: ActiveTask = {\n\t\t\tcontroller: new AbortController(),\n\t\t\taccepted: false,\n\t\t\thandedOff: false,\n\t\t\tdetachRequested: execution.background ?? false,\n\t\t\tmodeListeners: new Set(),\n\t\t\tremoveParent: () => {},\n\t\t\thandoff: () => {\n\t\t\t\tif (\n\t\t\t\t\t!active.accepted ||\n\t\t\t\t\t!active.detachRequested ||\n\t\t\t\t\trecord.settled ||\n\t\t\t\t\tactive.handedOff ||\n\t\t\t\t\tthis.closed ||\n\t\t\t\t\t!record.visible ||\n\t\t\t\t\tactive.controller.signal.aborted\n\t\t\t\t)\n\t\t\t\t\treturn;\n\t\t\t\tactive.handedOff = true;\n\t\t\t\ttask.mode = \"background\";\n\t\t\t\tchanged(record);\n\t\t\t\tactive.removeParent();\n\t\t\t\tresolveCaller({ kind: \"background\", task: snapshotOf(record) });\n\t\t\t\tthis.emit();\n\t\t\t},\n\t\t\tdone: new Promise<void>((resolve) => {\n\t\t\t\tresolveDone = resolve;\n\t\t\t}),\n\t\t};\n\t\tconst parentSignal = execution.signal;\n\t\tlet onUpdate = execution.background ? undefined : execution.onUpdate;\n\t\tconst parentAbort = () => {\n\t\t\tif (!active.detachRequested || !active.accepted) this.cancel(record);\n\t\t};\n\t\tparentSignal?.addEventListener(\"abort\", parentAbort, { once: true });\n\t\tactive.removeParent = () => {\n\t\t\tparentSignal?.removeEventListener(\"abort\", parentAbort);\n\t\t\tonUpdate = undefined;\n\t\t};\n\t\tthis.store.records.set(task.id, record);\n\t\tthis.executions.set(task.id, active);\n\t\tconst control: TaskControl<T> = {\n\t\t\tid: task.id,\n\t\t\tsignal: active.controller.signal,\n\t\t\tget mode() {\n\t\t\t\treturn task.mode;\n\t\t\t},\n\t\t\tonModeChange: (listener) => {\n\t\t\t\tif (record.settled || this.closed) return () => {};\n\t\t\t\tactive.modeListeners.add(listener);\n\t\t\t\treturn () => {\n\t\t\t\t\tactive.modeListeners.delete(listener);\n\t\t\t\t};\n\t\t\t},\n\t\t\trequestCancel: () => this.cancel(record),\n\t\t\taccept: () => {\n\t\t\t\tif (record.settled || active.accepted || this.closed || active.controller.signal.aborted) return;\n\t\t\t\tactive.accepted = true;\n\t\t\t\tif (task.status === \"queued\") task.status = \"running\";\n\t\t\t\tchanged(record);\n\t\t\t\tif (active.detachRequested) active.removeParent();\n\t\t\t\t// Let an already available final result win over a handoff.\n\t\t\t\tqueueMicrotask(() => queueMicrotask(active.handoff));\n\t\t\t\tthis.emit();\n\t\t\t},\n\t\t\tpublish: (result) => {\n\t\t\t\tif (record.settled || this.closed) return;\n\t\t\t\tretainResult(task, result);\n\t\t\t\tchanged(record);\n\t\t\t\tif (result.usage !== undefined) active.publishedUsage = structuredClone(result.usage);\n\t\t\t\tif (!active.detachRequested && !active.handedOff) {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tonUpdate?.(result);\n\t\t\t\t\t} catch {\n\t\t\t\t\t\t/* UI observers cannot stop execution. */\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tthis.emit();\n\t\t\t},\n\t\t\tsetOutputPath: (path, cleanup) => {\n\t\t\t\tif (record.settled) {\n\t\t\t\t\tif (cleanup) throw new Error(\"Task execution has settled\");\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tif (record.cleanup) throw new Error(\"Managed output is already registered\");\n\t\t\t\t// Never truncate a real filesystem path into a different path.\n\t\t\t\tif (Buffer.byteLength(path) > 8192) throw new Error(\"Task output path is too large\");\n\t\t\t\trecord.cleanup = cleanup;\n\t\t\t\ttask.outputPath = path;\n\t\t\t\tchanged(record);\n\t\t\t\tthis.emit();\n\t\t\t},\n\t\t};\n\t\tconst finish = (completion: TaskCompletion<T> | undefined, error?: unknown) => {\n\t\t\tif (record.settled) return;\n\t\t\trecord.settled = true;\n\t\t\tactive.modeListeners.clear();\n\t\t\tactive.removeParent();\n\t\t\ttask.endedAt = Date.now();\n\t\t\tconst failed = completion === undefined;\n\t\t\ttask.status =\n\t\t\t\tcompletion?.status ??\n\t\t\t\t(error instanceof TaskExecutionError\n\t\t\t\t\t? error.status\n\t\t\t\t\t: active.controller.signal.aborted\n\t\t\t\t\t\t? \"cancelled\"\n\t\t\t\t\t\t: failed\n\t\t\t\t\t\t\t? \"failed\"\n\t\t\t\t\t\t\t: \"completed\");\n\t\t\tif (completion) {\n\t\t\t\tretainResult(task, completion.result);\n\t\t\t\tif (completion.error !== undefined) task.error = boundText(completion.error, 4096);\n\t\t\t\tif (completion.exitCode !== undefined) task.exitCode = completion.exitCode;\n\t\t\t}\n\t\t\tif (failed) {\n\t\t\t\ttask.error = errorText(error);\n\t\t\t\tretainResult(\n\t\t\t\t\ttask,\n\t\t\t\t\t{ content: [{ type: \"text\", text: task.error }, ...(task.result?.content ?? [])], details: undefined },\n\t\t\t\t\ttask.resultTruncated,\n\t\t\t\t);\n\t\t\t}\n\t\t\tchanged(record);\n\t\t\tlet settlementWarning: string | undefined;\n\t\t\ttry {\n\t\t\t\tthis.options.onSettled?.(\n\t\t\t\t\tsnapshotOf(record),\n\t\t\t\t\tcompletion?.usage ?? completion?.result.usage ?? active.publishedUsage,\n\t\t\t\t);\n\t\t\t} catch (accountingError) {\n\t\t\t\tconst warning = `Usage settlement failed: ${errorText(accountingError)}`;\n\t\t\t\tsettlementWarning = warning;\n\t\t\t\ttask.error = boundText([task.error, warning].filter(Boolean).join(\"\\n\"), 8192);\n\t\t\t\tretainResult(\n\t\t\t\t\ttask,\n\t\t\t\t\t{ content: [{ type: \"text\", text: warning }, ...(task.result?.content ?? [])], details: undefined },\n\t\t\t\t\ttask.resultTruncated,\n\t\t\t\t);\n\t\t\t\tchanged(record);\n\t\t\t}\n\t\t\tactive.publishedUsage = undefined;\n\t\t\t// Delivery becomes eligible only after settlement is persisted.\n\t\t\trecord.delivery = active.handedOff ? \"pending\" : \"delivered\";\n\t\t\tif (!active.handedOff) {\n\t\t\t\tif (failed) rejectCaller(error);\n\t\t\t\telse {\n\t\t\t\t\tconst { usage: _usage, ...result } = completion.result;\n\t\t\t\t\tif (settlementWarning) result.content = [{ type: \"text\", text: settlementWarning }, ...result.content];\n\t\t\t\t\tresolveCaller({ kind: \"result\", result, status: task.status, error: task.error });\n\t\t\t\t}\n\t\t\t}\n\t\t\tfor (const waiter of [...record.waiters]) waiter();\n\t\t\tresolveDone();\n\t\t\tthis.executions.delete(task.id);\n\t\t\tthis.store.trim();\n\t\t\tthis.emit();\n\t\t};\n\t\t// The rejection handler is installed immediately, including for synchronous preflight throws.\n\t\ttry {\n\t\t\tconst running = execution.run(control);\n\t\t\tvoid Promise.resolve(running).then(\n\t\t\t\t(result) => finish(result),\n\t\t\t\t(error: unknown) => finish(undefined, error),\n\t\t\t);\n\t\t} catch (error) {\n\t\t\tfinish(undefined, error);\n\t\t}\n\t\tthis.emit();\n\t\treturn caller;\n\t}\n\n\tprivate detachable(record: TaskRecord): boolean {\n\t\tconst active = this.executions.get(record.task.id);\n\t\treturn !!active && !record.settled && !active.detachRequested && !active.controller.signal.aborted;\n\t}\n\n\tdetachForeground(): number {\n\t\tif (!this.enabled) return 0;\n\t\tconst eligible = [...this.store.records.values()]\n\t\t\t.filter((record) => this.detachable(record))\n\t\t\t.sort((left, right) => left.task.startedAt - right.task.startedAt);\n\t\tif (!eligible.length) return 0;\n\t\tconst free = this.maxActive - this.backgroundActive();\n\t\tif (free <= 0) throw this.limitError();\n\t\tconst records = eligible.slice(0, free);\n\t\tfor (const record of records) this.prepareDetach(record);\n\t\tfor (const record of records) this.finishDetach(record);\n\t\tthis.emit();\n\t\treturn records.length;\n\t}\n\n\tcanDetach(id: string): boolean {\n\t\tconst record = this.lookup(id);\n\t\treturn this.enabled && this.backgroundActive() < this.maxActive && this.detachable(record);\n\t}\n\n\tdetach(id: string): boolean {\n\t\tconst record = this.lookup(id);\n\t\tif (!this.enabled || !this.detachable(record)) return false;\n\t\tif (this.backgroundActive() >= this.maxActive) throw this.limitError();\n\t\tthis.prepareDetach(record);\n\t\tthis.finishDetach(record);\n\t\tthis.emit();\n\t\treturn true;\n\t}\n\n\tprivate prepareDetach(record: TaskRecord): void {\n\t\tconst active = this.executions.get(record.task.id)!;\n\t\tactive.detachRequested = true;\n\t\trecord.task.mode = \"background\";\n\t\tchanged(record);\n\t\tif (active.accepted) active.removeParent();\n\t}\n\n\tprivate finishDetach(record: TaskRecord): void {\n\t\tconst active = this.executions.get(record.task.id)!;\n\t\tactive.handoff();\n\t\tfor (const listener of active.modeListeners) {\n\t\t\ttry {\n\t\t\t\tlistener(record.task.mode);\n\t\t\t} catch {\n\t\t\t\t/* Executors own their diagnostics. */\n\t\t\t}\n\t\t}\n\t}\n\n\tlist(): TaskSnapshot[] {\n\t\treturn [...this.store.records.values()].filter((record) => record.visible).map(snapshotOf);\n\t}\n\n\tprivate lookup(id: string): TaskRecord {\n\t\tconst exact = this.store.records.get(id);\n\t\tif (exact) return exact;\n\t\tconst matches = [...this.store.records.values()].filter(\n\t\t\t({ task }) => task.id.startsWith(id) || task.id.slice(task.kind.length + 1).startsWith(id),\n\t\t);\n\t\tif (!id || matches.length !== 1) {\n\t\t\tthrow new TaskLookupError(matches.length > 1 ? \"ambiguous\" : \"unknown\", matches.map(snapshotOf));\n\t\t}\n\t\treturn matches[0]!;\n\t}\n\n\tget(id: string): TaskSnapshot {\n\t\treturn snapshotOf(this.lookup(id));\n\t}\n\n\tasync read(\n\t\tid: string,\n\t\toptions: { mode?: \"head\" | \"tail\"; bytes?: number; sinceBytes?: number } = {},\n\t): Promise<TaskRead> {\n\t\tconst record = this.lookup(id);\n\t\tconst release = this.retain(record.task.id);\n\t\ttry {\n\t\t\tconst task = snapshotOf(record);\n\t\t\tif (task.outputPath) {\n\t\t\t\ttry {\n\t\t\t\t\treturn { task, ...(await readOutputSlice(task.outputPath, options)) };\n\t\t\t\t} catch (error) {\n\t\t\t\t\treturn {\n\t\t\t\t\t\ttask,\n\t\t\t\t\t\treadError: boundText(`Output could not be read: ${errorText(error)}`, 4096),\n\t\t\t\t\t\t...sliceText(this.resultText(task), options),\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn { task, readError: record.readError, ...sliceText(this.resultText(task), options) };\n\t\t} finally {\n\t\t\trelease();\n\t\t}\n\t}\n\n\tprivate resultText(task: TaskSnapshot): string {\n\t\treturn boundText(\n\t\t\ttask.result?.content\n\t\t\t\t.filter((block) => block.type === \"text\")\n\t\t\t\t.map((block) => block.text)\n\t\t\t\t.join(\"\\n\") ||\n\t\t\t\ttask.error ||\n\t\t\t\t\"No output yet.\",\n\t\t);\n\t}\n\n\t/** One event-driven waiter can observe a whole waitAny cohort without per-task timers. */\n\tprivate waitForRecords(\n\t\trecords: readonly TaskRecord[],\n\t\ttimeoutMs: number,\n\t\tsignal?: AbortSignal,\n\t\tinterruptSignal?: AbortSignal,\n\t): Promise<void> {\n\t\tif (records.some((record) => record.settled) || interruptSignal?.aborted) return Promise.resolve();\n\t\treturn new Promise<void>((resolve, reject) => {\n\t\t\tlet finished = false;\n\t\t\tlet timer: ReturnType<typeof setTimeout> | undefined;\n\t\t\tconst complete = (aborted = false) => {\n\t\t\t\tif (finished) return;\n\t\t\t\tfinished = true;\n\t\t\t\tif (timer !== undefined) clearTimeout(timer);\n\t\t\t\tsignal?.removeEventListener(\"abort\", abort);\n\t\t\t\tinterruptSignal?.removeEventListener(\"abort\", interrupt);\n\t\t\t\tfor (const record of records) record.waiters.delete(wake);\n\t\t\t\tif (aborted) reject(signal?.reason ?? new Error(\"Wait aborted\"));\n\t\t\t\telse resolve();\n\t\t\t\tthis.store.trim();\n\t\t\t\tthis.emit();\n\t\t\t};\n\t\t\tconst wake = () => complete();\n\t\t\tconst abort = () => complete(true);\n\t\t\tconst interrupt = () => complete();\n\t\t\tfor (const record of records) record.waiters.add(wake);\n\t\t\tsignal?.addEventListener(\"abort\", abort, { once: true });\n\t\t\tinterruptSignal?.addEventListener(\"abort\", interrupt, { once: true });\n\t\t\ttimer = setTimeout(wake, finiteLimit(timeoutMs, TASKS_WAIT_DEFAULT_MS, TASKS_WAIT_MAX_MS));\n\t\t\tif (this.closed || interruptSignal?.aborted) wake();\n\t\t\tif (signal?.aborted) abort();\n\t\t});\n\t}\n\n\t/** Observe completion without consuming delivery; the host acknowledges only persisted tool results. */\n\tasync wait(\n\t\tid: string,\n\t\ttimeoutMs = TASKS_WAIT_DEFAULT_MS,\n\t\tsignal?: AbortSignal,\n\t\tinterruptSignal?: AbortSignal,\n\t): Promise<TaskSnapshot> {\n\t\tif (signal?.aborted) throw signal.reason ?? new Error(\"Wait aborted\");\n\t\tconst record = this.lookup(id);\n\t\tif (record.settled) return snapshotOf(record);\n\t\tawait this.waitForRecords([record], timeoutMs, signal, interruptSignal);\n\t\treturn snapshotOf(record);\n\t}\n\n\tasync waitAny(\n\t\ttimeoutMs = TASKS_WAIT_DEFAULT_MS,\n\t\tsignal?: AbortSignal,\n\t\tinterruptSignal?: AbortSignal,\n\t): Promise<TaskSnapshot | undefined> {\n\t\tif (signal?.aborted) throw signal.reason ?? new Error(\"Wait aborted\");\n\t\tconst records = [...this.store.records.values()].filter(\n\t\t\t(record) => record.visible && record.task.mode === \"background\" && !record.settled,\n\t\t);\n\t\tif (records.length === 0 || interruptSignal?.aborted) return undefined;\n\t\tawait this.waitForRecords(records, timeoutMs, signal, interruptSignal);\n\t\tconst settled = records\n\t\t\t.filter((record) => record.settled)\n\t\t\t.sort((left, right) => (left.task.endedAt ?? 0) - (right.task.endedAt ?? 0))[0];\n\t\treturn settled ? snapshotOf(settled) : undefined;\n\t}\n\n\tkill(id: string): boolean {\n\t\treturn this.cancel(this.lookup(id));\n\t}\n\n\tprivate cancel(record: TaskRecord): boolean {\n\t\tconst active = this.executions.get(record.task.id);\n\t\tif (!active || record.settled || active.controller.signal.aborted) return false;\n\t\trecord.task.status = \"stopping\";\n\t\tchanged(record);\n\t\tactive.controller.abort();\n\t\tthis.emit();\n\t\treturn true;\n\t}\n\n\tsubscribe(listener: () => void): () => void {\n\t\tif (this.closed) return () => {};\n\t\tthis.listeners.add(listener);\n\t\treturn () => {\n\t\t\tthis.listeners.delete(listener);\n\t\t};\n\t}\n\n\t/**\n\t * Retention protects snapshots and logs only. Delivery has its own explicit hold.\n\t */\n\tretain(id: string): () => void {\n\t\tconst record = this.lookup(id);\n\t\trecord.pins++;\n\t\tlet released = false;\n\t\treturn () => {\n\t\t\tif (released) return;\n\t\t\treleased = true;\n\t\t\trecord.pins--;\n\t\t\tthis.store.trim();\n\t\t\tif (!this.closed && this.pauses === 0 && this.candidate(record)) this.emit();\n\t\t};\n\t}\n\n\tholdDelivery(id: string): () => void {\n\t\tconst record = this.lookup(id);\n\t\tconst releaseRetention = this.retain(id);\n\t\trecord.deliveryHolds++;\n\t\tlet released = false;\n\t\treturn () => {\n\t\t\tif (released) return;\n\t\t\treleased = true;\n\t\t\trecord.deliveryHolds--;\n\t\t\treleaseRetention();\n\t\t};\n\t}\n\n\tpause(): () => void {\n\t\tthis.pauses++;\n\t\tlet resumed = false;\n\t\treturn () => {\n\t\t\tif (resumed) return;\n\t\t\tresumed = true;\n\t\t\tthis.pauses--;\n\t\t\tthis.emit();\n\t\t};\n\t}\n\n\tpendingNotifications(): TaskSnapshot[] {\n\t\tif (this.closed || this.pauses > 0) return [];\n\t\treturn [...this.store.records.values()].filter((record) => this.candidate(record)).map(snapshotOf);\n\t}\n\n\t/** Only explicit result-delivery holds delay an automatic completion. */\n\tprivate candidate(record: TaskRecord): boolean {\n\t\treturn record.visible && record.delivery === \"pending\" && record.waiters.size === 0 && record.deliveryHolds === 0;\n\t}\n\n\tclaimNotification(id: string): boolean {\n\t\tif (this.closed || this.pauses > 0) return false;\n\t\tconst record = this.store.records.get(id);\n\t\tif (!record || !this.candidate(record)) return false;\n\t\trecord.delivery = \"claimed\";\n\t\treturn true;\n\t}\n\n\tmarkDelivered(id: string): void {\n\t\tconst record = this.store.records.get(id);\n\t\tif (!record) return;\n\t\trecord.delivery = \"delivered\";\n\t\tthis.store.trim();\n\t}\n\n\treleaseNotification(id: string): void {\n\t\tconst record = this.store.records.get(id);\n\t\tif (!record || record.delivery !== \"claimed\") return;\n\t\trecord.delivery = \"pending\";\n\t\tthis.store.trim();\n\t\tthis.emit();\n\t}\n\n\tclose(): void {\n\t\tif (this.closed) return;\n\t\tthis._closed = true;\n\t\tthis.listeners.clear();\n\t\tfor (const record of this.store.records.values()) {\n\t\t\tthis.executions.get(record.task.id)?.removeParent();\n\t\t\tthis.cancel(record);\n\t\t\tfor (const waiter of [...record.waiters]) waiter();\n\t\t}\n\t\tthis.store.trim();\n\t}\n\n\tasync shutdown(graceMs = 2000): Promise<void> {\n\t\tthis.close();\n\t\tawait this.drain([...this.store.records.values()], graceMs);\n\t}\n\n\t/** Running tasks whose launch anchor is outside the branch made of `ancestors`. */\n\tactiveOutsideBranch(ancestors: ReadonlySet<string>): TaskSnapshot[] {\n\t\treturn [...this.store.records.values()]\n\t\t\t.filter((record) => !record.settled && record.task.anchorId !== null && !ancestors.has(record.task.anchorId))\n\t\t\t.map(snapshotOf);\n\t}\n\n\t/**\n\t * Hidden results stay pending: returning to their branch delivers them again.\n\t * Restored history is already delivered.\n\t */\n\tasync cancelOutsideBranch(ancestors: ReadonlySet<string>): Promise<void> {\n\t\tfor (const record of this.store.records.values())\n\t\t\trecord.visible = record.task.anchorId === null || ancestors.has(record.task.anchorId);\n\t\tconst outside = [...this.store.records.values()].filter((record) => !record.visible);\n\t\tfor (const record of outside) this.cancel(record);\n\t\tthis.store.trim();\n\t\tthis.emit();\n\t\tawait this.drain(outside, 2000);\n\t}\n\n\tprivate async drain(records: TaskRecord[], graceMs: number): Promise<void> {\n\t\tlet timer: ReturnType<typeof setTimeout> | undefined;\n\t\ttry {\n\t\t\tawait Promise.race([\n\t\t\t\tPromise.all(records.map((record) => this.executions.get(record.task.id)?.done)).then(() =>\n\t\t\t\t\tPromise.all(this.store.cleanups),\n\t\t\t\t),\n\t\t\t\tnew Promise<void>((resolve) => {\n\t\t\t\t\ttimer = setTimeout(resolve, finiteLimit(graceMs, 2000, 60_000));\n\t\t\t\t}),\n\t\t\t]);\n\t\t} finally {\n\t\t\tif (timer !== undefined) clearTimeout(timer);\n\t\t}\n\t}\n\n\tprivate emit(): void {\n\t\tif (this.closed) return;\n\t\tfor (const listener of [...this.listeners]) {\n\t\t\tif (this.closed) break;\n\t\t\ttry {\n\t\t\t\tlistener();\n\t\t\t} catch {\n\t\t\t\t/* Observers do not own execution or delivery. */\n\t\t\t}\n\t\t}\n\t}\n}\n"]}
1
+ {"version":3,"file":"runtime.js","sourceRoot":"","sources":["../../../src/core/tasks/runtime.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AAEzC,OAAO,EAAE,SAAS,EAAsB,SAAS,EAAE,MAAM,gBAAgB,CAAC;AAC1E,OAAO,EAAE,qBAAqB,EAAE,iBAAiB,EAAE,MAAM,aAAa,CAAC;AACvE,OAAO,EACN,UAAU,EACV,UAAU,EACV,SAAS,EACT,WAAW,EACX,eAAe,EACf,SAAS,EACT,gBAAgB,EAChB,gBAAgB,GAChB,MAAM,aAAa,CAAC;AACrB,OAAO,EAAE,aAAa,EAAE,MAAM,gBAAgB,CAAC;AAC/C,OAAO,EAAE,UAAU,EAAmB,SAAS,EAAE,MAAM,YAAY,CAAC;AACpE,OAAO,EACN,yBAAyB,EACzB,iBAAiB,EAEjB,eAAe,GAMf,MAAM,YAAY,CAAC;AAEpB,wFAAwF;AACxF,MAAM,OAAO,WAAW;IAcvB,YAAY,UAA8B,EAAE;QAZ3B,eAAU,GAAG,IAAI,GAAG,EAA8B,CAAC;QACnD,cAAS,GAAG,IAAI,aAAa,EAAE,CAAC;QAChC,cAAS,GAAG,IAAI,GAAG,EAAc,CAAC;QAO3C,YAAO,GAAG,KAAK,CAAC;QAChB,WAAM,GAAG,CAAC,CAAC;QAGlB,IAAI,CAAC,OAAO,GAAG,OAAO,CAAC;QACvB,IAAI,CAAC,iBAAiB,GAAG,OAAO,CAAC,OAAO,IAAI,KAAK,CAAC;QAClD,IAAI,CAAC,aAAa,GAAG,IAAI,CAAC,GAAG,CAAC,CAAC,EAAE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IAAI,CAAC,GAAG,IAAI,CAAC,SAAS,CAAC,EAAE,CAAC;YAC5C,IAAI,IAAI,CAAC,MAAM;gBAAE,MAAM;YACvB,IAAI,CAAC;gBACJ,QAAQ,EAAE,CAAC;YACZ,CAAC;YAAC,MAAM,CAAC;gBACR,iDAAiD;YAClD,CAAC;QACF,CAAC;IACF,CAAC;CACD","sourcesContent":["import { randomUUID } from \"node:crypto\";\nimport type { AgentToolResult } from \"@earendil-works/pi-agent-core\";\nimport { Execution, type ExecutionHost, errorText } from \"./execution.ts\";\nimport { TASKS_WAIT_DEFAULT_MS, TASKS_WAIT_MAX_MS } from \"./limits.ts\";\nimport {\n\tboundFacts,\n\tboundInput,\n\tboundText,\n\tfiniteLimit,\n\treadOutputSlice,\n\tsliceText,\n\tTASK_LABEL_BYTES,\n\tTASK_TITLE_BYTES,\n} from \"./output.ts\";\nimport { TaskScheduler } from \"./scheduler.ts\";\nimport { snapshotOf, type TaskRecord, TaskStore } from \"./store.ts\";\nimport {\n\tTASK_BACKGROUND_REJECTION,\n\tTASK_KIND_PATTERN,\n\ttype TaskExecution,\n\tTaskLookupError,\n\ttype TaskRead,\n\ttype TaskRuntimeOptions,\n\ttype TaskSnapshot,\n\ttype TasksContext,\n\ttype TaskToolOutcome,\n} from \"./types.ts\";\n\n/** Session-local supervision. Executors own their processes, items and output files. */\nexport class TaskRuntime implements TasksContext {\n\tprivate readonly store: TaskStore;\n\tprivate readonly executions = new Map<string, Execution<unknown>>();\n\tprivate readonly scheduler = new TaskScheduler();\n\tprivate readonly listeners = new Set<() => void>();\n\tprivate readonly host: ExecutionHost;\n\tprivate readonly maxBackground: number;\n\tprivate readonly maxHistory: number;\n\tprivate readonly maxRetained: number;\n\tprivate readonly options: TaskRuntimeOptions;\n\tprivate configuredEnabled: boolean;\n\tprivate _closed = false;\n\tprivate pauses = 0;\n\n\tconstructor(options: TaskRuntimeOptions = {}) {\n\t\tthis.options = options;\n\t\tthis.configuredEnabled = options.enabled ?? false;\n\t\tthis.maxBackground = Math.max(1, finiteLimit(options.maxBackground, 8, 128));\n\t\tthis.maxHistory = finiteLimit(options.maxHistory, 32, 1024);\n\t\t// Separate foreground and background histories, plus the protected-record allowance.\n\t\tthis.maxRetained = this.maxBackground + 2 * Math.max(1, this.maxHistory) + this.maxHistory;\n\t\tthis.store = new TaskStore(this.maxHistory, this.maxRetained, () => this.closed, options.onCleanupError);\n\t\tconst runtime = this;\n\t\tthis.host = {\n\t\t\tget closed() {\n\t\t\t\treturn runtime.closed;\n\t\t\t},\n\t\t\temit: () => this.emit(),\n\t\t\tsettle: (task, usage) => this.options.onSettled?.(task, usage),\n\t\t\treleased: (execution) => {\n\t\t\t\tthis.executions.delete(execution.task.id);\n\t\t\t\tthis.scheduler.release(execution);\n\t\t\t\tthis.store.trim();\n\t\t\t\tthis.emit();\n\t\t\t},\n\t\t};\n\t}\n\n\tget closed(): boolean {\n\t\treturn this._closed;\n\t}\n\n\tget session(): TaskRuntimeOptions[\"session\"] {\n\t\treturn this.options.session;\n\t}\n\n\t/**\n\t * Rehydrate terminal snapshots only, newest endedAt in each history (later input wins\n\t * ties). Existing runtime records win ID collisions. No execution, accounting,\n\t * notification, or deletion ownership is restored. Foreground records take their output\n\t * from the branch's tool results. The host supplies the current branch; closed services\n\t * ignore restoration.\n\t */\n\trestoreHistory(\n\t\trecords: readonly unknown[],\n\t\ttoolResults?: ReadonlyMap<string, AgentToolResult<unknown>[\"content\"]>,\n\t): void {\n\t\tthis.store.restoreHistory(records, toolResults);\n\t}\n\n\tget enabled(): boolean {\n\t\treturn this.configuredEnabled && !this.closed && this.options.backgroundAllowed !== false;\n\t}\n\n\tsetEnabled(enabled: boolean): void {\n\t\tthis.configuredEnabled = enabled;\n\t\tthis.emit();\n\t}\n\n\t/** Foreground work is bounded by its caller; only background work, queued or running, holds a slot. */\n\tprivate backgroundActive(): number {\n\t\tlet count = 0;\n\t\tfor (const record of this.store.records.values())\n\t\t\tif (!record.settled && record.task.mode === \"background\") count++;\n\t\treturn count;\n\t}\n\n\tprivate limitError(): Error {\n\t\treturn new Error(\n\t\t\t`Background task limit reached (${this.maxBackground}); stop or wait for a background task, or run in the foreground.`,\n\t\t);\n\t}\n\n\tasync execute<T>(execution: TaskExecution<T>): Promise<TaskToolOutcome<T>> {\n\t\t// Admission and registration happen synchronously, before invoking user code or awaiting anything.\n\t\tif (execution.background && this.options.backgroundAllowed === false) throw new Error(TASK_BACKGROUND_REJECTION);\n\t\tif (this.closed) throw new Error(\"Task service is closed\");\n\t\tif (execution.background) {\n\t\t\tif (!this.enabled) throw new Error(\"Background execution is not available in this host\");\n\t\t\tif (this.backgroundActive() >= this.maxBackground) throw this.limitError();\n\t\t\tif (this.store.records.size + this.store.cleanups.size >= this.maxRetained) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t\"Task history retention limit reached; deliver pending notifications or release pinned or claimed records\",\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t\tif (execution.signal?.aborted) throw execution.signal.reason ?? new Error(\"Execution aborted\");\n\t\tif (!TASK_KIND_PATTERN.test(execution.kind)) throw new Error(\"Invalid task source\");\n\t\tconst concurrency = execution.concurrency;\n\t\tif (concurrency && (!concurrency.key || !Number.isSafeInteger(concurrency.limit) || concurrency.limit < 1))\n\t\t\tthrow new Error(\"Invalid task concurrency\");\n\t\tconst anchorId = this.options.anchor?.() ?? null;\n\t\tif (anchorId !== null && Buffer.byteLength(anchorId) > 8192) throw new Error(\"Task branch anchor is too large\");\n\t\tconst task: TaskSnapshot = {\n\t\t\tid: `${execution.kind}-${randomUUID()}`,\n\t\t\tkind: execution.kind,\n\t\t\tlabel: boundText(execution.label ?? execution.kind, TASK_LABEL_BYTES),\n\t\t\ttitle: boundText(execution.title, TASK_TITLE_BYTES),\n\t\t\toutput: execution.output ?? \"log\",\n\t\t\t...(execution.input ? { input: boundInput(execution.input) } : {}),\n\t\t\t...(execution.facts?.length ? { facts: boundFacts(execution.facts) } : {}),\n\t\t\ttoolCallId: boundText(execution.toolCallId, 512),\n\t\t\tanchorId,\n\t\t\tmode: execution.background ? \"background\" : \"foreground\",\n\t\t\tstatus: \"queued\",\n\t\t\tstartedAt: Date.now(),\n\t\t};\n\t\tconst record: TaskRecord = {\n\t\t\ttask,\n\t\t\tsettled: false,\n\t\t\tvisible: true,\n\t\t\tdelivery: \"none\",\n\t\t\tpins: 0,\n\t\t\tdeliveryHolds: 0,\n\t\t\twaiters: new Set(),\n\t\t};\n\t\tconst active = new Execution(this.host, record, execution);\n\t\tthis.store.records.set(task.id, record);\n\t\tthis.executions.set(task.id, active as Execution<unknown>);\n\t\tthis.scheduler.schedule(active);\n\t\t// Queued background work returns at once; started work hands off after its own accept().\n\t\tif (active.queued) active.handoff();\n\t\tthis.emit();\n\t\treturn active.caller;\n\t}\n\n\tprivate detachable(record: TaskRecord): boolean {\n\t\treturn this.executions.get(record.task.id)?.detachable ?? false;\n\t}\n\n\tdetachForeground(): number {\n\t\tif (!this.enabled) return 0;\n\t\tconst eligible = [...this.store.records.values()]\n\t\t\t.filter((record) => this.detachable(record))\n\t\t\t.sort((left, right) => left.task.startedAt - right.task.startedAt);\n\t\tif (!eligible.length) return 0;\n\t\tconst free = this.maxBackground - this.backgroundActive();\n\t\tif (free <= 0) throw this.limitError();\n\t\tconst executions = eligible.slice(0, free).map((record) => this.executions.get(record.task.id)!);\n\t\tfor (const execution of executions) execution.requestDetach();\n\t\tfor (const execution of executions) execution.completeDetach();\n\t\tthis.emit();\n\t\treturn executions.length;\n\t}\n\n\tcanDetach(id: string): boolean {\n\t\tconst record = this.lookup(id);\n\t\treturn this.enabled && this.backgroundActive() < this.maxBackground && this.detachable(record);\n\t}\n\n\tdetach(id: string): boolean {\n\t\tconst record = this.lookup(id);\n\t\tif (!this.enabled || !this.detachable(record)) return false;\n\t\tif (this.backgroundActive() >= this.maxBackground) throw this.limitError();\n\t\tconst execution = this.executions.get(record.task.id)!;\n\t\texecution.requestDetach();\n\t\texecution.completeDetach();\n\t\tthis.emit();\n\t\treturn true;\n\t}\n\n\tlist(): TaskSnapshot[] {\n\t\treturn [...this.store.records.values()].filter((record) => record.visible).map(snapshotOf);\n\t}\n\n\tprivate lookup(id: string): TaskRecord {\n\t\tconst exact = this.store.records.get(id);\n\t\tif (exact) return exact;\n\t\tconst matches = [...this.store.records.values()].filter(\n\t\t\t({ task }) => task.id.startsWith(id) || task.id.slice(task.kind.length + 1).startsWith(id),\n\t\t);\n\t\tif (!id || matches.length !== 1) {\n\t\t\tthrow new TaskLookupError(matches.length > 1 ? \"ambiguous\" : \"unknown\", matches.map(snapshotOf));\n\t\t}\n\t\treturn matches[0]!;\n\t}\n\n\tget(id: string): TaskSnapshot {\n\t\treturn snapshotOf(this.lookup(id));\n\t}\n\n\tasync read(\n\t\tid: string,\n\t\toptions: { mode?: \"head\" | \"tail\"; bytes?: number; sinceBytes?: number } = {},\n\t): Promise<TaskRead> {\n\t\tconst record = this.lookup(id);\n\t\tconst release = this.retain(record.task.id);\n\t\ttry {\n\t\t\tconst task = snapshotOf(record);\n\t\t\tif (task.outputPath) {\n\t\t\t\ttry {\n\t\t\t\t\treturn { task, ...(await readOutputSlice(task.outputPath, options)) };\n\t\t\t\t} catch (error) {\n\t\t\t\t\treturn {\n\t\t\t\t\t\ttask,\n\t\t\t\t\t\treadError: boundText(`Output could not be read: ${errorText(error)}`, 4096),\n\t\t\t\t\t\t...sliceText(this.resultText(task), options),\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn { task, readError: record.readError, ...sliceText(this.resultText(task), options) };\n\t\t} finally {\n\t\t\trelease();\n\t\t}\n\t}\n\n\tprivate resultText(task: TaskSnapshot): string {\n\t\treturn task.result?.text || task.error || \"No output yet.\";\n\t}\n\n\t/** One event-driven waiter can observe a whole waitAny cohort without per-task timers. */\n\tprivate waitForRecords(\n\t\trecords: readonly TaskRecord[],\n\t\ttimeoutMs: number,\n\t\tsignal?: AbortSignal,\n\t\tinterruptSignal?: AbortSignal,\n\t): Promise<void> {\n\t\tif (records.some((record) => record.settled) || interruptSignal?.aborted) return Promise.resolve();\n\t\treturn new Promise<void>((resolve, reject) => {\n\t\t\tlet finished = false;\n\t\t\tlet timer: ReturnType<typeof setTimeout> | undefined;\n\t\t\tconst complete = (aborted = false) => {\n\t\t\t\tif (finished) return;\n\t\t\t\tfinished = true;\n\t\t\t\tif (timer !== undefined) clearTimeout(timer);\n\t\t\t\tsignal?.removeEventListener(\"abort\", abort);\n\t\t\t\tinterruptSignal?.removeEventListener(\"abort\", interrupt);\n\t\t\t\tfor (const record of records) record.waiters.delete(wake);\n\t\t\t\tif (aborted) reject(signal?.reason ?? new Error(\"Wait aborted\"));\n\t\t\t\telse resolve();\n\t\t\t\tthis.store.trim();\n\t\t\t\tthis.emit();\n\t\t\t};\n\t\t\tconst wake = () => complete();\n\t\t\tconst abort = () => complete(true);\n\t\t\tconst interrupt = () => complete();\n\t\t\tfor (const record of records) record.waiters.add(wake);\n\t\t\tsignal?.addEventListener(\"abort\", abort, { once: true });\n\t\t\tinterruptSignal?.addEventListener(\"abort\", interrupt, { once: true });\n\t\t\ttimer = setTimeout(wake, finiteLimit(timeoutMs, TASKS_WAIT_DEFAULT_MS, TASKS_WAIT_MAX_MS));\n\t\t\tif (this.closed || interruptSignal?.aborted) wake();\n\t\t\tif (signal?.aborted) abort();\n\t\t});\n\t}\n\n\t/** Observe completion without consuming delivery; the host acknowledges only persisted tool results. */\n\tasync wait(\n\t\tid: string,\n\t\ttimeoutMs = TASKS_WAIT_DEFAULT_MS,\n\t\tsignal?: AbortSignal,\n\t\tinterruptSignal?: AbortSignal,\n\t): Promise<TaskSnapshot> {\n\t\tif (signal?.aborted) throw signal.reason ?? new Error(\"Wait aborted\");\n\t\tconst record = this.lookup(id);\n\t\tif (record.settled) return snapshotOf(record);\n\t\tawait this.waitForRecords([record], timeoutMs, signal, interruptSignal);\n\t\treturn snapshotOf(record);\n\t}\n\n\tasync waitAny(\n\t\ttimeoutMs = TASKS_WAIT_DEFAULT_MS,\n\t\tsignal?: AbortSignal,\n\t\tinterruptSignal?: AbortSignal,\n\t): Promise<TaskSnapshot | undefined> {\n\t\tif (signal?.aborted) throw signal.reason ?? new Error(\"Wait aborted\");\n\t\tconst records = [...this.store.records.values()].filter(\n\t\t\t(record) => record.visible && record.task.mode === \"background\" && !record.settled,\n\t\t);\n\t\tif (records.length === 0 || interruptSignal?.aborted) return undefined;\n\t\tawait this.waitForRecords(records, timeoutMs, signal, interruptSignal);\n\t\tconst settled = records\n\t\t\t.filter((record) => record.settled)\n\t\t\t.sort((left, right) => (left.task.endedAt ?? 0) - (right.task.endedAt ?? 0))[0];\n\t\treturn settled ? snapshotOf(settled) : undefined;\n\t}\n\n\tkill(id: string): boolean {\n\t\treturn this.cancel(this.lookup(id));\n\t}\n\n\tprivate cancel(record: TaskRecord): boolean {\n\t\treturn this.executions.get(record.task.id)?.cancel() ?? false;\n\t}\n\n\tsubscribe(listener: () => void): () => void {\n\t\tif (this.closed) return () => {};\n\t\tthis.listeners.add(listener);\n\t\treturn () => {\n\t\t\tthis.listeners.delete(listener);\n\t\t};\n\t}\n\n\t/**\n\t * Retention protects snapshots and logs only. Delivery has its own explicit hold.\n\t */\n\tretain(id: string): () => void {\n\t\tconst record = this.lookup(id);\n\t\trecord.pins++;\n\t\tlet released = false;\n\t\treturn () => {\n\t\t\tif (released) return;\n\t\t\treleased = true;\n\t\t\trecord.pins--;\n\t\t\tthis.store.trim();\n\t\t\tif (!this.closed && this.pauses === 0 && this.candidate(record)) this.emit();\n\t\t};\n\t}\n\n\tholdDelivery(id: string): () => void {\n\t\tconst record = this.lookup(id);\n\t\tconst releaseRetention = this.retain(id);\n\t\trecord.deliveryHolds++;\n\t\tlet released = false;\n\t\treturn () => {\n\t\t\tif (released) return;\n\t\t\treleased = true;\n\t\t\trecord.deliveryHolds--;\n\t\t\treleaseRetention();\n\t\t};\n\t}\n\n\tpause(): () => void {\n\t\tthis.pauses++;\n\t\tlet resumed = false;\n\t\treturn () => {\n\t\t\tif (resumed) return;\n\t\t\tresumed = true;\n\t\t\tthis.pauses--;\n\t\t\tthis.emit();\n\t\t};\n\t}\n\n\tpendingNotifications(): TaskSnapshot[] {\n\t\tif (this.closed || this.pauses > 0) return [];\n\t\treturn [...this.store.records.values()].filter((record) => this.candidate(record)).map(snapshotOf);\n\t}\n\n\t/** Only explicit result-delivery holds delay an automatic completion. */\n\tprivate candidate(record: TaskRecord): boolean {\n\t\treturn record.visible && record.delivery === \"pending\" && record.waiters.size === 0 && record.deliveryHolds === 0;\n\t}\n\n\tclaimNotification(id: string): boolean {\n\t\tif (this.closed || this.pauses > 0) return false;\n\t\tconst record = this.store.records.get(id);\n\t\tif (!record || !this.candidate(record)) return false;\n\t\trecord.delivery = \"claimed\";\n\t\treturn true;\n\t}\n\n\tmarkDelivered(id: string): void {\n\t\tconst record = this.store.records.get(id);\n\t\tif (!record) return;\n\t\trecord.delivery = \"delivered\";\n\t\tthis.store.trim();\n\t}\n\n\treleaseNotification(id: string): void {\n\t\tconst record = this.store.records.get(id);\n\t\tif (!record || record.delivery !== \"claimed\") return;\n\t\trecord.delivery = \"pending\";\n\t\tthis.store.trim();\n\t\tthis.emit();\n\t}\n\n\tclose(): void {\n\t\tif (this.closed) return;\n\t\tthis._closed = true;\n\t\tthis.listeners.clear();\n\t\tfor (const record of this.store.records.values()) {\n\t\t\tthis.executions.get(record.task.id)?.releaseParent();\n\t\t\tthis.cancel(record);\n\t\t\tfor (const waiter of [...record.waiters]) waiter();\n\t\t}\n\t\tthis.store.trim();\n\t}\n\n\tasync shutdown(graceMs = 2000): Promise<void> {\n\t\tthis.close();\n\t\tawait this.drain([...this.store.records.values()], graceMs);\n\t}\n\n\t/** Running tasks whose launch anchor is outside the branch made of `ancestors`. */\n\tactiveOutsideBranch(ancestors: ReadonlySet<string>): TaskSnapshot[] {\n\t\treturn [...this.store.records.values()]\n\t\t\t.filter((record) => !record.settled && record.task.anchorId !== null && !ancestors.has(record.task.anchorId))\n\t\t\t.map(snapshotOf);\n\t}\n\n\t/**\n\t * Hidden results stay pending: returning to their branch delivers them again.\n\t * Restored history is already delivered.\n\t */\n\tasync cancelOutsideBranch(ancestors: ReadonlySet<string>): Promise<void> {\n\t\tfor (const record of this.store.records.values())\n\t\t\trecord.visible = record.task.anchorId === null || ancestors.has(record.task.anchorId);\n\t\tconst outside = [...this.store.records.values()].filter((record) => !record.visible);\n\t\tfor (const record of outside) this.cancel(record);\n\t\tthis.store.trim();\n\t\tthis.emit();\n\t\tawait this.drain(outside, 2000);\n\t}\n\n\tprivate async drain(records: TaskRecord[], graceMs: number): Promise<void> {\n\t\tlet timer: ReturnType<typeof setTimeout> | undefined;\n\t\ttry {\n\t\t\tawait Promise.race([\n\t\t\t\tPromise.all(records.map((record) => this.executions.get(record.task.id)?.done)).then(() =>\n\t\t\t\t\tPromise.all(this.store.cleanups),\n\t\t\t\t),\n\t\t\t\tnew Promise<void>((resolve) => {\n\t\t\t\t\ttimer = setTimeout(resolve, finiteLimit(graceMs, 2000, 60_000));\n\t\t\t\t}),\n\t\t\t]);\n\t\t} finally {\n\t\t\tif (timer !== undefined) clearTimeout(timer);\n\t\t}\n\t}\n\n\tprivate emit(): void {\n\t\tif (this.closed) return;\n\t\tfor (const listener of [...this.listeners]) {\n\t\t\tif (this.closed) break;\n\t\t\ttry {\n\t\t\t\tlistener();\n\t\t\t} catch {\n\t\t\t\t/* Observers do not own execution or delivery. */\n\t\t\t}\n\t\t}\n\t}\n}\n"]}
@@ -0,0 +1,16 @@
1
+ /** Per-key concurrency lanes. Executions without a concurrency key start immediately. */
2
+ export interface Schedulable {
3
+ readonly concurrency?: {
4
+ key: string;
5
+ limit: number;
6
+ };
7
+ start(): void;
8
+ }
9
+ export declare class TaskScheduler {
10
+ private readonly lanes;
11
+ schedule(execution: Schedulable): void;
12
+ /** A settled execution frees its slot or leaves the queue; the next waiting one starts. */
13
+ release(execution: Schedulable): void;
14
+ private pump;
15
+ }
16
+ //# sourceMappingURL=scheduler.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"scheduler.d.ts","sourceRoot":"","sources":["../../../src/core/tasks/scheduler.ts"],"names":[],"mappings":"AAAA,yFAAyF;AACzF,MAAM,WAAW,WAAW;IAC3B,QAAQ,CAAC,WAAW,CAAC,EAAE;QAAE,GAAG,EAAE,MAAM,CAAC;QAAC,KAAK,EAAE,MAAM,CAAA;KAAE,CAAC;IACtD,KAAK,IAAI,IAAI,CAAC;CACd;AAOD,qBAAa,aAAa;IACzB,OAAO,CAAC,QAAQ,CAAC,KAAK,CAA2B;IAEjD,QAAQ,CAAC,SAAS,EAAE,WAAW,GAAG,IAAI;IAetC,2FAA2F;IAC3F,OAAO,CAAC,SAAS,EAAE,WAAW,GAAG,IAAI;IAUrC,OAAO,CAAC,IAAI;CASZ"}