@unieai/rabi-tool-terminal 0.2.1-rc.3 → 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/locale/de.json ADDED
@@ -0,0 +1,6 @@
1
+ {
2
+ "meta": {
3
+ "title": "Persistente Terminal-Tools",
4
+ "description": "Stellen Sie sechs persistente PTY-Tools mit isoliertem Sitzungsbesitz und Integration von Hintergrundaufgaben bereit."
5
+ }
6
+ }
package/locale/en.json ADDED
@@ -0,0 +1,6 @@
1
+ {
2
+ "meta": {
3
+ "title": "Persistent terminal tools",
4
+ "description": "Provide six persistent PTY tools with isolated session ownership and background task integration."
5
+ }
6
+ }
package/locale/es.json ADDED
@@ -0,0 +1,6 @@
1
+ {
2
+ "meta": {
3
+ "title": "Herramientas de terminal persistente",
4
+ "description": "Proporcione seis herramientas PTY persistentes con propiedad de sesión aislada e integración de tareas en segundo plano."
5
+ }
6
+ }
package/locale/fr.json ADDED
@@ -0,0 +1,6 @@
1
+ {
2
+ "meta": {
3
+ "title": "Outils de terminal persistants",
4
+ "description": "Fournissez six outils PTY persistants avec propriété de session isolée et intégration de tâches en arrière-plan."
5
+ }
6
+ }
package/locale/ja.json ADDED
@@ -0,0 +1,6 @@
1
+ {
2
+ "meta": {
3
+ "title": "永続ターミナルツール",
4
+ "description": "6 つの永続 PTY ツールを提供し、セッションの所有権を分離してバックグラウンドタスクと連携します。"
5
+ }
6
+ }
package/locale/pt.json ADDED
@@ -0,0 +1,6 @@
1
+ {
2
+ "meta": {
3
+ "title": "Ferramentas de terminal persistentes",
4
+ "description": "Forneça seis ferramentas PTY persistentes com propriedade de sessão isolada e integração de tarefas em segundo plano."
5
+ }
6
+ }
package/locale/ru.json ADDED
@@ -0,0 +1,6 @@
1
+ {
2
+ "meta": {
3
+ "title": "Постоянные терминальные инструменты",
4
+ "description": "Предоставьте шесть постоянных инструментов PTY с изолированным владением сеансом и интеграцией фоновых задач."
5
+ }
6
+ }
package/locale/zh.json ADDED
@@ -0,0 +1,6 @@
1
+ {
2
+ "meta": {
3
+ "title": "持久终端工具",
4
+ "description": "提供六个持久 PTY 工具,隔离会话所有权并集成后台任务。"
5
+ }
6
+ }
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@unieai/rabi-tool-terminal",
3
3
  "description": "Six model-facing persistent PTY tools with owner isolation and generic background-job integration",
4
- "version": "0.2.1-rc.3",
4
+ "version": "0.2.2-rc.5",
5
5
  "publishConfig": {
6
6
  "access": "public"
7
7
  },
@@ -14,26 +14,31 @@
14
14
  "default": "./lib/index.js"
15
15
  },
16
16
  "./src/*": "./src/*",
17
+ "./locale/*.json": "./locale/*.json",
17
18
  "./package.json": "./package.json"
18
19
  },
19
20
  "files": [
21
+ "locale/*.json",
20
22
  "lib/index.js",
21
23
  "lib/types/**/*.d.ts",
24
+ "lib/types/**/*.d.ts.map",
25
+ "lib/**/*.js.map",
26
+ "src",
22
27
  "README.md"
23
28
  ],
24
29
  "license": "MIT",
25
30
  "dependencies": {
26
- "@unieai/schemastery": "3.18.5"
31
+ "@unieai/schemastery": "3.19.0"
27
32
  },
28
33
  "peerDependencies": {
29
- "@unieai/rabi-agent": "0.2.1-rc.3",
30
- "@unieai/rabi-llm": "0.2.1-rc.3",
31
- "@unieai/rabi-terminal": "0.2.1-rc.3",
32
- "@unieai/rabi-output-retention": "0.2.1-rc.3",
33
- "@unieai/rabi-system-prompt": "0.2.1-rc.3",
34
- "@unieai/rabi-jobs": "0.2.1-rc.3",
35
- "@unieai/rabi-tools": "0.2.1-rc.3",
36
- "@unieai/cordis": "4.0.5",
37
- "@unieai/rabi-working-directory": "0.2.1-rc.3"
34
+ "@unieai/rabi-agent": "0.2.2-rc.5",
35
+ "@unieai/rabi-llm": "0.2.2-rc.5",
36
+ "@unieai/rabi-terminal": "0.2.2-rc.5",
37
+ "@unieai/rabi-output-retention": "0.2.2-rc.5",
38
+ "@unieai/rabi-system-prompt": "0.2.2-rc.5",
39
+ "@unieai/rabi-jobs": "0.2.2-rc.5",
40
+ "@unieai/rabi-tools": "0.2.2-rc.5",
41
+ "@unieai/cordis": "4.1.0",
42
+ "@unieai/rabi-working-directory": "0.2.2-rc.5"
38
43
  }
39
44
  }
@@ -0,0 +1,31 @@
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
+
8
+ import type { JobOutputSource } from '@unieai/rabi-jobs'
9
+ import type { TerminalSendOperation } from '@unieai/rabi-terminal'
10
+ import { renderSendRead } from './render.ts'
11
+
12
+ /**
13
+ * Adapt the backend's consuming send reader to a registry pull source. The
14
+ * reader has no offsets of its own — each call hands over what arrived since
15
+ * the previous one — so the source counts the bytes it delivered to keep the
16
+ * registry's cursor monotonic. It binds lazily because the send starts inside
17
+ * the job starter, after the registry admitted the job; a read before that
18
+ * point delivers nothing.
19
+ * @param operation - the live send, once the starter has begun it.
20
+ * @returns one unlabeled source over the send's bounded delta.
21
+ */
22
+ export function sendSource(operation: () => TerminalSendOperation | undefined): JobOutputSource {
23
+ return {
24
+ read: (fromByte) => {
25
+ const live = operation()
26
+ if (live === undefined) return { text: '', nextOffset: fromByte, lossy: false }
27
+ const text = renderSendRead(live.readOutput())
28
+ return { text, nextOffset: fromByte + Buffer.byteLength(text), lossy: false }
29
+ },
30
+ }
31
+ }
package/src/index.ts ADDED
@@ -0,0 +1,409 @@
1
+ /**
2
+ * Six model-facing persistent terminal tools. Owner identity comes from the exact
3
+ * tool execution Agent; generic `ctx.jobs` owns background ids and collection.
4
+ * @module @unieai/rabi-tool-terminal
5
+ */
6
+
7
+ import type {} from '@unieai/rabi-working-directory'
8
+ import { resolve } from 'node:path'
9
+ import { Context } from '@unieai/cordis'
10
+ import z from '@unieai/schemastery'
11
+ import type { Agent } from '@unieai/rabi-agent'
12
+ import type { ContentBlock } from '@unieai/rabi-llm'
13
+ import { TerminalSessionId } from '@unieai/rabi-terminal'
14
+ import type { TerminalSendOperation, TerminalSendResult, TerminalSessionId as TerminalSessionIdType, TerminalSignal } from '@unieai/rabi-terminal'
15
+ import type {} from '@unieai/rabi-jobs'
16
+ import { defineTool } from '@unieai/rabi-tools'
17
+ import type { ToolDefinition } from '@unieai/rabi-tools'
18
+ import { sendSource } from './background.ts'
19
+ import { boundTerminalText, renderList, renderRead, renderSend, renderSpawn } from './render.ts'
20
+
21
+ declare module '@unieai/rabi-jobs' {
22
+ interface JobKindMap {
23
+ 'pty-send': 'pty-send'
24
+ }
25
+ }
26
+
27
+ /** Cordis plugin name. */
28
+ export const name = 'tool-terminal'
29
+ /** Required capability, registry, and prompt services. */
30
+ export const inject = ['terminals', 'tools', 'systemPrompt', 'workingDirectory']
31
+
32
+ /** Default cap for one complete model-facing terminal result. */
33
+ export const DEFAULT_MAX_RESULT_BYTES = 256 * 1024
34
+ /** Smallest cap that preserves registry-issued PTY and job ids in creation acknowledgements. */
35
+ export const MIN_MAX_RESULT_BYTES = 64
36
+
37
+ /** Model-facing terminal tool configuration. */
38
+ export interface Config {
39
+ /** Expose `run_in_background` and accept background sends (default true). */
40
+ enableRunInBackground?: boolean
41
+ /** Maximum UTF-8 bytes in one complete terminal or task-output result. */
42
+ maxResultBytes?: number
43
+ }
44
+
45
+ /** Schemastery configuration for the terminal tool consumer. */
46
+ export const Config: z<Config> = z.object({
47
+ enableRunInBackground: z.boolean().default(true),
48
+ maxResultBytes: z.number().step(1).min(MIN_MAX_RESULT_BYTES).max(Number.MAX_SAFE_INTEGER).default(DEFAULT_MAX_RESULT_BYTES),
49
+ })
50
+
51
+ interface SpawnArgs {
52
+ type: string
53
+ name?: string
54
+ cwd?: string
55
+ }
56
+
57
+ interface SessionArgs {
58
+ sessionId: string
59
+ }
60
+
61
+ interface SendArgs extends SessionArgs {
62
+ text: string
63
+ submit?: boolean
64
+ run_in_background?: boolean
65
+ }
66
+
67
+ interface ReadArgs extends SessionArgs {
68
+ offset?: number
69
+ count?: number
70
+ }
71
+
72
+ interface SignalArgs extends SessionArgs {
73
+ signal: TerminalSignal
74
+ }
75
+
76
+ const SESSION_STATUS_SCHEMA = {
77
+ oneOf: [
78
+ {
79
+ type: 'object',
80
+ additionalProperties: false,
81
+ properties: {
82
+ kind: { type: 'string', required: true, const: 'running' },
83
+ },
84
+ },
85
+ {
86
+ type: 'object',
87
+ additionalProperties: false,
88
+ properties: {
89
+ kind: { type: 'string', required: true, const: 'exited' },
90
+ exitCode: { required: true, oneOf: [{ type: 'integer' }, { type: 'null' }] },
91
+ signal: { required: true, oneOf: [{ type: 'string' }, { type: 'null' }] },
92
+ },
93
+ },
94
+ ],
95
+ } as const
96
+
97
+ const SESSION_SNAPSHOT_PROPERTIES = {
98
+ sessionId: { type: 'string', required: true },
99
+ name: { type: 'string' },
100
+ type: { type: 'string', required: true },
101
+ pid: { type: 'integer' },
102
+ status: { ...SESSION_STATUS_SCHEMA, required: true },
103
+ } as const
104
+
105
+ const SESSION_SNAPSHOT_SCHEMA = {
106
+ type: 'object',
107
+ additionalProperties: false,
108
+ properties: SESSION_SNAPSHOT_PROPERTIES,
109
+ } as const
110
+
111
+ const BACKGROUND_JOB_OUTPUT_SCHEMA = {
112
+ type: 'object',
113
+ additionalProperties: false,
114
+ properties: {
115
+ kind: { type: 'string', required: true, const: 'background' },
116
+ jobId: { type: 'string', required: true },
117
+ },
118
+ } as const
119
+
120
+ function requireAgent(agent: Agent | undefined): Agent {
121
+ if (agent === undefined) throw new Error('terminal tools require an initiating agent')
122
+ return agent
123
+ }
124
+
125
+ function sessionId(args: SessionArgs): TerminalSessionIdType {
126
+ if (args.sessionId.length === 0) {
127
+ throw new Error('sessionId must be a non-empty string')
128
+ }
129
+ return TerminalSessionId(args.sessionId)
130
+ }
131
+
132
+ function textResult(text: string, maxBytes: number): ContentBlock[] {
133
+ return [{ type: 'text', text: boundTerminalText(text, maxBytes) }]
134
+ }
135
+
136
+ function rawContentText(content: readonly ContentBlock[]): string | undefined {
137
+ if (content.length !== 1) return undefined
138
+ const block = content[0]
139
+ return block?.type === 'text' ? block.text : undefined
140
+ }
141
+
142
+ function sendDetail(result: TerminalSendResult): string {
143
+ return result.sessionStatus.kind === 'running'
144
+ ? `wait: ${result.waitReason}`
145
+ : `session exited: ${result.sessionStatus.exitCode ?? result.sessionStatus.signal ?? 'unknown'}`
146
+ }
147
+
148
+ /** Register all terminal tools and the minimal usage guidance. */
149
+ export function apply(ctx: Context, config: Config = {}): void {
150
+ const enableRunInBackground = config.enableRunInBackground ?? true
151
+ const maxResultBytes = config.maxResultBytes ?? DEFAULT_MAX_RESULT_BYTES
152
+ if (!Number.isSafeInteger(maxResultBytes) || maxResultBytes < MIN_MAX_RESULT_BYTES) {
153
+ throw new Error(`tool-terminal: maxResultBytes must be a safe integer of at least ${MIN_MAX_RESULT_BYTES}`)
154
+ }
155
+ const finalizeContent: NonNullable<ToolDefinition['finalizeContent']> = (_exec, result) => {
156
+ const raw = rawContentText(result.content)
157
+ return raw === undefined ? undefined : textResult(raw, maxResultBytes)
158
+ }
159
+ ctx.systemPrompt.section({
160
+ name: 'tool:pty',
161
+ order: ctx.systemPrompt.getSectionOrder('TOOL_PTY'),
162
+ 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.',
163
+ })
164
+
165
+ ctx.tools.register(defineTool({
166
+ name: 'terminal_open',
167
+ 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.',
168
+ parameters: {
169
+ type: { type: 'string', required: true, description: 'Registered terminal backend type, usually "shell".' },
170
+ name: { type: 'string', description: 'Optional owner-local display name such as "main" or "gdb".' },
171
+ cwd: { type: 'string', description: 'Initial working directory, relative to the Session current directory when not absolute.' },
172
+ },
173
+ finalizeContent,
174
+ output: {
175
+ schema: {
176
+ type: 'object',
177
+ additionalProperties: false,
178
+ properties: {
179
+ ...SESSION_SNAPSHOT_PROPERTIES,
180
+ motd: { type: 'string', required: true },
181
+ },
182
+ },
183
+ render: (_args, value) => [{ type: 'text', text: renderSpawn(value, maxResultBytes) }],
184
+ },
185
+ async execute(args: SpawnArgs, exec) {
186
+ if (args.type.length === 0) throw new Error('type must be a non-empty string')
187
+ const owner = requireAgent(exec.agent)
188
+ const cwd = await ctx.workingDirectory.ensure(owner, exec.signal)
189
+ const result = await ctx.terminals.spawn(owner, {
190
+ type: args.type,
191
+ ...args.name !== undefined ? { name: args.name } : {},
192
+ cwd: args.cwd === undefined ? cwd : resolve(cwd, args.cwd),
193
+ }, exec.signal)
194
+ return result
195
+ },
196
+ presentCall: (args) => {
197
+ const parsed = args
198
+ return { card: 'generic', title: `Open terminal ${parsed.name ?? parsed.type}`, kind: 'execute' }
199
+ },
200
+ }))
201
+
202
+ ctx.tools.register(defineTool({
203
+ name: 'terminal_send',
204
+ 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.'
205
+ + (enableRunInBackground ? ' Background mode returns a job id for job_output/job_kill.' : ''),
206
+ parameters: {
207
+ sessionId: { type: 'string', required: true, description: 'Terminal session id returned by terminal_open or terminal_list.' },
208
+ text: { type: 'string', required: true, description: 'UTF-8 text to write to the terminal.' },
209
+ submit: { type: 'boolean', description: 'Submit Enter after text (default true). Set false for control characters or incomplete REPL input.' },
210
+ ...enableRunInBackground
211
+ ? { run_in_background: { type: 'boolean' as const, description: 'Return a job id immediately; collect with job_output or stop with job_kill.' } }
212
+ : {},
213
+ },
214
+ finalizeContent,
215
+ output: {
216
+ schema: {
217
+ oneOf: [
218
+ BACKGROUND_JOB_OUTPUT_SCHEMA,
219
+ {
220
+ type: 'object',
221
+ additionalProperties: false,
222
+ properties: {
223
+ kind: { type: 'string', required: true, const: 'foreground' },
224
+ viewport: { type: 'string', required: true },
225
+ waitReason: {
226
+ type: 'string',
227
+ required: true,
228
+ enum: ['stdin_read', 'inferred_idle', 'timeout', 'session_exit'],
229
+ },
230
+ sessionStatus: { ...SESSION_STATUS_SCHEMA, required: true },
231
+ truncated: { type: 'boolean', required: true },
232
+ },
233
+ },
234
+ ],
235
+ },
236
+ render: (_args, value) => [{
237
+ type: 'text',
238
+ text: value.kind === 'background'
239
+ ? `started background job ${value.jobId}`
240
+ : renderSend(value, maxResultBytes),
241
+ }],
242
+ presentationMeta: (_args, value) => value.kind === 'foreground'
243
+ ? {
244
+ viewport: value.viewport,
245
+ waitReason: value.waitReason,
246
+ sessionStatus: value.sessionStatus,
247
+ truncated: value.truncated,
248
+ }
249
+ : null,
250
+ },
251
+ async execute(args: SendArgs, exec) {
252
+ const owner = requireAgent(exec.agent)
253
+ const id = sessionId(args)
254
+ const request = { text: args.text, submit: args.submit ?? true }
255
+ if (args.run_in_background === true) {
256
+ if (!enableRunInBackground) throw new Error('background terminal sends are disabled by tool-terminal configuration')
257
+ const jobs = ctx.get('jobs')
258
+ if (jobs === undefined) throw new Error('background terminal sends require @unieai/rabi-jobs and @unieai/rabi-tool-jobs')
259
+ let cancelRequested = false
260
+ let operation: TerminalSendOperation | undefined
261
+ const jobId = jobs.start({
262
+ kind: 'pty-send',
263
+ label: `${id}: ${args.text || '(input)'}`,
264
+ toolCall: { callId: exec.callId, rootCallId: exec.rootCallId },
265
+ owner: owner.id,
266
+ outputLimitBytes: maxResultBytes,
267
+ output: [sendSource(() => operation)],
268
+ run: () => {
269
+ const started = ctx.terminals.startSend(owner, id, request)
270
+ operation = started
271
+ return {
272
+ cancel: () => {
273
+ cancelRequested = true
274
+ started.cancel()
275
+ },
276
+ done: started.done.then(
277
+ result => ({ status: cancelRequested ? 'killed' as const : 'completed' as const, detail: sendDetail(result) }),
278
+ (error: unknown) => ({ status: 'failed' as const, detail: String(error) }),
279
+ ),
280
+ }
281
+ },
282
+ })
283
+ return { kind: 'background' as const, jobId }
284
+ }
285
+ const operation = ctx.terminals.startSend(owner, id, { ...request, signal: exec.signal })
286
+ const result = await operation.done
287
+ if (exec.signal.aborted) throw new Error('terminal send aborted')
288
+ return { kind: 'foreground' as const, ...result }
289
+ },
290
+ presentCall(args) {
291
+ const parsed = args as Partial<SendArgs>
292
+ if (parsed.run_in_background === true) {
293
+ return { card: 'generic', title: `Send to terminal ${parsed.sessionId as string} in background`, kind: 'execute', rawInput: parsed.text }
294
+ }
295
+ // Keep these Host-only fallbacks aligned with the conversation locale
296
+ // keys `terminal.sendInput` and `terminal.session` used by Web.
297
+ return { card: 'terminal', title: parsed.text || '(send input)', description: `Terminal ${parsed.sessionId as string}` }
298
+ },
299
+ presentResult(args, result) {
300
+ if ((args as Partial<SendArgs>).run_in_background === true || result.isError) return undefined
301
+ const raw = rawContentText(result.content)
302
+ return raw === undefined ? undefined : { card: 'terminal', output: raw }
303
+ },
304
+ }))
305
+
306
+ ctx.tools.register(defineTool({
307
+ name: 'terminal_read',
308
+ description: 'Read a bounded page of retained output from a persistent terminal without sending input.',
309
+ parameters: {
310
+ sessionId: { type: 'string', required: true, description: 'Terminal session id.' },
311
+ offset: { type: 'number', description: 'Newest-relative line offset (default 0).' },
312
+ count: { type: 'number', description: 'Requested line count (default 500; backend caps apply).' },
313
+ },
314
+ finalizeContent,
315
+ output: {
316
+ schema: {
317
+ type: 'object',
318
+ additionalProperties: false,
319
+ properties: {
320
+ text: { type: 'string', required: true },
321
+ totalLines: { type: 'integer', required: true },
322
+ lineBegin: { type: 'integer', required: true },
323
+ lineEnd: { type: 'integer', required: true },
324
+ truncated: { type: 'boolean', required: true },
325
+ },
326
+ },
327
+ render: (_args, value) => [{ type: 'text', text: renderRead(value, maxResultBytes) }],
328
+ },
329
+ execute(args: ReadArgs, exec) {
330
+ const result = ctx.terminals.read(requireAgent(exec.agent), sessionId(args), {
331
+ ...args.offset !== undefined ? { offset: args.offset } : {},
332
+ ...args.count !== undefined ? { count: args.count } : {},
333
+ })
334
+ return Promise.resolve(result)
335
+ },
336
+ presentCall: args => ({ card: 'generic', title: `Read terminal ${(args).sessionId}`, kind: 'read', rawInput: args }),
337
+ }))
338
+
339
+ ctx.tools.register(defineTool({
340
+ name: 'terminal_signal',
341
+ description: 'Send an allowed signal to the current foreground process group of a persistent terminal.',
342
+ parameters: {
343
+ sessionId: { type: 'string', required: true, description: 'Terminal session id.' },
344
+ signal: { type: 'string', required: true, enum: ['SIGINT', 'SIGTERM', 'SIGKILL', 'SIGTSTP', 'SIGHUP'], description: 'Signal to deliver. Shell-targeted SIGKILL is rejected; use terminal_close.' },
345
+ },
346
+ finalizeContent,
347
+ output: {
348
+ schema: {
349
+ type: 'object',
350
+ additionalProperties: false,
351
+ properties: {
352
+ delivered: { type: 'boolean', required: true, const: true },
353
+ targetPgid: { type: 'integer', required: true },
354
+ },
355
+ },
356
+ render: (args, value) => [{ type: 'text', text: `delivered ${args.signal} to foreground process group ${value.targetPgid}` }],
357
+ },
358
+ async execute(args: SignalArgs, exec) {
359
+ return ctx.terminals.signal(requireAgent(exec.agent), sessionId(args), args.signal)
360
+ },
361
+ presentCall: args => ({ card: 'generic', title: `Signal terminal ${args.sessionId}`, kind: 'execute', rawInput: args }),
362
+ }))
363
+
364
+ ctx.tools.register(defineTool({
365
+ name: 'terminal_close',
366
+ description: 'Close one persistent terminal and wait until its captured owned process tree is gone.',
367
+ parameters: {
368
+ sessionId: { type: 'string', required: true, description: 'Terminal session id.' },
369
+ },
370
+ finalizeContent,
371
+ output: {
372
+ schema: {
373
+ type: 'object',
374
+ additionalProperties: false,
375
+ properties: {
376
+ sessionId: { type: 'string', required: true },
377
+ outcome: { type: 'string', required: true, enum: ['closed', 'already-closing'] },
378
+ },
379
+ },
380
+ render: (_args, value) => [{
381
+ type: 'text',
382
+ text: value.outcome === 'closed'
383
+ ? `closed terminal session ${value.sessionId}`
384
+ : `terminal session ${value.sessionId} was already closing`,
385
+ }],
386
+ },
387
+ async execute(args: SessionArgs, exec) {
388
+ const id = sessionId(args)
389
+ const closed = await ctx.terminals.kill(requireAgent(exec.agent), id)
390
+ return { sessionId: id, outcome: closed ? 'closed' as const : 'already-closing' as const }
391
+ },
392
+ presentCall: args => ({ card: 'generic', title: `Close terminal ${(args).sessionId}`, kind: 'delete' }),
393
+ }))
394
+
395
+ ctx.tools.register(defineTool({
396
+ name: 'terminal_list',
397
+ description: 'List persistent terminal sessions owned by the current agent.',
398
+ parameters: {},
399
+ finalizeContent,
400
+ output: {
401
+ schema: { type: 'array', items: SESSION_SNAPSHOT_SCHEMA },
402
+ render: (_args, value) => [{ type: 'text', text: renderList(value, maxResultBytes) }],
403
+ },
404
+ execute(_args: Record<string, never>, exec) {
405
+ return Promise.resolve(ctx.terminals.list(requireAgent(exec.agent)))
406
+ },
407
+ presentCall: () => ({ card: 'generic', title: 'List terminal sessions', kind: 'read' }),
408
+ }))
409
+ }
package/src/render.ts ADDED
@@ -0,0 +1,177 @@
1
+ /** Model and UI rendering for persistent terminal tool results. */
2
+
3
+ import { TextRetainer } from '@unieai/rabi-output-retention'
4
+
5
+ interface RenderedSessionStatusRunning {
6
+ kind: 'running'
7
+ }
8
+
9
+ interface RenderedSessionStatusExited {
10
+ kind: 'exited'
11
+ exitCode: number | null
12
+ signal: string | null
13
+ }
14
+
15
+ type RenderedSessionStatus = RenderedSessionStatusRunning | RenderedSessionStatusExited
16
+
17
+ interface RenderedSessionSnapshot {
18
+ sessionId: string
19
+ name?: string
20
+ type: string
21
+ pid?: number
22
+ status: RenderedSessionStatus
23
+ }
24
+
25
+ interface RenderedSpawnResult extends RenderedSessionSnapshot {
26
+ motd: string
27
+ }
28
+
29
+ interface RenderedSendResult {
30
+ viewport: string
31
+ waitReason: 'stdin_read' | 'inferred_idle' | 'timeout' | 'session_exit'
32
+ sessionStatus: RenderedSessionStatus
33
+ truncated: boolean
34
+ }
35
+
36
+ interface RenderedSendRead {
37
+ delta: string
38
+ truncated: boolean
39
+ }
40
+
41
+ interface RenderedReadResult {
42
+ text: string
43
+ totalLines: number
44
+ lineBegin: number
45
+ lineEnd: number
46
+ truncated: boolean
47
+ }
48
+
49
+ const encoder = new TextEncoder()
50
+ const TRUNCATED = '\n[output truncated]'
51
+
52
+ function byteLength(text: string): number {
53
+ return encoder.encode(text).byteLength
54
+ }
55
+
56
+ function retain(text: string, maxBytes: number, kind: 'head' | 'tail'): string {
57
+ const retainer = new TextRetainer({ kind, maxBytes })
58
+ retainer.push(text)
59
+ return retainer.finish().text
60
+ }
61
+
62
+ function fitWithSuffix(content: string, suffix: string, maxBytes: number): string {
63
+ const fixedBytes = byteLength(suffix)
64
+ if (fixedBytes >= maxBytes) return retain(suffix, maxBytes, 'tail')
65
+ return `${retain(content, maxBytes - fixedBytes, 'tail')}${suffix}`
66
+ }
67
+
68
+ function fitWithPrefix(prefix: string, content: string, maxBytes: number): string {
69
+ const fixed = `${prefix}${TRUNCATED}`
70
+ const fixedBytes = byteLength(fixed)
71
+ if (fixedBytes >= maxBytes) return retain(fixed, maxBytes, 'head')
72
+ return `${prefix}${retain(content, maxBytes - fixedBytes, 'tail')}${TRUNCATED}`
73
+ }
74
+
75
+ function boundBodyWithSuffix(
76
+ content: string,
77
+ metadata: string,
78
+ upstreamTruncated: boolean,
79
+ maxBytes: number,
80
+ ): string {
81
+ const suffix = `${metadata}${upstreamTruncated ? TRUNCATED : ''}`
82
+ const complete = `${content}${suffix}`
83
+ if (byteLength(complete) <= maxBytes) return complete
84
+ return fitWithSuffix(content, `${metadata}${TRUNCATED}`, maxBytes)
85
+ }
86
+
87
+ /**
88
+ * Bound one complete terminal acknowledgement while preserving UTF-8 cuts.
89
+ * @param text - complete acknowledgement text.
90
+ * @param maxBytes - positive final result cap.
91
+ * @returns bounded text with a truncation marker when it fits.
92
+ */
93
+ export function boundTerminalText(text: string, maxBytes: number): string {
94
+ if (byteLength(text) <= maxBytes) return text
95
+ const markerBytes = byteLength(TRUNCATED)
96
+ if (markerBytes >= maxBytes) return retain(TRUNCATED, maxBytes, 'tail')
97
+ return `${retain(text, maxBytes - markerBytes, 'head')}${TRUNCATED}`
98
+ }
99
+
100
+ /**
101
+ * Render one created session and its bounded MOTD.
102
+ * @param result - published spawn result.
103
+ * @param maxBytes - complete UTF-8 result cap.
104
+ * @returns Model-facing session acknowledgement.
105
+ */
106
+ export function renderSpawn(result: RenderedSpawnResult, maxBytes: number): string {
107
+ const label = result.name === undefined ? result.sessionId : `${result.sessionId} (${result.name})`
108
+ const prefix = `started terminal session ${label} [type: ${result.type}]\n`
109
+ const motd = result.motd || '(no startup output)'
110
+ const complete = `${prefix}${motd}`
111
+ return byteLength(complete) <= maxBytes ? complete : fitWithPrefix(prefix, motd, maxBytes)
112
+ }
113
+
114
+ /**
115
+ * Render one settled interactive send.
116
+ * @param result - settled send outcome.
117
+ * @param maxBytes - complete UTF-8 result cap.
118
+ * @returns Terminal output plus wait/session markers.
119
+ */
120
+ export function renderSend(result: RenderedSendResult, maxBytes: number): string {
121
+ const output = result.viewport || '(no new output)'
122
+ const status = result.sessionStatus.kind === 'running'
123
+ ? 'running'
124
+ : `exited code=${result.sessionStatus.exitCode ?? 'null'} signal=${result.sessionStatus.signal ?? 'null'}`
125
+ return boundBodyWithSuffix(
126
+ output,
127
+ `\n[wait: ${result.waitReason}]\n[session: ${status}]`,
128
+ result.truncated,
129
+ maxBytes,
130
+ )
131
+ }
132
+
133
+ /**
134
+ * Render one incremental background operation read.
135
+ * @param read - consuming operation delta.
136
+ * @returns Delta plus its upstream truncation marker. The generic task control
137
+ * applies the producer's complete-result cap after adding job status.
138
+ */
139
+ export function renderSendRead(read: RenderedSendRead): string {
140
+ const separator = read.delta.endsWith('\n') || read.delta.length === 0 ? '' : '\n'
141
+ return `${read.delta}${read.truncated ? `${separator}[output truncated]` : ''}`
142
+ }
143
+
144
+ /**
145
+ * Render one bounded historical page.
146
+ * @param result - retained scrollback page.
147
+ * @param maxBytes - complete UTF-8 result cap.
148
+ * @returns Page text plus pagination and truncation markers.
149
+ */
150
+ export function renderRead(result: RenderedReadResult, maxBytes: number): string {
151
+ const output = result.text || '(no retained output)'
152
+ return boundBodyWithSuffix(
153
+ output,
154
+ `\n[lines: ${result.lineBegin}-${result.lineEnd} of ${result.totalLines}]`,
155
+ result.truncated,
156
+ maxBytes,
157
+ )
158
+ }
159
+
160
+ /**
161
+ * Render owner-visible live sessions.
162
+ * @param sessions - fresh owner-scoped snapshots.
163
+ * @param maxBytes - complete UTF-8 result cap.
164
+ * @returns One line per session or the empty marker.
165
+ */
166
+ export function renderList(sessions: readonly RenderedSessionSnapshot[], maxBytes: number): string {
167
+ if (sessions.length === 0) return '(no terminal sessions)'
168
+ const text = sessions.map((session) => {
169
+ const name = session.name === undefined ? '' : ` (${session.name})`
170
+ const pid = session.pid === undefined ? '' : ` pid=${session.pid}`
171
+ const status = session.status.kind === 'running'
172
+ ? 'running'
173
+ : `exited code=${session.status.exitCode ?? 'null'} signal=${session.status.signal ?? 'null'}`
174
+ return `${session.sessionId}${name} [${session.type}] ${status}${pid}`
175
+ }).join('\n')
176
+ return boundBodyWithSuffix(text, '', false, maxBytes)
177
+ }