@songtonyli/dsh-cli 0.1.50 → 0.1.52

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.
@@ -293,62 +293,6 @@ function cursorTo(row) {
293
293
  return `\u001b[${String(row + 1)};1H`;
294
294
  }
295
295
  //#endregion
296
- //#region lib/types/attach.js
297
- /**
298
- * `/attach`: read a local file and admit it into the attachment store as the
299
- * image or file block the next prompt carries, the way the browser composer
300
- * uploads a dropped file.
301
- * @module @deepseek-ai/dsh-tui-app/attach
302
- */
303
- /** Image media types by file extension; every other extension attaches as a file. */
304
- const IMAGE_MEDIA_TYPES = {
305
- ".png": "image/png",
306
- ".jpg": "image/jpeg",
307
- ".jpeg": "image/jpeg",
308
- ".webp": "image/webp",
309
- ".gif": "image/gif"
310
- };
311
- /**
312
- * Read `path` (relative to `cwd`) and store it.
313
- * @param store - the composed attachment store.
314
- * @param cwd - the directory relative paths resolve against.
315
- * @param path - the file to attach.
316
- * @returns the pending attachment.
317
- * @throws when the file cannot be read or the store rejects it.
318
- */
319
- async function attachLocalFile(store, cwd, path) {
320
- const absolute = resolve(cwd, path);
321
- const name = basename(absolute);
322
- const data = new Uint8Array(await readFile(absolute));
323
- const mediaType = IMAGE_MEDIA_TYPES[extname(absolute).toLowerCase()];
324
- if (mediaType !== void 0) {
325
- const [ref] = await store.saveImages([{
326
- data,
327
- mediaType,
328
- name
329
- }]);
330
- /* v8 ignore next -- saveImages returns one ref per input */
331
- if (ref === void 0) throw new Error(`the attachment store returned no reference for ${name}`);
332
- return {
333
- name,
334
- block: {
335
- type: "image",
336
- attachment: ref
337
- }
338
- };
339
- }
340
- return {
341
- name,
342
- block: {
343
- type: "file",
344
- attachment: await store.saveFile({
345
- data,
346
- name
347
- })
348
- }
349
- };
350
- }
351
- //#endregion
352
296
  //#region lib/types/diff.js
353
297
  /**
354
298
  * Line diff for tool cards: a longest-common-subsequence alignment of old and
@@ -972,6 +916,474 @@ function foldMarker(hidden, opens) {
972
916
  return `… ${String(hidden)} more row${hidden === 1 ? "" : "s"} · ${FOLD_KEYS[opens]}`;
973
917
  }
974
918
  //#endregion
919
+ //#region lib/types/background.js
920
+ /**
921
+ * `Ctrl+B`: move the bound Agent's running tool calls to the background.
922
+ *
923
+ * A `tools/execute` around-wrapper tracks every root call an Agent dispatches
924
+ * while a job registry is composed. Moving a call registers a `tool` job in
925
+ * `ctx.jobs` whose settlement is the tool body's own outcome, and answers the
926
+ * call at once with a result that names the job, so the turn continues while
927
+ * the body keeps running. The registry and `dsh-tool-jobs` then own the rest:
928
+ * the completion notice reaches the owning Agent, `job_output` reads the
929
+ * result, and `job_kill` stops the body through the wrapper's own signal.
930
+ *
931
+ * The registry fuses the caller's signal into every body, so stopping the
932
+ * turn that dispatched a moved call still stops that call. {@link
933
+ * ToolBackgrounder.holdStopped} keeps such a settlement from waking the Agent
934
+ * the user just stopped.
935
+ * @module @deepseek-ai/dsh-tui-app/background
936
+ */
937
+ /** The text a moved call's result opens with; the job id follows it. */
938
+ const MOVED_PREFIX = "The user moved this call to the background. It keeps running as job ";
939
+ /** Matches a moved call's result text and captures the job id. */
940
+ const MOVED_PATTERN = /^The user moved this call to the background\. It keeps running as job (\S+?)\./u;
941
+ /** Detail of a moved call that stopped because the turn that dispatched it was stopped. */
942
+ const STOPPED_WITH_TURN = "stopped with the turn that called it";
943
+ /**
944
+ * Bound of the registry wait that holds a stopped call's job: the longest
945
+ * delay a Node timer takes (2^31 - 1 ms, about 24.8 days). The wait ends when
946
+ * the job settles, which the abort that stopped the turn brings about; the
947
+ * bound only has to outlast that.
948
+ */
949
+ const HOLD_WAIT_MS = 2147483647;
950
+ /**
951
+ * The model-facing result of a call the user moved to the background.
952
+ * @param id - the job that took the call over.
953
+ * @returns the result text: the job id, how its outcome arrives, and how to stop it.
954
+ */
955
+ function movedResultText(id) {
956
+ return `${MOVED_PREFIX}${id}. You are notified when it finishes; read its result with job_output, or stop it with job_kill. Continue with steps that do not depend on it.`;
957
+ }
958
+ /**
959
+ * The job a moved call's logged result names, so a replayed log draws the
960
+ * card the live session drew.
961
+ * @param content - the logged result content.
962
+ * @returns the job id, or undefined for every other result.
963
+ */
964
+ function movedJobId(content) {
965
+ const first = content[0];
966
+ if (content.length !== 1 || first?.type !== "text") return void 0;
967
+ return MOVED_PATTERN.exec(first.text)?.[1];
968
+ }
969
+ /**
970
+ * The text of a tool result as a job result: text blocks as they are, and a
971
+ * placeholder naming each other block, which a string result cannot carry.
972
+ * @param content - the result content.
973
+ * @returns the joined text.
974
+ */
975
+ function resultText(content) {
976
+ return content.map((block) => block.type === "text" ? block.text : `[${block.type} omitted]`).join("\n");
977
+ }
978
+ /**
979
+ * Tracks root tool calls and moves them to the job registry on request.
980
+ * One instance serves one terminal application.
981
+ */
982
+ var ToolBackgrounder = class {
983
+ options;
984
+ /** Tracked calls whose body has not settled, in dispatch order. */
985
+ calls = /* @__PURE__ */ new Map();
986
+ /** Jobs a body registered for itself while it ran, for as long as the body runs. */
987
+ innerJobs = /* @__PURE__ */ new Set();
988
+ /** The job a moved call's body registered for itself, by the moved call's job. */
989
+ outputs = /* @__PURE__ */ new Map();
990
+ constructor(options) {
991
+ this.options = options;
992
+ }
993
+ /**
994
+ * The `tools/execute` listener body. A nested call, a call without an
995
+ * Agent, and every call while no registry is composed pass straight
996
+ * through. A tracked call returns the body's own outcome, or the moved
997
+ * result as soon as {@link moveAll} hands it to the registry.
998
+ * @param exec - the call about to dispatch.
999
+ * @param next - the rest of the around-dispatch chain and the body.
1000
+ * @returns the call's outcome.
1001
+ */
1002
+ async around(exec, next) {
1003
+ const agent = exec.agent;
1004
+ if (agent === void 0 || exec.parent !== void 0 || this.options.jobs() === void 0) return next();
1005
+ keepSignalWritable(exec);
1006
+ const outer = exec.signal;
1007
+ const stop = new AbortController();
1008
+ exec.signal = AbortSignal.any([outer, stop.signal]);
1009
+ const moved = Promise.withResolvers();
1010
+ const settled = Promise.withResolvers();
1011
+ const body = settled.promise;
1012
+ const call = {
1013
+ callId: exec.callId,
1014
+ name: exec.name,
1015
+ agent,
1016
+ arguments: exec.arguments,
1017
+ outer,
1018
+ stop,
1019
+ body,
1020
+ answer: moved.resolve
1021
+ };
1022
+ this.calls.set(call.callId, call);
1023
+ this.options.changed();
1024
+ (async () => next())().then(settled.resolve, settled.reject);
1025
+ const restore = () => {
1026
+ exec.signal = outer;
1027
+ this.calls.delete(call.callId);
1028
+ if (call.inner !== void 0) this.innerJobs.delete(call.inner);
1029
+ this.options.changed();
1030
+ };
1031
+ body.then(restore, restore);
1032
+ return Promise.race([body, moved.promise]);
1033
+ }
1034
+ /**
1035
+ * The calls of one Agent still running in the foreground.
1036
+ * @param agent - the Agent whose calls to list.
1037
+ * @returns the calls in dispatch order.
1038
+ */
1039
+ running(agent) {
1040
+ return this.foreground(agent);
1041
+ }
1042
+ /**
1043
+ * Move every foreground call of one Agent to the registry. A call the
1044
+ * registry refuses keeps running in the foreground.
1045
+ * @param jobs - the composed job registry.
1046
+ * @param agent - the Agent whose calls to move.
1047
+ * @param label - the one-line job label for a call.
1048
+ * @returns the moved calls and the refusals.
1049
+ */
1050
+ moveAll(jobs, agent, label) {
1051
+ const report = {
1052
+ moved: [],
1053
+ refused: []
1054
+ };
1055
+ for (const call of this.foreground(agent)) {
1056
+ let id;
1057
+ try {
1058
+ id = jobs.start({
1059
+ kind: "tool",
1060
+ label: label(call),
1061
+ owner: agent.id,
1062
+ run: (handle) => ({
1063
+ cancel: (reason) => {
1064
+ call.stop.abort(reason);
1065
+ },
1066
+ done: call.body.then((result) => this.outcome(call, handle, result), (error) => ({
1067
+ status: "failed",
1068
+ detail: describeFailure(error)
1069
+ }))
1070
+ })
1071
+ });
1072
+ } catch (error) {
1073
+ report.refused.push(`${call.name}: ${describeFailure(error)}`);
1074
+ continue;
1075
+ }
1076
+ call.job = id;
1077
+ if (call.inner !== void 0) this.outputs.set(id, call.inner);
1078
+ const text = movedResultText(id);
1079
+ call.answer({
1080
+ isError: true,
1081
+ error: { message: text },
1082
+ content: [{
1083
+ type: "text",
1084
+ text
1085
+ }]
1086
+ });
1087
+ report.moved.push({
1088
+ callId: call.callId,
1089
+ name: call.name,
1090
+ id
1091
+ });
1092
+ }
1093
+ if (report.moved.length > 0) this.options.changed();
1094
+ return report;
1095
+ }
1096
+ /**
1097
+ * Keep the jobs of moved calls whose dispatching turn was just stopped from
1098
+ * waking their Agent: a live registry wait makes their settlement count as
1099
+ * delivered, so `dsh-tool-jobs` sends no completion notice. Call it right
1100
+ * after cancelling the Agent, before the bodies observe the abort.
1101
+ * @param jobs - the composed job registry.
1102
+ * @param agent - the Agent whose turn was stopped.
1103
+ * @returns how many moved calls stop with the turn.
1104
+ */
1105
+ holdStopped(jobs, agent) {
1106
+ let held = 0;
1107
+ for (const call of this.calls.values()) {
1108
+ if (call.agent !== agent || call.job === void 0 || !call.outer.aborted) continue;
1109
+ held += 1;
1110
+ jobs.wait(call.job, HOLD_WAIT_MS, agent.id).catch(ignoreGone);
1111
+ }
1112
+ return held;
1113
+ }
1114
+ /**
1115
+ * Follow one registry event. A job registered while a tracked body of the
1116
+ * same owner runs, of the body's own tool kind and with its command as the
1117
+ * label when it has one, is that body's own job, which is not background
1118
+ * work of its own. A removed job is no longer anyone's output.
1119
+ * @param event - the registry event.
1120
+ */
1121
+ observe(event) {
1122
+ if (event.type === "removed") {
1123
+ const removed = event.job.id;
1124
+ this.outputs = new Map([...this.outputs].filter(([, inner]) => inner !== removed));
1125
+ return;
1126
+ }
1127
+ if (event.type !== "registered") return;
1128
+ const { job } = event;
1129
+ const call = [...this.calls.values()].find((candidate) => candidate.inner === void 0 && candidate.agent.id === job.owner && candidate.name === job.kind && (commandOf(candidate.arguments) ?? job.label) === job.label);
1130
+ if (call === void 0) return;
1131
+ call.inner = job.id;
1132
+ this.innerJobs.add(job.id);
1133
+ if (call.job !== void 0) this.outputs.set(call.job, job.id);
1134
+ }
1135
+ /**
1136
+ * Whether a job is a tracked body's own, which the terminal does not list
1137
+ * as background work while that body runs.
1138
+ * @param id - the job to test.
1139
+ * @returns true while the body that registered it runs.
1140
+ */
1141
+ isInner(id) {
1142
+ return this.innerJobs.has(id);
1143
+ }
1144
+ /**
1145
+ * The job whose output ring shows a job's live output: the job its moved
1146
+ * body registered for itself while that job is still registered, else the
1147
+ * job itself.
1148
+ * @param id - the job the user opened.
1149
+ * @returns the job to read output from.
1150
+ */
1151
+ outputOf(id) {
1152
+ return this.outputs.get(id) ?? id;
1153
+ }
1154
+ /**
1155
+ * The tracked calls of one Agent not yet moved.
1156
+ * @param agent - the Agent whose calls to list.
1157
+ * @returns the calls in dispatch order.
1158
+ */
1159
+ foreground(agent) {
1160
+ return [...this.calls.values()].filter((call) => call.agent === agent && call.job === void 0);
1161
+ }
1162
+ /**
1163
+ * The terminal outcome of a moved call. The result text also goes on the
1164
+ * ring's `log` channel, which observers read and the model's own read skips.
1165
+ * @param call - the moved call.
1166
+ * @param handle - the job's producer face.
1167
+ * @param result - the body's normalized outcome.
1168
+ * @returns the job outcome.
1169
+ */
1170
+ outcome(call, handle, result) {
1171
+ const text = resultText(result.content);
1172
+ if (text !== "") handle.append(text, { channel: "log" });
1173
+ if (!result.isError) return {
1174
+ status: "completed",
1175
+ ...text === "" ? {} : { result: text }
1176
+ };
1177
+ if (call.stop.signal.aborted) return { status: "killed" };
1178
+ if (call.outer.aborted) return {
1179
+ status: "killed",
1180
+ detail: STOPPED_WITH_TURN
1181
+ };
1182
+ return {
1183
+ status: "failed",
1184
+ detail: result.error.message.replace(/\n[\s\S]*$/u, ""),
1185
+ result: text
1186
+ };
1187
+ }
1188
+ };
1189
+ /**
1190
+ * Replace the execution's `signal` data property with an accessor pair over
1191
+ * the same value. The registry freezes the execution when the call's result
1192
+ * commits, which makes a data property read-only; a moved body is still
1193
+ * running then, and both this wrapper and the registry restore the signal
1194
+ * when it settles. An accessor keeps those writes legal after the freeze.
1195
+ * @param exec - the call about to dispatch.
1196
+ */
1197
+ function keepSignalWritable(exec) {
1198
+ let current = exec.signal;
1199
+ Object.defineProperty(exec, "signal", {
1200
+ get: () => current,
1201
+ set: (signal) => {
1202
+ current = signal;
1203
+ },
1204
+ enumerable: true
1205
+ });
1206
+ }
1207
+ /**
1208
+ * The `command` argument of a shell-style call.
1209
+ * @param args - the call's parsed arguments.
1210
+ * @returns the command, or undefined when the arguments carry none.
1211
+ */
1212
+ function commandOf(args) {
1213
+ if (typeof args !== "object" || args === null || !("command" in args)) return void 0;
1214
+ return typeof args.command === "string" ? args.command : void 0;
1215
+ }
1216
+ /**
1217
+ * Drop the rejection of a hold's registry wait. A wait on a live job its
1218
+ * owner holds rejects only once the job left the registry, and then nothing
1219
+ * is left to hold.
1220
+ * @param _gone - the rejection.
1221
+ */
1222
+ /* v8 ignore next -- a live owned job settles before it can leave the registry */
1223
+ function ignoreGone(_gone) {}
1224
+ /** What separates two facts on one line. */
1225
+ const SEPARATOR$5 = " · ";
1226
+ /** The key the running spinner names while a foreground call can be moved. */
1227
+ const BACKGROUND_KEY_HINT = "Ctrl+B background";
1228
+ /** What the `/jobs` picker says between its heading and its rows. */
1229
+ const JOBS_PICKER_HINT = "Enter shows the output · Ctrl+K stops the highlighted job";
1230
+ /**
1231
+ * Whether a job is still running or stopping.
1232
+ * @param job - the job.
1233
+ * @returns true until the job settles.
1234
+ */
1235
+ function isLive(job) {
1236
+ return job.status === "running" || job.status === "stopping";
1237
+ }
1238
+ /**
1239
+ * How long a job has run: until now while live, until it settled otherwise.
1240
+ * @param job - the job.
1241
+ * @param now - the wall clock.
1242
+ * @returns the formatted elapsed time.
1243
+ */
1244
+ function jobElapsed(job, now) {
1245
+ return formatElapsed((job.finishedAt ?? now) - job.startedAt);
1246
+ }
1247
+ /**
1248
+ * The one line drawn above the editor while a background job runs: the live
1249
+ * count, each job's id, label, and elapsed time, and the command that lists
1250
+ * them, cut to the width.
1251
+ * @param jobs - the bound session's background jobs, in registration order.
1252
+ * @param render - the palette, the wall clock, and the columns the line fits.
1253
+ * @returns the dim line, or the empty string while no job runs.
1254
+ */
1255
+ function renderJobsLine(jobs, render) {
1256
+ const live = jobs.filter(isLive);
1257
+ if (live.length === 0) return "";
1258
+ const { palette } = render;
1259
+ const text = [`${String(live.length)} in background`, ...live.map((job) => `${job.id} ${oneLine(job.label)} ${jobElapsed(job, render.now)}`)].join(SEPARATOR$5);
1260
+ const tail = `${SEPARATOR$5}/jobs`;
1261
+ const room = Math.max(1, render.width - 2 - tail.length);
1262
+ return `${palette.accent("◇")} ${palette.dim(`${truncateToWidth(text, room, "…")}${tail}`)}`;
1263
+ }
1264
+ /**
1265
+ * One `/jobs` picker row.
1266
+ * @param job - the job.
1267
+ * @param now - the wall clock.
1268
+ * @returns the id as the label, and status, elapsed time, and job label as the description.
1269
+ */
1270
+ function jobChoice(job, now) {
1271
+ return {
1272
+ value: job.id,
1273
+ label: job.id,
1274
+ description: [
1275
+ job.status,
1276
+ jobElapsed(job, now),
1277
+ oneLine(job.label)
1278
+ ].join(SEPARATOR$5)
1279
+ };
1280
+ }
1281
+ /**
1282
+ * The detail page of one job: its status line, label, start, and the tail
1283
+ * of its retained output.
1284
+ * @param job - the job.
1285
+ * @param chunks - the retained output chunks, in offset order.
1286
+ * @param now - the wall clock.
1287
+ * @returns the page rows.
1288
+ */
1289
+ function jobDetailRows(job, chunks, now) {
1290
+ const rows = [
1291
+ [
1292
+ job.status,
1293
+ ...job.detail === void 0 ? [] : [job.detail],
1294
+ jobElapsed(job, now)
1295
+ ].join(SEPARATOR$5),
1296
+ job.label,
1297
+ `started ${formatTimestamp(job.startedAt)} UTC`
1298
+ ];
1299
+ if (job.progress !== void 0) rows.push(job.progress);
1300
+ const output = chunks.map((chunk) => chunk.text).join("").replace(/\n$/u, "");
1301
+ if (output === "") {
1302
+ rows.push("", isLive(job) ? "no output yet" : "no output");
1303
+ return rows;
1304
+ }
1305
+ const lines = output.split("\n");
1306
+ const kept = lines.slice(-200);
1307
+ rows.push("", kept.length < lines.length ? `output · last ${String(kept.length)} of ${String(lines.length)} lines` : "output");
1308
+ rows.push(...kept);
1309
+ return rows;
1310
+ }
1311
+ /**
1312
+ * The transient line one settlement shows.
1313
+ * @param job - the settled job.
1314
+ * @param notified - whether a completion notice goes to the Agent.
1315
+ * @returns the line.
1316
+ */
1317
+ function settledToast(job, notified) {
1318
+ const parts = [`◇ ${job.id} ${job.status}`, oneLine(job.label)];
1319
+ if (notified) parts.push("agent notified");
1320
+ return parts.join(SEPARATOR$5);
1321
+ }
1322
+ /**
1323
+ * A label on one line.
1324
+ * @param label - the job label, which a command can spread over lines.
1325
+ * @returns the label with each line break as one space.
1326
+ */
1327
+ function oneLine(label) {
1328
+ return label.replace(/\s*\n\s*/gu, " ");
1329
+ }
1330
+ //#endregion
1331
+ //#region lib/types/attach.js
1332
+ /**
1333
+ * `/attach`: read a local file and admit it into the attachment store as the
1334
+ * image or file block the next prompt carries, the way the browser composer
1335
+ * uploads a dropped file.
1336
+ * @module @deepseek-ai/dsh-tui-app/attach
1337
+ */
1338
+ /** Image media types by file extension; every other extension attaches as a file. */
1339
+ const IMAGE_MEDIA_TYPES = {
1340
+ ".png": "image/png",
1341
+ ".jpg": "image/jpeg",
1342
+ ".jpeg": "image/jpeg",
1343
+ ".webp": "image/webp",
1344
+ ".gif": "image/gif"
1345
+ };
1346
+ /**
1347
+ * Read `path` (relative to `cwd`) and store it.
1348
+ * @param store - the composed attachment store.
1349
+ * @param cwd - the directory relative paths resolve against.
1350
+ * @param path - the file to attach.
1351
+ * @returns the pending attachment.
1352
+ * @throws when the file cannot be read or the store rejects it.
1353
+ */
1354
+ async function attachLocalFile(store, cwd, path) {
1355
+ const absolute = resolve(cwd, path);
1356
+ const name = basename(absolute);
1357
+ const data = new Uint8Array(await readFile(absolute));
1358
+ const mediaType = IMAGE_MEDIA_TYPES[extname(absolute).toLowerCase()];
1359
+ if (mediaType !== void 0) {
1360
+ const [ref] = await store.saveImages([{
1361
+ data,
1362
+ mediaType,
1363
+ name
1364
+ }]);
1365
+ /* v8 ignore next -- saveImages returns one ref per input */
1366
+ if (ref === void 0) throw new Error(`the attachment store returned no reference for ${name}`);
1367
+ return {
1368
+ name,
1369
+ block: {
1370
+ type: "image",
1371
+ attachment: ref
1372
+ }
1373
+ };
1374
+ }
1375
+ return {
1376
+ name,
1377
+ block: {
1378
+ type: "file",
1379
+ attachment: await store.saveFile({
1380
+ data,
1381
+ name
1382
+ })
1383
+ }
1384
+ };
1385
+ }
1386
+ //#endregion
975
1387
  //#region lib/types/catalog.js
976
1388
  /**
977
1389
  * Terminal rows for the browser's settings, plugins, subagents, deliverables,
@@ -3871,6 +4283,19 @@ var ToolBlock = class {
3871
4283
  this.measured = false;
3872
4284
  }
3873
4285
  /**
4286
+ * Settle the card as moved to the background: the glyph takes the accent
4287
+ * colour and the body ends on `lines` instead of a result.
4288
+ * @param lines - the rows naming the job that took the call over.
4289
+ */
4290
+ setBackground(lines) {
4291
+ this.resultLines = lines;
4292
+ this.resultCode = void 0;
4293
+ this.resultDiff = void 0;
4294
+ this.status = "background";
4295
+ this.revision += 1;
4296
+ this.measured = false;
4297
+ }
4298
+ /**
3874
4299
  * Unroll the card's rows on the application's frame tick instead of drawing
3875
4300
  * them all in one frame: now, and again whenever a call or a result makes
3876
4301
  * the card grow.
@@ -4022,11 +4447,18 @@ var ToolBlock = class {
4022
4447
  }
4023
4448
  /**
4024
4449
  * The colour of this card's status glyph.
4025
- * @returns warning while running, success once done, error once failed.
4450
+ * @returns warning while running, success once done, error once failed, accent once moved to the background.
4026
4451
  */
4027
4452
  statusStyle() {
4028
4453
  const palette = this.theme.palette;
4029
- return this.status === "running" ? palette.warning : this.status === "done" ? palette.success : palette.error;
4454
+ switch (this.status) {
4455
+ case "running": return palette.warning;
4456
+ case "done": return palette.success;
4457
+ case "error": return palette.error;
4458
+ case "background": return palette.accent;
4459
+ /* v8 ignore next 2 -- closed-union exhaustiveness guard */
4460
+ default: return assertNever(this.status, "tool card status");
4461
+ }
4030
4462
  }
4031
4463
  /**
4032
4464
  * The one row a folded subagent card draws, led by the status-coloured
@@ -4048,7 +4480,7 @@ var ToolBlock = class {
4048
4480
  return truncateToWidth(`${palette.warning("◆")} ${name}${description}${meta}`, width, "…");
4049
4481
  }
4050
4482
  const started = this.status === "done" && this.resultLines[0]?.startsWith("started ") === true;
4051
- const tag = this.status === "error" ? palette.error("[failed]") : started ? palette.dim("[started]") : palette.success("[done]");
4483
+ const tag = this.status === "error" ? palette.error("[failed]") : this.status === "background" ? palette.accent("[background]") : started ? palette.dim("[started]") : palette.success("[done]");
4052
4484
  const cut = truncateToWidth(`${started ? palette.dim("◆") : this.statusStyle()("◆")} ${palette.dim(facts.description === "" ? this.toolName : facts.description)}${meta}`, Math.max(1, width - visibleWidth(tag) - 1), "…");
4053
4485
  return truncateToWidth(`${cut}${" ".repeat(Math.max(1, width - visibleWidth(cut) - visibleWidth(tag)))}${tag}`, width, "…");
4054
4486
  }
@@ -5712,6 +6144,7 @@ const KEY_LINES = {
5712
6144
  "While follow-ups wait: ↑ on an empty input edits the newest · Shift+↑ selects one",
5713
6145
  "Ctrl+O folds every tool card and context row",
5714
6146
  "Ctrl+T todos · Ctrl+P parent session · Ctrl+L redraw · ? keys",
6147
+ "Ctrl+B moves running tool calls to the background · /jobs lists them",
5715
6148
  "Esc arms the stop · Esc again stops the turn",
5716
6149
  "Ctrl+C clears the input, twice quits · Ctrl+D quits an empty input"
5717
6150
  ],
@@ -5731,8 +6164,9 @@ const OPEN = { kind: "open" };
5731
6164
  /**
5732
6165
  * What one key press means where the keyboard is.
5733
6166
  *
5734
- * `Escape`, `Ctrl+O`, `Ctrl+G`, `Ctrl+T`, `Ctrl+P`, and `Ctrl+L` mean the
5735
- * same thing everywhere and are answered first. Everything else is the region's own.
6167
+ * `Escape`, `Ctrl+O`, `Ctrl+G`, `Ctrl+B`, `Ctrl+T`, `Ctrl+P`, and `Ctrl+L`
6168
+ * mean the same thing everywhere and are answered first. Everything else is
6169
+ * the region's own.
5736
6170
  * @param region - the region holding the keyboard.
5737
6171
  * @param data - the raw key bytes.
5738
6172
  * @returns the action to apply, or undefined when this region claims nothing
@@ -5743,6 +6177,7 @@ function resolveKey(region, data) {
5743
6177
  if (matchesKey(data, "escape")) return ESCAPE;
5744
6178
  if (matchesKey(data, "ctrl+o")) return FOLD_ALL;
5745
6179
  if (matchesKey(data, "ctrl+g")) return READER;
6180
+ if (matchesKey(data, "ctrl+b")) return { kind: "background" };
5746
6181
  if (matchesKey(data, "ctrl+t")) return { kind: "todos" };
5747
6182
  if (matchesKey(data, "ctrl+p")) return { kind: "parent" };
5748
6183
  if (matchesKey(data, "ctrl+l")) return { kind: "redraw" };
@@ -7744,6 +8179,8 @@ var PickPrompt = class extends ListPrompt {
7744
8179
  visible;
7745
8180
  /** What `Ctrl+S` does with the highlighted row, when the caller gave it a meaning. */
7746
8181
  onSave;
8182
+ /** What `Ctrl+K` does with the highlighted row, when the caller gave it a meaning. */
8183
+ onStop;
7747
8184
  constructor(palette, title, items, options = {}) {
7748
8185
  const rows = items.map((item) => ({ ...item }));
7749
8186
  const inForce = items.findIndex((item) => item.value === options.current);
@@ -7758,6 +8195,7 @@ var PickPrompt = class extends ListPrompt {
7758
8195
  this.inForce = inForce;
7759
8196
  this.visible = markedRows;
7760
8197
  this.onSave = options.onSave;
8198
+ this.onStop = options.onStop;
7761
8199
  if (inForce > 0) this.highlight(inForce);
7762
8200
  }
7763
8201
  /**
@@ -7787,10 +8225,10 @@ var PickPrompt = class extends ListPrompt {
7787
8225
  this.setQuery("");
7788
8226
  return;
7789
8227
  }
7790
- if (matchesKey(data, "ctrl+s")) {
8228
+ if (matchesKey(data, "ctrl+s") || matchesKey(data, "ctrl+k")) {
7791
8229
  const row = this.selected();
7792
8230
  const item = row === null ? void 0 : this.items.find((candidate) => candidate.value === row.value);
7793
- if (item !== void 0) this.onSave?.(item);
8231
+ if (item !== void 0) (matchesKey(data, "ctrl+s") ? this.onSave : this.onStop)?.(item);
7794
8232
  return;
7795
8233
  }
7796
8234
  const typed = typedText(data);
@@ -10519,10 +10957,12 @@ var ToastPane = class {
10519
10957
  * turns keystrokes into agent input, answers the approval and user-questions
10520
10958
  * seams for that Agent, and switches between sessions through its host. Above
10521
10959
  * the editor it draws an activity board of the open turn's todos and the
10522
- * latest descendant line. Under the editor it keeps two docked regions the
10523
- * keyboard can take over — the subagent panel and the status bar — and one
10524
- * repeating tick advances their elapsed counters and re-reads a stale
10525
- * subagent listing. A second tick, at its own period, brightens streamed
10960
+ * latest descendant line, and a live line while background jobs run; `Ctrl+B`
10961
+ * moves the running tool calls to those jobs (`./background.ts`). Under the
10962
+ * editor it keeps two docked regions the keyboard can take over — the
10963
+ * subagent panel and the status bar — and one repeating tick advances their
10964
+ * elapsed counters and the jobs line's, and re-reads a stale subagent
10965
+ * listing. A second tick, at its own period, brightens streamed
10526
10966
  * reply text and floats out reasoning, tool cards, and activity-board rows
10527
10967
  * that just landed, each only as far up the frame as the renderer repaints
10528
10968
  * without discarding the terminal's scrollback (`./screen.ts`).
@@ -10738,6 +11178,10 @@ const LOCAL_COMMANDS = [
10738
11178
  name: "subagents",
10739
11179
  description: "Browse the subagent sessions under this session (Enter opens one as a live session view)"
10740
11180
  },
11181
+ {
11182
+ name: "jobs",
11183
+ description: "Browse this session's background jobs (Enter shows the output, Ctrl+K stops one; Ctrl+B moves running tool calls here)"
11184
+ },
10741
11185
  {
10742
11186
  name: "parent",
10743
11187
  description: "Return from a subagent view or a /btw side agent to the session it was opened from"
@@ -10782,6 +11226,19 @@ const LOCAL_COMMAND_NAMES = new Set(LOCAL_COMMANDS.map((command) => command.name
10782
11226
  function isSubscriptionMethod(method) {
10783
11227
  return method.id !== "api-key";
10784
11228
  }
11229
+ /** Shown when `Ctrl+B` or `/jobs` is used and this composition has no `ctx.jobs`. */
11230
+ const JOBS_MISSING = "background jobs need a job registry in this composition";
11231
+ /**
11232
+ * Columns of a moved call's card headline its job label keeps. The label
11233
+ * reaches the model in the completion notice, so it names the call without
11234
+ * carrying a whole command. A presentation choice of this terminal surface,
11235
+ * not a deployment setting.
11236
+ */
11237
+ const JOB_LABEL_COLUMNS = 120;
11238
+ /** Why a job the user stopped from `/jobs` was killed, as the model reads it. */
11239
+ const USER_STOP_REASON = "stopped by the user";
11240
+ /** Shown when `Ctrl+B` is pressed while the turn runs no tool call. */
11241
+ const NOTHING_TO_BACKGROUND = "no tool call is running · Ctrl+B moves a running call to the background";
10785
11242
  /** Shown when `!` is submitted and this composition has no `ctx.shell`. */
10786
11243
  const SHELL_MISSING = "! needs a shell executor in this composition";
10787
11244
  /** Shown when a second `!` is submitted while one is still running. */
@@ -10849,6 +11306,14 @@ var TuiApp = class {
10849
11306
  queueDraft;
10850
11307
  /** Suppresses the empty-queue focus handoff during a synchronous inbox transfer. */
10851
11308
  transferringQueue = false;
11309
+ /** Holds {@link jobsLine} exactly while a background job of the bound session runs. */
11310
+ jobsSlot = new Container();
11311
+ /** The live background-jobs line above the editor. */
11312
+ jobsLine;
11313
+ /** The bound session's background jobs at the last read, in registration order. */
11314
+ backgroundJobs = [];
11315
+ /** Tracks root tool calls and moves them to background jobs on `Ctrl+B`. */
11316
+ backgrounder;
10852
11317
  /** Holds {@link panel} exactly while the bound session has subagent rows. */
10853
11318
  panelSlot = new Container();
10854
11319
  /** The terminal's alternate screen, which the reader draws on; see {@link AlternateScreen}. */
@@ -11070,6 +11535,13 @@ var TuiApp = class {
11070
11535
  };
11071
11536
  this.queue = new Text("", 0, 0);
11072
11537
  this.activity = new Text("", 0, 0);
11538
+ this.jobsLine = new Text("", 0, 0);
11539
+ this.backgrounder = new ToolBackgrounder({
11540
+ jobs: () => deps.ctx.get("jobs"),
11541
+ changed: () => {
11542
+ this.onForegroundCallsChanged();
11543
+ }
11544
+ });
11073
11545
  this.panel = new Text("", 0, 0);
11074
11546
  this.banner = new ViewBanner(palette);
11075
11547
  this.footer = new FooterBar(() => ({
@@ -11096,6 +11568,7 @@ var TuiApp = class {
11096
11568
  this.inspector,
11097
11569
  this.queueSlot,
11098
11570
  this.activitySlot,
11571
+ this.jobsSlot,
11099
11572
  this.banner,
11100
11573
  this.editor,
11101
11574
  this.panelSlot,
@@ -11158,7 +11631,11 @@ var TuiApp = class {
11158
11631
  }), ctx.on("user-questions/request", (request, next) => {
11159
11632
  if (!this.claimPrompt(request.agent)) return next();
11160
11633
  return this.askQuestions(request.questions, request.signal);
11161
- }), this.tui.addInputListener((data) => this.onKey(data)));
11634
+ }), ctx.on("tools/execute", (exec, next) => this.backgrounder.around(exec, next)), this.tui.addInputListener((data) => this.onKey(data)));
11635
+ const jobs = ctx.get("jobs");
11636
+ if (jobs !== void 0) this.disposers.push(jobs.events.subscribe({ owners: "all" }, (event) => {
11637
+ this.onJobEvent(event);
11638
+ }));
11162
11639
  const projections = ctx.get("sessionProjections");
11163
11640
  if (projections !== void 0) this.disposers.push(projections.onChanged((session) => {
11164
11641
  if (session === this.agent.session) this.refreshFooter();
@@ -11288,6 +11765,7 @@ var TuiApp = class {
11288
11765
  this.refreshQueue();
11289
11766
  this.refreshFooter();
11290
11767
  this.refreshSubagentPanel();
11768
+ this.refreshJobs();
11291
11769
  this.reconcileSubagents();
11292
11770
  }
11293
11771
  /**
@@ -11883,7 +12361,8 @@ var TuiApp = class {
11883
12361
  * one runs at a time, and a stopped app runs none.
11884
12362
  */
11885
12363
  updateTicker() {
11886
- if (!this.stopped && (this.turnStartedAt !== void 0 || this.subagentsStale || this.panelView.ticking)) {
12364
+ const jobsTicking = this.backgroundJobs.some(isLive);
12365
+ if (!this.stopped && (this.turnStartedAt !== void 0 || this.subagentsStale || this.panelView.ticking || jobsTicking)) {
11887
12366
  this.ticker ??= this.deps.tick(() => {
11888
12367
  this.onTick();
11889
12368
  }, this.deps.liveRefreshMs);
@@ -11898,6 +12377,7 @@ var TuiApp = class {
11898
12377
  onTick() {
11899
12378
  if (this.subagentsStale) this.reconcileSubagents();
11900
12379
  this.refreshSubagentPanel();
12380
+ if (this.backgroundJobs.some(isLive)) this.refreshJobs();
11901
12381
  if (this.turnStartedAt !== void 0) this.refreshFooter();
11902
12382
  }
11903
12383
  statusFacts() {
@@ -12010,6 +12490,137 @@ var TuiApp = class {
12010
12490
  return [describeFailure(error)];
12011
12491
  }
12012
12492
  }
12493
+ /** Redraw what follows the foreground calls: the spinner's key hint and the jobs line. */
12494
+ onForegroundCallsChanged() {
12495
+ this.refreshLoader();
12496
+ this.refreshJobs();
12497
+ }
12498
+ /**
12499
+ * Follow one job-registry event: the backgrounder learns which jobs belong
12500
+ * to a running call, the jobs line follows the bound session's jobs, and a
12501
+ * settlement of one of them shows a transient line.
12502
+ * @param event - the registry event.
12503
+ */
12504
+ onJobEvent(event) {
12505
+ this.backgrounder.observe(event);
12506
+ if (event.type === "output") return;
12507
+ const { job } = event;
12508
+ if (job.owner !== void 0 && job.owner !== this.agent.session.id) return;
12509
+ this.refreshJobs();
12510
+ if (event.type !== "settled" || event.cause === "teardown" || this.backgrounder.isInner(job.id)) return;
12511
+ this.showToast(settledToast(job, !event.awaited && event.cause === "producer"));
12512
+ }
12513
+ /**
12514
+ * Re-read the bound session's background jobs and redraw the live line
12515
+ * above the editor. A job a running call registered for itself is that
12516
+ * call's own work, not background work, and is left out while it runs.
12517
+ */
12518
+ refreshJobs() {
12519
+ const jobs = this.deps.ctx.get("jobs");
12520
+ this.backgroundJobs = jobs === void 0 ? [] : jobs.list(this.agent.session.id).filter((job) => !this.backgrounder.isInner(job.id));
12521
+ const text = renderJobsLine(this.backgroundJobs, {
12522
+ palette: this.deps.palette,
12523
+ now: this.deps.now(),
12524
+ width: this.contentWidth()
12525
+ });
12526
+ const mounted = this.jobsSlot.children.length > 0;
12527
+ if (text === "") {
12528
+ if (mounted) this.jobsSlot.removeChild(this.jobsLine);
12529
+ } else {
12530
+ if (!mounted) this.jobsSlot.addChild(this.jobsLine);
12531
+ this.jobsLine.setText(text);
12532
+ }
12533
+ this.updateTicker();
12534
+ this.tui.requestRender();
12535
+ }
12536
+ /**
12537
+ * Answer `Ctrl+B` during a turn: move every foreground call of the bound
12538
+ * Agent to a background job and say what moved.
12539
+ */
12540
+ moveToBackground() {
12541
+ const jobs = this.deps.ctx.get("jobs");
12542
+ if (jobs === void 0) {
12543
+ this.showToast(JOBS_MISSING);
12544
+ return;
12545
+ }
12546
+ const report = this.backgrounder.moveAll(jobs, this.agent, (call) => this.jobLabel(call));
12547
+ for (const refusal of report.refused) this.notice(`could not move ${refusal} to the background`, "error");
12548
+ const [first] = report.moved;
12549
+ if (first === void 0) {
12550
+ if (report.refused.length === 0) this.showToast(NOTHING_TO_BACKGROUND);
12551
+ return;
12552
+ }
12553
+ this.showToast(report.moved.length === 1 ? `◇ ${first.name} moved to the background as ${first.id} · /jobs lists it` : `◇ ${String(report.moved.length)} calls moved to the background · /jobs lists them`);
12554
+ }
12555
+ /**
12556
+ * The job label of a moved call: the tool name and its card headline on one line.
12557
+ * @param call - the call being moved.
12558
+ * @returns the label, cut to {@link JOB_LABEL_COLUMNS} columns.
12559
+ */
12560
+ jobLabel(call) {
12561
+ const title = this.toolBlocks.get(call.callId)?.title.split("\n", 1)[0] ?? "";
12562
+ return truncateToWidth(title === "" ? call.name : `${call.name} ${title}`, JOB_LABEL_COLUMNS, "…");
12563
+ }
12564
+ /**
12565
+ * Walk the bound session's background jobs: one row per job, `Enter` shows
12566
+ * its status and output, and `Ctrl+K` stops the highlighted one. The rows
12567
+ * are read again each time the list opens, so a return from a detail page
12568
+ * shows the statuses as they are now.
12569
+ */
12570
+ async browseJobs() {
12571
+ const jobs = this.deps.ctx.get("jobs");
12572
+ if (jobs === void 0) {
12573
+ this.notice(JOBS_MISSING, "error");
12574
+ return;
12575
+ }
12576
+ let visited;
12577
+ for (;;) {
12578
+ this.refreshJobs();
12579
+ const views = this.backgroundJobs;
12580
+ if (views.length === 0) {
12581
+ this.notice("no background jobs in this session · Ctrl+B moves a running tool call here");
12582
+ return;
12583
+ }
12584
+ const now = this.deps.now();
12585
+ const picked = await this.showModal(new PickPrompt(this.deps.palette, "Background jobs", views.map((view) => jobChoice(view, now)), {
12586
+ body: [JOBS_PICKER_HINT],
12587
+ ...visited === void 0 ? {} : { current: visited },
12588
+ onStop: (item) => {
12589
+ const view = views.find((candidate) => candidate.id === item.value);
12590
+ /* v8 ignore next -- the picker answers with one of the rows it was handed */
12591
+ if (view !== void 0) this.stopJob(jobs, view);
12592
+ }
12593
+ }));
12594
+ if (picked === void 0) return;
12595
+ const view = views.find((candidate) => candidate.id === picked.value);
12596
+ /* v8 ignore next -- the picker settles with one of the rows it was handed */
12597
+ if (view === void 0) return;
12598
+ visited = view.id;
12599
+ await this.showModal(new DetailPrompt(this.deps.palette, `Job ${view.id}`, this.jobDetail(jobs, view)));
12600
+ }
12601
+ }
12602
+ /**
12603
+ * The detail page of one job, read fresh: its status and the tail of the
12604
+ * output its body writes, which for a moved shell call is the shell's own
12605
+ * process job.
12606
+ * @param jobs - the registry the list was read from.
12607
+ * @param listed - the job as the list showed it.
12608
+ * @returns the page rows.
12609
+ */
12610
+ jobDetail(jobs, listed) {
12611
+ const owner = this.agent.session.id;
12612
+ const view = jobs.get(listed.id, owner);
12613
+ return jobDetailRows(view, jobs.readAt(this.backgrounder.outputOf(view.id), 0, owner).chunks, this.deps.now());
12614
+ }
12615
+ /**
12616
+ * Stop one job from `/jobs` and say whether anything was still running.
12617
+ * @param jobs - the registry the list was read from.
12618
+ * @param view - the highlighted job.
12619
+ */
12620
+ stopJob(jobs, view) {
12621
+ const outcome = jobs.kill(view.id, this.agent.session.id, USER_STOP_REASON);
12622
+ this.showToast(outcome === "requested" ? `stopping ${view.id}` : `${view.id} already finished`);
12623
+ }
12013
12624
  /**
12014
12625
  * Walk the agent's todo list: one row per item, and entering a row shows
12015
12626
  * that item in full with its position, the list's counts by status, and the
@@ -12306,6 +12917,10 @@ var TuiApp = class {
12306
12917
  }
12307
12918
  this.dispatchCommand("/effort");
12308
12919
  return { consume: true };
12920
+ case "background":
12921
+ if (this.agent.status !== "running") return this.focus === "editor" ? void 0 : { consume: true };
12922
+ this.moveToBackground();
12923
+ return { consume: true };
12309
12924
  case "todos":
12310
12925
  this.focusEditor();
12311
12926
  this.dispatchCommand("/todos");
@@ -12367,8 +12982,13 @@ var TuiApp = class {
12367
12982
  }
12368
12983
  this.disarmStop();
12369
12984
  this.agent.cancel({ kind: "user" }, { keepInbox: true });
12985
+ const jobs = this.deps.ctx.get("jobs");
12986
+ const moved = jobs === void 0 ? 0 : this.backgrounder.holdStopped(jobs, this.agent);
12370
12987
  const queued = this.agent.inbox.nextTurn.length + this.agent.inbox.nextStep.length;
12371
- this.notice(queued === 0 ? "stopping the turn…" : `stopping the turn… ${String(queued)} queued message(s) stay queued`);
12988
+ const facts = ["stopping the turn…"];
12989
+ if (queued > 0) facts.push(`${String(queued)} queued message(s) stay queued`);
12990
+ if (moved > 0) facts.push(`${String(moved)} background call(s) from this turn stop with it`);
12991
+ this.notice(facts.join(" "));
12372
12992
  return { consume: true };
12373
12993
  }
12374
12994
  /** Start the window in which an `Escape` reaching the editor does nothing at all. */
@@ -13241,6 +13861,9 @@ var TuiApp = class {
13241
13861
  case "parent":
13242
13862
  await this.leaveSubagent();
13243
13863
  return;
13864
+ case "jobs":
13865
+ await this.browseJobs();
13866
+ return;
13244
13867
  case "settings":
13245
13868
  await this.settings(argument);
13246
13869
  return;
@@ -14298,8 +14921,11 @@ var TuiApp = class {
14298
14921
  const block = this.toolBlocks.get(result.toolCallId);
14299
14922
  if (block === void 0) break;
14300
14923
  const isError = result.isError === true;
14301
- const body = toolResultBody(this.presentResult(block.name, this.toolArguments.get(result.toolCallId), result.content, isError, event.data.meta), result.content);
14302
- block.setResult(body.lines, isError, body.code, body.diff);
14924
+ const moved = isError ? movedJobId(result.content) : void 0;
14925
+ if (moved === void 0) {
14926
+ const body = toolResultBody(this.presentResult(block.name, this.toolArguments.get(result.toolCallId), result.content, isError, event.data.meta), result.content);
14927
+ block.setResult(body.lines, isError, body.code, body.diff);
14928
+ } else block.setBackground([`◇ moved to the background as ${moved} · /jobs lists it`]);
14303
14929
  this.spinners.delete(block);
14304
14930
  this.updateSpinTicker();
14305
14931
  this.fadeBlock((fade) => {
@@ -14519,10 +15145,16 @@ var TuiApp = class {
14519
15145
  const rest = message.slice(activity.length);
14520
15146
  return `${shimmer(palette, activity, this.deps.now())}${rest === "" ? "" : palette.dim(rest)}`;
14521
15147
  }
14522
- /** Draw the spinner label plus the current call's ↑send ↓receive suffix. */
15148
+ /**
15149
+ * Draw the spinner label plus the current call's ↑send ↓receive suffix,
15150
+ * and the key that moves a foreground call to the background while one runs.
15151
+ */
14523
15152
  refreshLoader() {
15153
+ const parts = [this.loaderActivity];
14524
15154
  const suffix = formatLiveUsage(this.liveUsage);
14525
- this.loader.setMessage(suffix === "" ? this.loaderActivity : `${this.loaderActivity} ${suffix}`);
15155
+ if (suffix !== "") parts.push(suffix);
15156
+ if (this.backgrounder.running(this.agent).length > 0) parts.push(`· ${BACKGROUND_KEY_HINT}`);
15157
+ this.loader.setMessage(parts.join(" "));
14526
15158
  }
14527
15159
  /**
14528
15160
  * Label the spinner for a tool-call delta before its card is paced.