@unieai/rabi-tool-terminal 0.0.0-stage → 0.2.2-rc.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 DeepSeek
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,8 @@
1
- # Temporary Holding Version
1
+ # @unieai/rabi-tool-terminal
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Six model-facing persistent PTY tools with owner isolation and generic background-job integration
4
+
5
+ Part of Rabi, the agent harness UnieAI Code runs on. Installed as a dependency of `@unieai/rabi`;
6
+ not meant to be used on its own.
7
+
8
+ See LICENSE for the license and copyright of this package.
package/lib/index.js ADDED
@@ -0,0 +1,654 @@
1
+ import { resolve } from "node:path";
2
+ import z from "@unieai/schemastery";
3
+ import { TerminalSessionId } from "@unieai/rabi-terminal";
4
+ import { defineTool } from "@unieai/rabi-tools";
5
+ import { TextRetainer } from "@unieai/rabi-output-retention";
6
+ //#region lib/types/render.js
7
+ /** Model and UI rendering for persistent terminal tool results. */
8
+ const encoder = new TextEncoder();
9
+ const TRUNCATED = "\n[output truncated]";
10
+ function byteLength(text) {
11
+ return encoder.encode(text).byteLength;
12
+ }
13
+ function retain(text, maxBytes, kind) {
14
+ const retainer = new TextRetainer({
15
+ kind,
16
+ maxBytes
17
+ });
18
+ retainer.push(text);
19
+ return retainer.finish().text;
20
+ }
21
+ function fitWithSuffix(content, suffix, maxBytes) {
22
+ const fixedBytes = byteLength(suffix);
23
+ if (fixedBytes >= maxBytes) return retain(suffix, maxBytes, "tail");
24
+ return `${retain(content, maxBytes - fixedBytes, "tail")}${suffix}`;
25
+ }
26
+ function fitWithPrefix(prefix, content, maxBytes) {
27
+ const fixed = `${prefix}${TRUNCATED}`;
28
+ const fixedBytes = byteLength(fixed);
29
+ if (fixedBytes >= maxBytes) return retain(fixed, maxBytes, "head");
30
+ return `${prefix}${retain(content, maxBytes - fixedBytes, "tail")}${TRUNCATED}`;
31
+ }
32
+ function boundBodyWithSuffix(content, metadata, upstreamTruncated, maxBytes) {
33
+ const complete = `${content}${`${metadata}${upstreamTruncated ? TRUNCATED : ""}`}`;
34
+ if (byteLength(complete) <= maxBytes) return complete;
35
+ return fitWithSuffix(content, `${metadata}${TRUNCATED}`, maxBytes);
36
+ }
37
+ /**
38
+ * Bound one complete terminal acknowledgement while preserving UTF-8 cuts.
39
+ * @param text - complete acknowledgement text.
40
+ * @param maxBytes - positive final result cap.
41
+ * @returns bounded text with a truncation marker when it fits.
42
+ */
43
+ function boundTerminalText(text, maxBytes) {
44
+ if (byteLength(text) <= maxBytes) return text;
45
+ const markerBytes = byteLength(TRUNCATED);
46
+ if (markerBytes >= maxBytes) return retain(TRUNCATED, maxBytes, "tail");
47
+ return `${retain(text, maxBytes - markerBytes, "head")}${TRUNCATED}`;
48
+ }
49
+ /**
50
+ * Render one created session and its bounded MOTD.
51
+ * @param result - published spawn result.
52
+ * @param maxBytes - complete UTF-8 result cap.
53
+ * @returns Model-facing session acknowledgement.
54
+ */
55
+ function renderSpawn(result, maxBytes) {
56
+ const prefix = `started terminal session ${result.name === void 0 ? result.sessionId : `${result.sessionId} (${result.name})`} [type: ${result.type}]\n`;
57
+ const motd = result.motd || "(no startup output)";
58
+ const complete = `${prefix}${motd}`;
59
+ return byteLength(complete) <= maxBytes ? complete : fitWithPrefix(prefix, motd, maxBytes);
60
+ }
61
+ /**
62
+ * Render one settled interactive send.
63
+ * @param result - settled send outcome.
64
+ * @param maxBytes - complete UTF-8 result cap.
65
+ * @returns Terminal output plus wait/session markers.
66
+ */
67
+ function renderSend(result, maxBytes) {
68
+ const output = result.viewport || "(no new output)";
69
+ const status = result.sessionStatus.kind === "running" ? "running" : `exited code=${result.sessionStatus.exitCode ?? "null"} signal=${result.sessionStatus.signal ?? "null"}`;
70
+ return boundBodyWithSuffix(output, `\n[wait: ${result.waitReason}]\n[session: ${status}]`, result.truncated, maxBytes);
71
+ }
72
+ /**
73
+ * Render one incremental background operation read.
74
+ * @param read - consuming operation delta.
75
+ * @returns Delta plus its upstream truncation marker. The generic task control
76
+ * applies the producer's complete-result cap after adding job status.
77
+ */
78
+ function renderSendRead(read) {
79
+ const separator = read.delta.endsWith("\n") || read.delta.length === 0 ? "" : "\n";
80
+ return `${read.delta}${read.truncated ? `${separator}[output truncated]` : ""}`;
81
+ }
82
+ /**
83
+ * Render one bounded historical page.
84
+ * @param result - retained scrollback page.
85
+ * @param maxBytes - complete UTF-8 result cap.
86
+ * @returns Page text plus pagination and truncation markers.
87
+ */
88
+ function renderRead(result, maxBytes) {
89
+ return boundBodyWithSuffix(result.text || "(no retained output)", `\n[lines: ${result.lineBegin}-${result.lineEnd} of ${result.totalLines}]`, result.truncated, maxBytes);
90
+ }
91
+ /**
92
+ * Render owner-visible live sessions.
93
+ * @param sessions - fresh owner-scoped snapshots.
94
+ * @param maxBytes - complete UTF-8 result cap.
95
+ * @returns One line per session or the empty marker.
96
+ */
97
+ function renderList(sessions, maxBytes) {
98
+ if (sessions.length === 0) return "(no terminal sessions)";
99
+ return boundBodyWithSuffix(sessions.map((session) => {
100
+ const name = session.name === void 0 ? "" : ` (${session.name})`;
101
+ const pid = session.pid === void 0 ? "" : ` pid=${session.pid}`;
102
+ const status = session.status.kind === "running" ? "running" : `exited code=${session.status.exitCode ?? "null"} signal=${session.status.signal ?? "null"}`;
103
+ return `${session.sessionId}${name} [${session.type}] ${status}${pid}`;
104
+ }).join("\n"), "", false, maxBytes);
105
+ }
106
+ //#endregion
107
+ //#region lib/types/background.js
108
+ /**
109
+ * Generic-job adaptation for background terminal sends: the registry pull
110
+ * source over the backend's consuming send reader.
111
+ *
112
+ * @module @unieai/rabi-tool-terminal/background
113
+ */
114
+ /**
115
+ * Adapt the backend's consuming send reader to a registry pull source. The
116
+ * reader has no offsets of its own — each call hands over what arrived since
117
+ * the previous one — so the source counts the bytes it delivered to keep the
118
+ * registry's cursor monotonic. It binds lazily because the send starts inside
119
+ * the job starter, after the registry admitted the job; a read before that
120
+ * point delivers nothing.
121
+ * @param operation - the live send, once the starter has begun it.
122
+ * @returns one unlabeled source over the send's bounded delta.
123
+ */
124
+ function sendSource(operation) {
125
+ return { read: (fromByte) => {
126
+ const live = operation();
127
+ if (live === void 0) return {
128
+ text: "",
129
+ nextOffset: fromByte,
130
+ lossy: false
131
+ };
132
+ const text = renderSendRead(live.readOutput());
133
+ return {
134
+ text,
135
+ nextOffset: fromByte + Buffer.byteLength(text),
136
+ lossy: false
137
+ };
138
+ } };
139
+ }
140
+ //#endregion
141
+ //#region lib/types/index.js
142
+ /**
143
+ * Six model-facing persistent terminal tools. Owner identity comes from the exact
144
+ * tool execution Agent; generic `ctx.jobs` owns background ids and collection.
145
+ * @module @unieai/rabi-tool-terminal
146
+ */
147
+ /** Cordis plugin name. */
148
+ const name = "tool-terminal";
149
+ /** Required capability, registry, and prompt services. */
150
+ const inject = [
151
+ "terminals",
152
+ "tools",
153
+ "systemPrompt",
154
+ "workingDirectory"
155
+ ];
156
+ /** Default cap for one complete model-facing terminal result. */
157
+ const DEFAULT_MAX_RESULT_BYTES = 256 * 1024;
158
+ /** Smallest cap that preserves registry-issued PTY and job ids in creation acknowledgements. */
159
+ const MIN_MAX_RESULT_BYTES = 64;
160
+ /** Schemastery configuration for the terminal tool consumer. */
161
+ const Config = z.object({
162
+ enableRunInBackground: z.boolean().default(true),
163
+ maxResultBytes: z.number().step(1).min(64).max(Number.MAX_SAFE_INTEGER).default(DEFAULT_MAX_RESULT_BYTES)
164
+ });
165
+ const SESSION_STATUS_SCHEMA = { oneOf: [{
166
+ type: "object",
167
+ additionalProperties: false,
168
+ properties: { kind: {
169
+ type: "string",
170
+ required: true,
171
+ const: "running"
172
+ } }
173
+ }, {
174
+ type: "object",
175
+ additionalProperties: false,
176
+ properties: {
177
+ kind: {
178
+ type: "string",
179
+ required: true,
180
+ const: "exited"
181
+ },
182
+ exitCode: {
183
+ required: true,
184
+ oneOf: [{ type: "integer" }, { type: "null" }]
185
+ },
186
+ signal: {
187
+ required: true,
188
+ oneOf: [{ type: "string" }, { type: "null" }]
189
+ }
190
+ }
191
+ }] };
192
+ const SESSION_SNAPSHOT_PROPERTIES = {
193
+ sessionId: {
194
+ type: "string",
195
+ required: true
196
+ },
197
+ name: { type: "string" },
198
+ type: {
199
+ type: "string",
200
+ required: true
201
+ },
202
+ pid: { type: "integer" },
203
+ status: {
204
+ ...SESSION_STATUS_SCHEMA,
205
+ required: true
206
+ }
207
+ };
208
+ const SESSION_SNAPSHOT_SCHEMA = {
209
+ type: "object",
210
+ additionalProperties: false,
211
+ properties: SESSION_SNAPSHOT_PROPERTIES
212
+ };
213
+ const BACKGROUND_JOB_OUTPUT_SCHEMA = {
214
+ type: "object",
215
+ additionalProperties: false,
216
+ properties: {
217
+ kind: {
218
+ type: "string",
219
+ required: true,
220
+ const: "background"
221
+ },
222
+ jobId: {
223
+ type: "string",
224
+ required: true
225
+ }
226
+ }
227
+ };
228
+ function requireAgent(agent) {
229
+ if (agent === void 0) throw new Error("terminal tools require an initiating agent");
230
+ return agent;
231
+ }
232
+ function sessionId(args) {
233
+ if (args.sessionId.length === 0) throw new Error("sessionId must be a non-empty string");
234
+ return TerminalSessionId(args.sessionId);
235
+ }
236
+ function textResult(text, maxBytes) {
237
+ return [{
238
+ type: "text",
239
+ text: boundTerminalText(text, maxBytes)
240
+ }];
241
+ }
242
+ function rawContentText(content) {
243
+ if (content.length !== 1) return void 0;
244
+ const block = content[0];
245
+ return block?.type === "text" ? block.text : void 0;
246
+ }
247
+ function sendDetail(result) {
248
+ return result.sessionStatus.kind === "running" ? `wait: ${result.waitReason}` : `session exited: ${result.sessionStatus.exitCode ?? result.sessionStatus.signal ?? "unknown"}`;
249
+ }
250
+ /** Register all terminal tools and the minimal usage guidance. */
251
+ function apply(ctx, config = {}) {
252
+ const enableRunInBackground = config.enableRunInBackground ?? true;
253
+ const maxResultBytes = config.maxResultBytes ?? 262144;
254
+ if (!Number.isSafeInteger(maxResultBytes) || maxResultBytes < 64) throw new Error(`tool-terminal: maxResultBytes must be a safe integer of at least 64`);
255
+ const finalizeContent = (_exec, result) => {
256
+ const raw = rawContentText(result.content);
257
+ return raw === void 0 ? void 0 : textResult(raw, maxResultBytes);
258
+ };
259
+ ctx.systemPrompt.section({
260
+ name: "tool:pty",
261
+ order: ctx.systemPrompt.getSectionOrder("TOOL_PTY"),
262
+ text: "Use a terminal session only when work needs persistent terminal state or interactive stdin; prefer shell/read/write/edit for bounded one-shot operations. Track every terminal session id and close sessions that no longer matter. An inferred_idle or timeout result does not prove the foreground command exited."
263
+ });
264
+ ctx.tools.register(defineTool({
265
+ name: "terminal_open",
266
+ description: "Create a persistent, owner-isolated terminal session from a registered backend type. Use this for shell or REPL state that must survive across tool calls.",
267
+ parameters: {
268
+ type: {
269
+ type: "string",
270
+ required: true,
271
+ description: "Registered terminal backend type, usually \"shell\"."
272
+ },
273
+ name: {
274
+ type: "string",
275
+ description: "Optional owner-local display name such as \"main\" or \"gdb\"."
276
+ },
277
+ cwd: {
278
+ type: "string",
279
+ description: "Initial working directory, relative to the Session current directory when not absolute."
280
+ }
281
+ },
282
+ finalizeContent,
283
+ output: {
284
+ schema: {
285
+ type: "object",
286
+ additionalProperties: false,
287
+ properties: {
288
+ ...SESSION_SNAPSHOT_PROPERTIES,
289
+ motd: {
290
+ type: "string",
291
+ required: true
292
+ }
293
+ }
294
+ },
295
+ render: (_args, value) => [{
296
+ type: "text",
297
+ text: renderSpawn(value, maxResultBytes)
298
+ }]
299
+ },
300
+ async execute(args, exec) {
301
+ if (args.type.length === 0) throw new Error("type must be a non-empty string");
302
+ const owner = requireAgent(exec.agent);
303
+ const cwd = await ctx.workingDirectory.ensure(owner, exec.signal);
304
+ return await ctx.terminals.spawn(owner, {
305
+ type: args.type,
306
+ ...args.name !== void 0 ? { name: args.name } : {},
307
+ cwd: args.cwd === void 0 ? cwd : resolve(cwd, args.cwd)
308
+ }, exec.signal);
309
+ },
310
+ presentCall: (args) => {
311
+ const parsed = args;
312
+ return {
313
+ card: "generic",
314
+ title: `Open terminal ${parsed.name ?? parsed.type}`,
315
+ kind: "execute"
316
+ };
317
+ }
318
+ }));
319
+ ctx.tools.register(defineTool({
320
+ name: "terminal_send",
321
+ description: "Send text to a persistent terminal. By default Enter is submitted and the call waits for a prompt, stdin wait, output silence, timeout, or session exit." + (enableRunInBackground ? " Background mode returns a job id for job_output/job_kill." : ""),
322
+ parameters: {
323
+ sessionId: {
324
+ type: "string",
325
+ required: true,
326
+ description: "Terminal session id returned by terminal_open or terminal_list."
327
+ },
328
+ text: {
329
+ type: "string",
330
+ required: true,
331
+ description: "UTF-8 text to write to the terminal."
332
+ },
333
+ submit: {
334
+ type: "boolean",
335
+ description: "Submit Enter after text (default true). Set false for control characters or incomplete REPL input."
336
+ },
337
+ ...enableRunInBackground ? { run_in_background: {
338
+ type: "boolean",
339
+ description: "Return a job id immediately; collect with job_output or stop with job_kill."
340
+ } } : {}
341
+ },
342
+ finalizeContent,
343
+ output: {
344
+ schema: { oneOf: [BACKGROUND_JOB_OUTPUT_SCHEMA, {
345
+ type: "object",
346
+ additionalProperties: false,
347
+ properties: {
348
+ kind: {
349
+ type: "string",
350
+ required: true,
351
+ const: "foreground"
352
+ },
353
+ viewport: {
354
+ type: "string",
355
+ required: true
356
+ },
357
+ waitReason: {
358
+ type: "string",
359
+ required: true,
360
+ enum: [
361
+ "stdin_read",
362
+ "inferred_idle",
363
+ "timeout",
364
+ "session_exit"
365
+ ]
366
+ },
367
+ sessionStatus: {
368
+ ...SESSION_STATUS_SCHEMA,
369
+ required: true
370
+ },
371
+ truncated: {
372
+ type: "boolean",
373
+ required: true
374
+ }
375
+ }
376
+ }] },
377
+ render: (_args, value) => [{
378
+ type: "text",
379
+ text: value.kind === "background" ? `started background job ${value.jobId}` : renderSend(value, maxResultBytes)
380
+ }],
381
+ presentationMeta: (_args, value) => value.kind === "foreground" ? {
382
+ viewport: value.viewport,
383
+ waitReason: value.waitReason,
384
+ sessionStatus: value.sessionStatus,
385
+ truncated: value.truncated
386
+ } : null
387
+ },
388
+ async execute(args, exec) {
389
+ const owner = requireAgent(exec.agent);
390
+ const id = sessionId(args);
391
+ const request = {
392
+ text: args.text,
393
+ submit: args.submit ?? true
394
+ };
395
+ if (args.run_in_background === true) {
396
+ if (!enableRunInBackground) throw new Error("background terminal sends are disabled by tool-terminal configuration");
397
+ const jobs = ctx.get("jobs");
398
+ if (jobs === void 0) throw new Error("background terminal sends require @unieai/rabi-jobs and @unieai/rabi-tool-jobs");
399
+ let cancelRequested = false;
400
+ let operation;
401
+ return {
402
+ kind: "background",
403
+ jobId: jobs.start({
404
+ kind: "pty-send",
405
+ label: `${id}: ${args.text || "(input)"}`,
406
+ toolCall: {
407
+ callId: exec.callId,
408
+ rootCallId: exec.rootCallId
409
+ },
410
+ owner: owner.id,
411
+ outputLimitBytes: maxResultBytes,
412
+ output: [sendSource(() => operation)],
413
+ run: () => {
414
+ const started = ctx.terminals.startSend(owner, id, request);
415
+ operation = started;
416
+ return {
417
+ cancel: () => {
418
+ cancelRequested = true;
419
+ started.cancel();
420
+ },
421
+ done: started.done.then((result) => ({
422
+ status: cancelRequested ? "killed" : "completed",
423
+ detail: sendDetail(result)
424
+ }), (error) => ({
425
+ status: "failed",
426
+ detail: String(error)
427
+ }))
428
+ };
429
+ }
430
+ })
431
+ };
432
+ }
433
+ const result = await ctx.terminals.startSend(owner, id, {
434
+ ...request,
435
+ signal: exec.signal
436
+ }).done;
437
+ if (exec.signal.aborted) throw new Error("terminal send aborted");
438
+ return {
439
+ kind: "foreground",
440
+ ...result
441
+ };
442
+ },
443
+ presentCall(args) {
444
+ const parsed = args;
445
+ if (parsed.run_in_background === true) return {
446
+ card: "generic",
447
+ title: `Send to terminal ${parsed.sessionId} in background`,
448
+ kind: "execute",
449
+ rawInput: parsed.text
450
+ };
451
+ return {
452
+ card: "terminal",
453
+ title: parsed.text || "(send input)",
454
+ description: `Terminal ${parsed.sessionId}`
455
+ };
456
+ },
457
+ presentResult(args, result) {
458
+ if (args.run_in_background === true || result.isError) return void 0;
459
+ const raw = rawContentText(result.content);
460
+ return raw === void 0 ? void 0 : {
461
+ card: "terminal",
462
+ output: raw
463
+ };
464
+ }
465
+ }));
466
+ ctx.tools.register(defineTool({
467
+ name: "terminal_read",
468
+ description: "Read a bounded page of retained output from a persistent terminal without sending input.",
469
+ parameters: {
470
+ sessionId: {
471
+ type: "string",
472
+ required: true,
473
+ description: "Terminal session id."
474
+ },
475
+ offset: {
476
+ type: "number",
477
+ description: "Newest-relative line offset (default 0)."
478
+ },
479
+ count: {
480
+ type: "number",
481
+ description: "Requested line count (default 500; backend caps apply)."
482
+ }
483
+ },
484
+ finalizeContent,
485
+ output: {
486
+ schema: {
487
+ type: "object",
488
+ additionalProperties: false,
489
+ properties: {
490
+ text: {
491
+ type: "string",
492
+ required: true
493
+ },
494
+ totalLines: {
495
+ type: "integer",
496
+ required: true
497
+ },
498
+ lineBegin: {
499
+ type: "integer",
500
+ required: true
501
+ },
502
+ lineEnd: {
503
+ type: "integer",
504
+ required: true
505
+ },
506
+ truncated: {
507
+ type: "boolean",
508
+ required: true
509
+ }
510
+ }
511
+ },
512
+ render: (_args, value) => [{
513
+ type: "text",
514
+ text: renderRead(value, maxResultBytes)
515
+ }]
516
+ },
517
+ execute(args, exec) {
518
+ const result = ctx.terminals.read(requireAgent(exec.agent), sessionId(args), {
519
+ ...args.offset !== void 0 ? { offset: args.offset } : {},
520
+ ...args.count !== void 0 ? { count: args.count } : {}
521
+ });
522
+ return Promise.resolve(result);
523
+ },
524
+ presentCall: (args) => ({
525
+ card: "generic",
526
+ title: `Read terminal ${args.sessionId}`,
527
+ kind: "read",
528
+ rawInput: args
529
+ })
530
+ }));
531
+ ctx.tools.register(defineTool({
532
+ name: "terminal_signal",
533
+ description: "Send an allowed signal to the current foreground process group of a persistent terminal.",
534
+ parameters: {
535
+ sessionId: {
536
+ type: "string",
537
+ required: true,
538
+ description: "Terminal session id."
539
+ },
540
+ signal: {
541
+ type: "string",
542
+ required: true,
543
+ enum: [
544
+ "SIGINT",
545
+ "SIGTERM",
546
+ "SIGKILL",
547
+ "SIGTSTP",
548
+ "SIGHUP"
549
+ ],
550
+ description: "Signal to deliver. Shell-targeted SIGKILL is rejected; use terminal_close."
551
+ }
552
+ },
553
+ finalizeContent,
554
+ output: {
555
+ schema: {
556
+ type: "object",
557
+ additionalProperties: false,
558
+ properties: {
559
+ delivered: {
560
+ type: "boolean",
561
+ required: true,
562
+ const: true
563
+ },
564
+ targetPgid: {
565
+ type: "integer",
566
+ required: true
567
+ }
568
+ }
569
+ },
570
+ render: (args, value) => [{
571
+ type: "text",
572
+ text: `delivered ${args.signal} to foreground process group ${value.targetPgid}`
573
+ }]
574
+ },
575
+ async execute(args, exec) {
576
+ return ctx.terminals.signal(requireAgent(exec.agent), sessionId(args), args.signal);
577
+ },
578
+ presentCall: (args) => ({
579
+ card: "generic",
580
+ title: `Signal terminal ${args.sessionId}`,
581
+ kind: "execute",
582
+ rawInput: args
583
+ })
584
+ }));
585
+ ctx.tools.register(defineTool({
586
+ name: "terminal_close",
587
+ description: "Close one persistent terminal and wait until its captured owned process tree is gone.",
588
+ parameters: { sessionId: {
589
+ type: "string",
590
+ required: true,
591
+ description: "Terminal session id."
592
+ } },
593
+ finalizeContent,
594
+ output: {
595
+ schema: {
596
+ type: "object",
597
+ additionalProperties: false,
598
+ properties: {
599
+ sessionId: {
600
+ type: "string",
601
+ required: true
602
+ },
603
+ outcome: {
604
+ type: "string",
605
+ required: true,
606
+ enum: ["closed", "already-closing"]
607
+ }
608
+ }
609
+ },
610
+ render: (_args, value) => [{
611
+ type: "text",
612
+ text: value.outcome === "closed" ? `closed terminal session ${value.sessionId}` : `terminal session ${value.sessionId} was already closing`
613
+ }]
614
+ },
615
+ async execute(args, exec) {
616
+ const id = sessionId(args);
617
+ return {
618
+ sessionId: id,
619
+ outcome: await ctx.terminals.kill(requireAgent(exec.agent), id) ? "closed" : "already-closing"
620
+ };
621
+ },
622
+ presentCall: (args) => ({
623
+ card: "generic",
624
+ title: `Close terminal ${args.sessionId}`,
625
+ kind: "delete"
626
+ })
627
+ }));
628
+ ctx.tools.register(defineTool({
629
+ name: "terminal_list",
630
+ description: "List persistent terminal sessions owned by the current agent.",
631
+ parameters: {},
632
+ finalizeContent,
633
+ output: {
634
+ schema: {
635
+ type: "array",
636
+ items: SESSION_SNAPSHOT_SCHEMA
637
+ },
638
+ render: (_args, value) => [{
639
+ type: "text",
640
+ text: renderList(value, maxResultBytes)
641
+ }]
642
+ },
643
+ execute(_args, exec) {
644
+ return Promise.resolve(ctx.terminals.list(requireAgent(exec.agent)));
645
+ },
646
+ presentCall: () => ({
647
+ card: "generic",
648
+ title: "List terminal sessions",
649
+ kind: "read"
650
+ })
651
+ }));
652
+ }
653
+ //#endregion
654
+ export { Config, DEFAULT_MAX_RESULT_BYTES, MIN_MAX_RESULT_BYTES, apply, inject, name };
@@ -0,0 +1,20 @@
1
+ /**
2
+ * Generic-job adaptation for background terminal sends: the registry pull
3
+ * source over the backend's consuming send reader.
4
+ *
5
+ * @module @unieai/rabi-tool-terminal/background
6
+ */
7
+ import type { JobOutputSource } from '@unieai/rabi-jobs';
8
+ import type { TerminalSendOperation } from '@unieai/rabi-terminal';
9
+ /**
10
+ * Adapt the backend's consuming send reader to a registry pull source. The
11
+ * reader has no offsets of its own — each call hands over what arrived since
12
+ * the previous one — so the source counts the bytes it delivered to keep the
13
+ * registry's cursor monotonic. It binds lazily because the send starts inside
14
+ * the job starter, after the registry admitted the job; a read before that
15
+ * point delivers nothing.
16
+ * @param operation - the live send, once the starter has begun it.
17
+ * @returns one unlabeled source over the send's bounded delta.
18
+ */
19
+ export declare function sendSource(operation: () => TerminalSendOperation | undefined): JobOutputSource;
20
+ //# sourceMappingURL=background.d.ts.map