@tduyng/pi-shell 0.0.0-stage → 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,178 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ Use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ Copyright 2026 tduyng
package/README.md CHANGED
@@ -1,3 +1,67 @@
1
- # Temporary Holding Version
1
+ # @tduyng/pi-shell
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
+ Background shell execution for pi. One `bg` tool covers the full lifecycle: start, read output, kill, and list tasks.
4
+
5
+ ## The bg tool
6
+
7
+ A single tool with an `action` field. Each `bg` task runs in the current working directory with a fresh shell, like pi's own bash. There is no persistent shell session.
8
+
9
+ ### start
10
+
11
+ Spawns a detached command. Returns `task_id` (8-char UUID prefix), `pid`, and the absolute `log` path. stdout and stderr stream to a log file at `<agentDir>/shell-logs/<taskId>.log`. The task runs silently until you ask about it. Optional `timeout` caps the task (max 600 seconds). Default is no timeout.
12
+
13
+ ### output
14
+
15
+ Reads new bytes since the last read using a byte cursor. The `wait` parameter controls behavior:
16
+
17
+ - `"now"`: returns immediately with whatever is available.
18
+ - `"next_write"`: parks the agent until the first new byte appears, then wakes it with the new output.
19
+ - `"exit"`: parks the agent until the process ends, then delivers the verdict plus the unread tail.
20
+
21
+ The cursor never advances on wake reads, so a later `bg` output call still sees every byte from the stored offset onward.
22
+
23
+ ### kill
24
+
25
+ Sends SIGTERM to the process group, polls every 50ms for up to 1 second, then escalates to SIGKILL. Accepts `task_id`, raw `pid`, or `port` (resolved to a pid via `lsof -ti`).
26
+
27
+ ### status
28
+
29
+ Lists all tasks with id, pid, state (running, exited, killed), cursor offset, and the first 80 characters of the command.
30
+
31
+ ## Honest exits
32
+
33
+ Pi 0.99 already reports a signal-killed command as a failure. Its bash backend returns `128 + signal` for a child that died without an exit code, and raises when a command ends with neither an exit code nor a signal. This extension does not override that backend.
34
+
35
+ `shell-process.test.ts` runs `kill -9` against pi's own bash tool and asserts a nonzero result in the 128+n family, so a pi release that reintroduces the silent success fails here.
36
+
37
+ A `tool_result` handler annotates the two cases where the exit code alone cannot tell the model what happened. An exit 1 from `grep`, `rg`, or `find` means no matches, and a command killed by its timeout did not finish cleanly. Each note stops the model from retrying a search that already succeeded.
38
+
39
+ ## Middle-out output view
40
+
41
+ Large logs are truncated to a head and tail, defaulting to 8KB total, with an exact omitted-byte count in between. The read window per side is 16KB, split on UTF-8 sequence boundaries so characters are never cut mid-byte. The full log stays on disk at the path always shown in results.
42
+
43
+ ## Wake on exit
44
+
45
+ Only a task the model parked on (via `wait: "exit"` or `wait: "next_write"`) injects a user message when it finishes. A burst of exits coalesces into one message sharing a byte budget: default 8KB total, minimum 1KB per task. The wake carries the exit verdict, the unread tail, and the full log path per task, so the model gets the result without a read-back.
46
+
47
+ The wake fires from the `onExit` callback via `queueMicrotask`, not from polling. If the agent is mid-turn, the wake lands in the follow-up queue and is delivered at the next `agent_settled` boundary.
48
+
49
+ ## Footer indicator
50
+
51
+ The footer shows a dot and the live task count (e.g. "2 bg running") while any background task is active. It clears when the last task exits.
52
+
53
+ ## Task lifecycle
54
+
55
+ Each `bg` task is in-memory only. It dies with the pi process. Persisted session entries record the command, log path, and start time so the model can read the log after a reload. The live process handle is gone. Detached grandchildren that inherit the shell's stdout keep writing to the log after the shell exits. The log stream stays open until both the stdout and stderr pipes close. Ending it on the first close would drop data the second pipe still delivers.
56
+
57
+ ## Install
58
+
59
+ ```bash
60
+ pi install npm:@tduyng/pi-shell
61
+ ```
62
+
63
+ Local checkout: `pi install /path/to/dotfiles/pi/agent/extensions/pi-shell`
64
+
65
+ ## Configure
66
+
67
+ - `SHELL`: set to `0`, `false`, `no`, or `off` to disable the extension entirely.
package/package.json CHANGED
@@ -1,6 +1,45 @@
1
1
  {
2
2
  "name": "@tduyng/pi-shell",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.0.1",
4
+ "description": "Background processes the agent parks on: one bg tool with start/output/kill/status, cursor reads that never re-read bytes, and a runtime wake-up when a task exits.",
5
+ "keywords": [
6
+ "pi",
7
+ "pi-package",
8
+ "pi-extension",
9
+ "pi-coding-agent",
10
+ "shell",
11
+ "background",
12
+ "process"
13
+ ],
14
+ "homepage": "https://gitlab.com/tduyng/pi-agent/-/tree/main/extensions/pi-shell#readme",
15
+ "bugs": "https://gitlab.com/tduyng/pi-agent/-/issues",
16
+ "license": "Apache-2.0",
17
+ "author": "tduyng",
18
+ "repository": {
19
+ "type": "git",
20
+ "url": "git+https://gitlab.com/tduyng/pi-agent.git",
21
+ "directory": "extensions/pi-shell"
22
+ },
23
+ "type": "module",
24
+ "files": [
25
+ "src",
26
+ "!src/**/*.test.ts",
27
+ "README.md",
28
+ "LICENSE"
29
+ ],
30
+ "peerDependencies": {
31
+ "@earendil-works/pi-ai": "*",
32
+ "@earendil-works/pi-coding-agent": "*"
33
+ },
34
+ "publishConfig": {
35
+ "access": "public"
36
+ },
37
+ "pi": {
38
+ "extensions": [
39
+ "./src/index.ts"
40
+ ]
41
+ },
42
+ "dependencies": {
43
+ "ata-validator": "^1.62.1"
44
+ }
45
+ }
package/src/index.ts ADDED
@@ -0,0 +1,385 @@
1
+ import { Validator, type Infer } from 'ata-validator'
2
+ import { t } from 'ata-validator/t'
3
+
4
+ import {
5
+ isBashToolResult,
6
+ type AgentToolResult,
7
+ type ExtensionAPI,
8
+ type ExtensionContext
9
+ } from '@earendil-works/pi-coding-agent'
10
+
11
+ interface ToolResultPatch {
12
+ content: (import('@earendil-works/pi-ai').TextContent | import('@earendil-works/pi-ai').ImageContent)[]
13
+ }
14
+
15
+ import {
16
+ killTask,
17
+ middleOut,
18
+ benignExitNote,
19
+ pidForPort,
20
+ readNewBytes,
21
+ readUnreadTail,
22
+ registry,
23
+ spawnTask,
24
+ watchForWrite
25
+ } from './process.js'
26
+ import type { TaskRecord } from './process.js'
27
+ const isString = new Validator(t.string()).isValidObject
28
+
29
+ const OUTPUT_VIEW_MAX_BYTES = 8 * 1024
30
+ const WAKE_TAIL_MAX_BYTES = 8 * 1024
31
+ const MIN_WAKE_TAIL_BYTES = 1024
32
+
33
+ const STATE_TYPE = 'shell'
34
+ const WAKE_TYPE = 'shell-wake'
35
+ const ENABLED = !/^(0|false|no|off)$/i.test(process.env['SHELL'] ?? '')
36
+ const LOG_PREFIX = 'Full log: '
37
+
38
+ const bgSchema = t.object({
39
+ action: t.string({ enum: ['start', 'output', 'kill', 'status'] }),
40
+ command: t.optional(t.string()),
41
+ timeout: t.optional(t.number()),
42
+ task_id: t.optional(t.string()),
43
+ from_offset: t.optional(t.number()),
44
+ wait: t.optional(t.union([t.literal('now'), t.literal('next_write'), t.literal('exit')])),
45
+ pid: t.optional(t.number()),
46
+ port: t.optional(t.number())
47
+ })
48
+
49
+ type BgInput = Infer<typeof bgSchema>
50
+
51
+ function describeExit(exitCode: number | null, signal: string | null): string {
52
+ if (exitCode !== null) {
53
+ if (exitCode === 0) return 'exited 0'
54
+ return `exited ${exitCode}`
55
+ }
56
+ if (signal) {
57
+ const match = /^(SIG[A-Z]+)\s*\((.*)\)$/.exec(signal)
58
+ if (match) {
59
+ return `killed (${match[1]}, ${match[2]})`
60
+ }
61
+ if (signal.startsWith('SIGKILL')) return `killed (${signal})`
62
+ if (signal.startsWith('SIGTERM')) return `terminated (${signal})`
63
+ return `killed by ${signal}`
64
+ }
65
+ return 'exited (unknown status)'
66
+ }
67
+
68
+ function textResult(text: string): AgentToolResult<unknown> {
69
+ return { content: [{ type: 'text', text }], details: {} }
70
+ }
71
+
72
+ export function owedWakes(): TaskRecord[] {
73
+ return registry
74
+ .all()
75
+ .filter((rec) => rec.wakeRequested && !rec.wakeSent && (rec.exitCode !== null || rec.signal !== null))
76
+ }
77
+
78
+ export async function buildWakeText(records: TaskRecord[], budget = WAKE_TAIL_MAX_BYTES): Promise<string> {
79
+ const share = Math.max(MIN_WAKE_TAIL_BYTES, Math.floor(budget / records.length))
80
+ const blocks: string[] = []
81
+ for (const rec of records) {
82
+ const benign = isBenignNoMatch(rec) ? ' (no matches found, not an error)' : ''
83
+ const note = describeExit(rec.exitCode, rec.signal)
84
+ let tailText = ''
85
+ try {
86
+ const tail = await readUnreadTail(rec.taskId, share)
87
+ if (tail.text) {
88
+ const omitted = tail.end - tail.start - Buffer.byteLength(tail.text)
89
+ tailText = omitted > 0 ? `\n${tail.text}\n[${omitted} bytes omitted, middle cut]` : `\n${tail.text}`
90
+ }
91
+ } catch {}
92
+ blocks.push(`bg task ${rec.taskId} ${note}${benign}.${tailText}\n${LOG_PREFIX}${rec.logPath}`)
93
+ }
94
+ return blocks.join('\n\n')
95
+ }
96
+
97
+ export async function sendBackgroundWake(pi: Pick<ExtensionAPI, 'sendMessage'>, text: string): Promise<void> {
98
+ pi.sendMessage(
99
+ { customType: WAKE_TYPE, content: text, display: true },
100
+ { deliverAs: 'followUp', triggerTurn: true }
101
+ )
102
+ }
103
+
104
+ async function flushWakes(pi: ExtensionAPI): Promise<boolean> {
105
+ const owed = owedWakes()
106
+ if (owed.length === 0) return false
107
+ const text = await buildWakeText(owed)
108
+ try {
109
+ await sendBackgroundWake(pi, text)
110
+ for (const rec of owed) rec.wakeSent = true
111
+ return true
112
+ } catch {
113
+ return false
114
+ }
115
+ }
116
+
117
+ function isBenignNoMatch(rec: Pick<TaskRecord, 'command' | 'exitCode' | 'signal'>): boolean {
118
+ if (rec.exitCode !== 1 || rec.signal !== null) return false
119
+ const cmd = rec.command.trim()
120
+ return /^(grep|rg|find)\b/.test(cmd) || /\b(grep|rg)\b/.test(cmd)
121
+ }
122
+
123
+ interface PersistedTask {
124
+ taskId: string
125
+ command: string
126
+ logPath: string
127
+ startedAt: number
128
+ }
129
+
130
+ const StructuredResultSchema = t.object({ exit_code: t.optional(t.number()) }, { additionalProperties: true })
131
+ const isStructuredResultSchema = new Validator(StructuredResultSchema).isValidObject
132
+
133
+ const PersistedTaskSchema = t.object({
134
+ taskId: t.string({ minLength: 1 }),
135
+ command: t.string(),
136
+ logPath: t.string(),
137
+ startedAt: t.number()
138
+ })
139
+ const isPersistedTaskSchema = new Validator(PersistedTaskSchema).isValidObject
140
+
141
+ function isPersistedTask(value: unknown): value is PersistedTask {
142
+ return isPersistedTaskSchema(value)
143
+ }
144
+
145
+ function reconstructTasks(ctx: ExtensionContext): void {
146
+ for (const entry of ctx.sessionManager.getBranch()) {
147
+ if (entry.type !== 'custom' || entry.customType !== STATE_TYPE) continue
148
+ if (!isPersistedTask(entry.data)) continue
149
+ const task = entry.data
150
+ if (registry.has(task.taskId)) continue
151
+ registry.set(task.taskId, {
152
+ taskId: task.taskId,
153
+ pid: 0,
154
+ command: task.command,
155
+ logPath: task.logPath,
156
+ offset: 0,
157
+ exitCode: null,
158
+ signal: 'session ended',
159
+ wakeRequested: false,
160
+ wakeSent: true,
161
+ startedAt: task.startedAt,
162
+ exitWaiters: new Set()
163
+ })
164
+ }
165
+ }
166
+
167
+ async function bgAction(pi: ExtensionAPI, ctx: ExtensionContext, params: BgInput): Promise<AgentToolResult<unknown>> {
168
+ const rec = params.task_id !== undefined ? registry.get(params.task_id) : undefined
169
+ if (params.action === 'output') {
170
+ if (!rec) throw new Error(`No such task: ${params.task_id}`)
171
+ const from = params.from_offset ?? rec.offset
172
+ const wait = params.wait ?? 'now'
173
+ const read = await readNewBytes(params.task_id!, from)
174
+ const view = middleOut(read.text, OUTPUT_VIEW_MAX_BYTES)
175
+ const omittedNote =
176
+ view.omitted > 0 ? `\n[${view.omitted} bytes omitted, middle cut. Full log: ${rec.logPath}]` : ''
177
+ const body = view.head + (view.omitted > 0 ? `\n...\n${view.tail}` : view.tail)
178
+
179
+ if (wait === 'exit' && (rec.exitCode !== null || rec.signal !== null)) {
180
+ rec.wakeSent = true
181
+ const benign = isBenignNoMatch(rec) ? ' (no matches found, not an error)' : ''
182
+ return textResult(
183
+ `task ${params.task_id} ${describeExit(rec.exitCode, rec.signal)}${benign}. ` +
184
+ `bytes ${read.start}-${read.end} of ${read.size} since offset ${from}.\n` +
185
+ `${body || '(no new output)'}${omittedNote}\n${LOG_PREFIX}${rec.logPath}`
186
+ )
187
+ }
188
+
189
+ if (wait === 'now') {
190
+ if (rec.exitCode !== null || rec.signal !== null) {
191
+ rec.wakeSent = true
192
+ }
193
+ return textResult(
194
+ `task ${params.task_id}: bytes ${read.start}-${read.end} of ${read.size}\n` +
195
+ `${body || '(no new output)'}${omittedNote}\n${LOG_PREFIX}${rec.logPath}`
196
+ )
197
+ }
198
+
199
+ if (wait === 'next_write') {
200
+ const controller = watchForWrite(
201
+ params.task_id!,
202
+ read.end,
203
+ (text, start, end, size) => {
204
+ const v = middleOut(text, OUTPUT_VIEW_MAX_BYTES)
205
+ const omitted =
206
+ v.omitted > 0 ? `\n[${v.omitted} bytes omitted, middle cut. Full log: ${rec.logPath}]` : ''
207
+ void sendBackgroundWake(
208
+ pi,
209
+ `bg task ${params.task_id} wrote new output (bytes ${start}-${end} of ${size}).\n` +
210
+ `${v.head}${v.omitted > 0 ? `\n...\n${v.tail}` : v.tail}${omitted}\n${LOG_PREFIX}${rec.logPath}`
211
+ ).catch(() => undefined)
212
+ },
213
+ () => {
214
+ if (rec.exitCode === null && rec.signal === null) return
215
+ const benign = isBenignNoMatch(rec) ? ' (no matches found, not an error)' : ''
216
+ void sendBackgroundWake(
217
+ pi,
218
+ `bg task ${params.task_id} exited ${describeExit(rec.exitCode, rec.signal)}${benign} with no new output. ${LOG_PREFIX}${rec.logPath}`
219
+ ).catch(() => undefined)
220
+ }
221
+ )
222
+ ctx.signal?.addEventListener('abort', () => controller.abort(), { once: true })
223
+ return textResult(
224
+ `Watching task ${params.task_id} (bytes ${read.start}-${read.end} of ${read.size}). ` +
225
+ `The agent will be woken when new output appears. ${LOG_PREFIX}${rec.logPath}`
226
+ )
227
+ }
228
+
229
+ rec.wakeRequested = true
230
+ return textResult(
231
+ `Watching task ${params.task_id} (bytes ${read.start}-${read.end} of ${read.size}). ` +
232
+ `The agent will be woken when it exits. ${LOG_PREFIX}${rec.logPath}`
233
+ )
234
+ }
235
+
236
+ if (params.action === 'kill') {
237
+ if (params.task_id !== undefined) {
238
+ const target = registry.get(params.task_id)
239
+ if (!target) throw new Error(`No such task: ${params.task_id}`)
240
+ if (target.exitCode !== null || target.signal !== null) {
241
+ return textResult(
242
+ `Task ${params.task_id} already finished (${describeExit(target.exitCode, target.signal)}).`
243
+ )
244
+ }
245
+ target.wakeSent = true
246
+ killTask(params.task_id)
247
+ return textResult(`Sent SIGTERM to task ${params.task_id} (pid ${target.pid}).`)
248
+ }
249
+ if (params.pid !== undefined) {
250
+ const target = registry.all().find((r) => r.pid === params.pid)
251
+ if (!target) throw new Error(`pid ${params.pid} is not a background task of this session`)
252
+ if (target.exitCode !== null || target.signal !== null) {
253
+ return textResult(`pid ${params.pid} (task ${target.taskId}) already finished.`)
254
+ }
255
+ target.wakeSent = true
256
+ killTask(target.taskId)
257
+ return textResult(`Sent SIGTERM to pid ${params.pid} (task ${target.taskId}).`)
258
+ }
259
+ if (params.port !== undefined) {
260
+ const pid = await pidForPort(params.port)
261
+ if (pid === undefined) {
262
+ return textResult(`No process listening on port ${params.port}.`)
263
+ }
264
+ const target = registry.all().find((r) => r.pid === pid)
265
+ if (!target) throw new Error(`pid ${pid} on port ${params.port} is not a background task of this session`)
266
+ if (target.exitCode !== null || target.signal !== null) {
267
+ return textResult(`pid ${pid} on port ${params.port} (task ${target.taskId}) already finished.`)
268
+ }
269
+ target.wakeSent = true
270
+ killTask(target.taskId)
271
+ return textResult(`Sent SIGTERM to pid ${pid} on port ${params.port} (task ${target.taskId}).`)
272
+ }
273
+ throw new Error('bg action kill needs one of task_id, pid, or port')
274
+ }
275
+
276
+ const tasks = registry.all()
277
+ if (tasks.length === 0) {
278
+ return textResult('No background tasks.')
279
+ }
280
+ const lines = tasks.map((r) => {
281
+ const state = r.exitCode !== null || r.signal !== null ? describeExit(r.exitCode, r.signal) : 'running'
282
+ const benign = isBenignNoMatch(r) ? ' (no matches)' : ''
283
+ return `${r.taskId} ${r.pid} ${state}${benign} offset ${r.offset} ${r.command.slice(0, 80)}`
284
+ })
285
+ return textResult(lines.join('\n'))
286
+ }
287
+
288
+ let statusCtx: ExtensionContext | undefined
289
+
290
+ function refreshBgStatus(): void {
291
+ if (!statusCtx) return
292
+ try {
293
+ const running = registry.all().filter((r) => r.exitCode === null && r.signal === null).length
294
+ statusCtx.ui.setStatus('shell', running > 0 ? `● ${running} bg running` : undefined)
295
+ } catch {
296
+ statusCtx = undefined
297
+ }
298
+ }
299
+
300
+ function agentIsIdle(): boolean {
301
+ if (!statusCtx) return false
302
+ try {
303
+ return statusCtx.isIdle() && !statusCtx.hasPendingMessages()
304
+ } catch {
305
+ statusCtx = undefined
306
+ return false
307
+ }
308
+ }
309
+
310
+ export default function shellExtension(pi: ExtensionAPI): void {
311
+ if (!ENABLED) return
312
+
313
+ pi.on('session_start', async (_event, ctx) => {
314
+ reconstructTasks(ctx)
315
+ statusCtx = ctx
316
+ refreshBgStatus()
317
+ })
318
+ pi.on('session_tree', async (_event, ctx) => {
319
+ reconstructTasks(ctx)
320
+ statusCtx = ctx
321
+ refreshBgStatus()
322
+ })
323
+
324
+ pi.registerTool({
325
+ name: 'bg',
326
+ label: 'bg',
327
+ description:
328
+ 'Run background commands. start returns task_id, pid, and log path. output reads new bytes with wait now, next_write, or exit. kill stops by task_id, pid, or port. status lists tasks. Use for long commands.',
329
+ promptSnippet: 'Run background commands',
330
+ annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: false },
331
+ promptGuidelines: [
332
+ 'For long work, start it with bg, then request output with wait "exit" instead of polling a foreground shell.'
333
+ ],
334
+ parameters: bgSchema,
335
+ async execute(_toolCallId, params: BgInput, _signal, _onUpdate, ctx) {
336
+ if (params.action === 'start') {
337
+ if (!params.command) throw new Error('bg action start needs a command.')
338
+ statusCtx = ctx
339
+ const rec = spawnTask({
340
+ command: params.command,
341
+ cwd: ctx.cwd,
342
+ timeout: params.timeout,
343
+ onExit: () => {
344
+ queueMicrotask(() => {
345
+ refreshBgStatus()
346
+ if (!agentIsIdle()) return
347
+ void flushWakes(pi)
348
+ })
349
+ }
350
+ })
351
+ refreshBgStatus()
352
+ return textResult(
353
+ `task_id: ${rec.taskId}\npid: ${rec.pid}\nlog: ${rec.logPath}\n` +
354
+ `Started in background. Use bg (action output, wait "exit") to be woken when it finishes.`
355
+ )
356
+ }
357
+ return bgAction(pi, ctx, params)
358
+ }
359
+ })
360
+
361
+ pi.on('agent_settled', async (event, ctx) => {
362
+ statusCtx = ctx
363
+ refreshBgStatus()
364
+ if (event.aborted) return
365
+ if (!ctx.isIdle() || ctx.hasPendingMessages()) return
366
+ if (owedWakes().length === 0) return
367
+ queueMicrotask(() => {
368
+ void flushWakes(pi)
369
+ })
370
+ })
371
+
372
+ pi.on('tool_result', (event, _ctx): ToolResultPatch | undefined => {
373
+ if (!isBashToolResult(event)) return undefined
374
+ const resultText = event.content.map((c) => (c.type === 'text' ? c.text : '')).join('')
375
+ const rawCommand = event.input['command']
376
+ const command = isString(rawCommand) ? rawCommand : ''
377
+ const exitCode = isStructuredResultSchema(event.structuredContent)
378
+ ? event.structuredContent.exit_code
379
+ : undefined
380
+ const note = benignExitNote(event.isError, command, exitCode, resultText)
381
+
382
+ if (note === undefined) return undefined
383
+ return { content: [...event.content, { type: 'text' as const, text: note }] }
384
+ })
385
+ }
package/src/process.ts ADDED
@@ -0,0 +1,508 @@
1
+ import { spawn } from 'node:child_process'
2
+ import type { ChildProcess } from 'node:child_process'
3
+ import { randomUUID } from 'node:crypto'
4
+ import { createWriteStream, mkdirSync, readdirSync, statSync, unlinkSync, watch } from 'node:fs'
5
+ import type { WriteStream } from 'node:fs'
6
+ import { open, stat } from 'node:fs/promises'
7
+ import { basename, join } from 'node:path'
8
+
9
+ import { getAgentDir, getShellConfig } from '@earendil-works/pi-coding-agent'
10
+
11
+ export const DEFAULT_TIMEOUT_S = 0
12
+ export const MAX_TIMEOUT_S = 600
13
+ const SHELL_LOG_RETENTION_MS = 7 * 24 * 60 * 60 * 1000
14
+ const MAX_SHELL_LOG_BYTES = 512 * 1024 * 1024
15
+ const LOG_SWEEP_INTERVAL_MS = 5 * 60 * 1000
16
+ let lastLogSweep = 0
17
+
18
+ export interface TaskRecord {
19
+ taskId: string
20
+ pid: number
21
+ command: string
22
+ logPath: string
23
+ offset: number
24
+ exitCode: number | null
25
+ signal: string | null
26
+ wakeRequested: boolean
27
+ wakeSent: boolean
28
+ startedAt: number
29
+ child?: ChildProcess
30
+ exitWaiters: Set<() => void>
31
+ }
32
+
33
+ export interface SpawnOptions {
34
+ command: string
35
+ cwd: string
36
+ timeout?: number
37
+ onExit?: (taskId: string) => void
38
+ }
39
+
40
+ function timeoutSeconds(timeout: number | undefined): number {
41
+ if (timeout === undefined) return DEFAULT_TIMEOUT_S
42
+ if (!Number.isFinite(timeout) || timeout <= 0) {
43
+ throw new Error(`Invalid timeout: ${timeout}. Must be a positive number of seconds.`)
44
+ }
45
+ return Math.min(timeout, MAX_TIMEOUT_S)
46
+ }
47
+ export function killTree(pid: number): void {
48
+ try {
49
+ process.kill(process.platform === 'win32' ? pid : -pid, 'SIGKILL')
50
+ } catch {
51
+ try {
52
+ process.kill(pid, 'SIGKILL')
53
+ } catch {}
54
+ }
55
+ }
56
+
57
+ class ProcessRegistry {
58
+ private tasks = new Map<string, TaskRecord>()
59
+
60
+ has(taskId: string): boolean {
61
+ return this.tasks.has(taskId)
62
+ }
63
+
64
+ get(taskId: string): TaskRecord | undefined {
65
+ return this.tasks.get(taskId)
66
+ }
67
+
68
+ all(): TaskRecord[] {
69
+ return [...this.tasks.values()]
70
+ }
71
+
72
+ set(taskId: string, record: TaskRecord): void {
73
+ this.tasks.set(taskId, record)
74
+ }
75
+ }
76
+
77
+ export const registry = new ProcessRegistry()
78
+
79
+ export function taskLogDir(): string {
80
+ return join(getAgentDir(), 'shell-logs')
81
+ }
82
+
83
+ function sweepTaskLogs(dir: string, now: number): void {
84
+ if (now - lastLogSweep < LOG_SWEEP_INTERVAL_MS) return
85
+ lastLogSweep = now
86
+ let entries: string[]
87
+ try {
88
+ entries = readdirSync(dir)
89
+ } catch {
90
+ return
91
+ }
92
+ const files = entries
93
+ .filter((name) => name.endsWith('.log'))
94
+ .map((name) => {
95
+ const path = join(dir, name)
96
+ try {
97
+ const fileStat = statSync(path)
98
+ return { name, path, size: fileStat.size, mtimeMs: fileStat.mtimeMs }
99
+ } catch {
100
+ return undefined
101
+ }
102
+ })
103
+ .filter((entry): entry is { name: string; path: string; size: number; mtimeMs: number } => entry !== undefined)
104
+ .toSorted((a, b) => a.mtimeMs - b.mtimeMs)
105
+ let total = files.reduce((sum, file) => sum + file.size, 0)
106
+ for (const file of files) {
107
+ if (registry.has(file.name.slice(0, -4))) continue
108
+ if (now - file.mtimeMs < SHELL_LOG_RETENTION_MS && total <= MAX_SHELL_LOG_BYTES) continue
109
+ try {
110
+ unlinkSync(file.path)
111
+ total -= file.size
112
+ } catch {}
113
+ }
114
+ }
115
+
116
+ interface ShellInvocation {
117
+ shell: string
118
+ args: string[]
119
+ fromStdin: boolean
120
+ }
121
+
122
+ function resolveShell(): ShellInvocation {
123
+ const cfg = getShellConfig()
124
+ return { shell: cfg.shell, args: cfg.args, fromStdin: cfg.commandTransport === 'stdin' }
125
+ }
126
+
127
+ export function spawnTask(options: SpawnOptions): TaskRecord {
128
+ const timeout = timeoutSeconds(options.timeout)
129
+ const taskId = randomUUID().slice(0, 8)
130
+ const logDirPath = taskLogDir()
131
+ mkdirSync(logDirPath, { recursive: true })
132
+ sweepTaskLogs(logDirPath, Date.now())
133
+ const logPath = join(logDirPath, `${taskId}.log`)
134
+ const stream: WriteStream = createWriteStream(logPath, { flags: 'a' })
135
+
136
+ const shell = resolveShell()
137
+ const child = spawn(shell.shell, shell.fromStdin ? shell.args : [...shell.args, options.command], {
138
+ cwd: options.cwd,
139
+ detached: process.platform !== 'win32',
140
+ stdio: shell.fromStdin ? ['pipe', 'pipe', 'pipe'] : ['ignore', 'pipe', 'pipe']
141
+ })
142
+ if (shell.fromStdin) {
143
+ child.stdin?.on('error', () => {})
144
+ child.stdin?.end(options.command)
145
+ }
146
+ child.stdout?.pipe(stream, { end: false })
147
+ child.stderr?.pipe(stream, { end: false })
148
+
149
+ const record: TaskRecord = {
150
+ taskId,
151
+ pid: child.pid ?? 0,
152
+ command: options.command,
153
+ logPath,
154
+ offset: 0,
155
+ exitCode: null,
156
+ signal: null,
157
+ wakeRequested: false,
158
+ wakeSent: false,
159
+ startedAt: Date.now(),
160
+ child,
161
+ exitWaiters: new Set()
162
+ }
163
+ registry.set(taskId, record)
164
+
165
+ let killTimer: NodeJS.Timeout | undefined
166
+ let finalized = false
167
+ const finalize = (): void => {
168
+ if (finalized) return
169
+ finalized = true
170
+ finalizeRecord(taskId, killTimer, options.onExit)
171
+ }
172
+ if (timeout > 0) {
173
+ killTimer = setTimeout(() => {
174
+ const rec = registry.get(taskId)
175
+ if (rec && rec.exitCode === null && rec.signal === null) {
176
+ killTree(rec.pid)
177
+ rec.signal = 'SIGKILL (timeout)'
178
+ }
179
+ }, timeout * 1000)
180
+ }
181
+
182
+ child.once('error', (err) => {
183
+ const rec = registry.get(taskId)
184
+ if (rec) {
185
+ rec.exitCode = 1
186
+ rec.signal = `spawn error: ${err.message}`
187
+ finalize()
188
+ }
189
+ })
190
+
191
+ child.once('exit', (code, signal) => {
192
+ const rec = registry.get(taskId)
193
+ if (rec) {
194
+ rec.exitCode = code
195
+ if (rec.signal === null) {
196
+ rec.signal = signal
197
+ }
198
+ finalize()
199
+ }
200
+ })
201
+
202
+ stream.on('error', () => {
203
+ const rec = registry.get(taskId)
204
+ if (!rec || finalized) return
205
+ killTree(rec.pid)
206
+ rec.exitCode = 1
207
+ rec.signal = 'log stream error'
208
+ finalize()
209
+ })
210
+
211
+ const pipes = [child.stdout, child.stderr].filter((pipe) => pipe !== undefined && pipe !== null)
212
+ let pipesClosed = 0
213
+ const onPipeClose = () => {
214
+ pipesClosed += 1
215
+ if (pipesClosed >= pipes.length) stream.end()
216
+ }
217
+ if (pipes.length === 0) {
218
+ stream.end()
219
+ } else {
220
+ for (const pipe of pipes) pipe.once('close', onPipeClose)
221
+ }
222
+
223
+ return record
224
+ }
225
+
226
+ function finalizeRecord(
227
+ taskId: string,
228
+ killTimer: NodeJS.Timeout | undefined,
229
+ onExit?: (taskId: string) => void
230
+ ): void {
231
+ const rec = registry.get(taskId)
232
+ if (rec) {
233
+ rec.child = undefined
234
+ rec.exitWaiters.forEach((w) => w())
235
+ rec.exitWaiters.clear()
236
+ }
237
+ if (killTimer) clearTimeout(killTimer)
238
+ onExit?.(taskId)
239
+ }
240
+
241
+ export function killTask(taskId: string): boolean {
242
+ const rec = registry.get(taskId)
243
+ if (!rec) return false
244
+ if (rec.exitCode !== null || rec.signal !== null) return true
245
+ const pid = rec.pid
246
+ if (!pid) return true
247
+ try {
248
+ process.kill(process.platform === 'win32' ? pid : -pid, 'SIGTERM')
249
+ } catch {
250
+ return true
251
+ }
252
+ const deadline = Date.now() + 1000
253
+ const poll = setInterval(() => {
254
+ const recNow = registry.get(taskId)
255
+ if (!recNow || recNow.exitCode !== null || recNow.signal !== null || Date.now() >= deadline) {
256
+ clearInterval(poll)
257
+ if (recNow && recNow.exitCode === null && recNow.signal === null) {
258
+ killTree(pid)
259
+ }
260
+ }
261
+ }, 50)
262
+ return true
263
+ }
264
+
265
+ export async function pidForPort(port: number): Promise<number | undefined> {
266
+ const { execFile } = await import('node:child_process')
267
+ const { promisify } = await import('node:util')
268
+ try {
269
+ const execFileP = promisify(execFile)
270
+ const out = await execFileP('lsof', ['-ti', `tcp:${port}`])
271
+ const stdout = String((out as { stdout?: unknown }).stdout ?? '')
272
+ const pid = stdout.trim().split('\n')[0]?.trim()
273
+ if (!pid) return undefined
274
+ const n = Number.parseInt(pid, 10)
275
+ return Number.isFinite(n) ? n : undefined
276
+ } catch {
277
+ return undefined
278
+ }
279
+ }
280
+
281
+ export async function readNewBytes(
282
+ taskId: string,
283
+ fromOffset: number
284
+ ): Promise<{
285
+ text: string
286
+ start: number
287
+ end: number
288
+ size: number
289
+ offset: number
290
+ }> {
291
+ const rec = registry.get(taskId)
292
+ if (!rec) throw new Error(`No such task: ${taskId}`)
293
+ let file
294
+ try {
295
+ file = await open(rec.logPath, 'r')
296
+ } catch {
297
+ rec.offset = fromOffset
298
+ return { text: '', start: fromOffset, end: fromOffset, size: 0, offset: fromOffset }
299
+ }
300
+ try {
301
+ const size = (await file.stat()).size
302
+ const start = Math.max(0, Math.min(fromOffset, size))
303
+ if (start >= size) {
304
+ rec.offset = size
305
+ return { text: '', start, end: size, size, offset: size }
306
+ }
307
+ const unread = size - start
308
+ const VIEW_WINDOW = 16 * 1024
309
+ let text: string
310
+ if (unread <= VIEW_WINDOW * 2) {
311
+ const buffer = Buffer.alloc(unread)
312
+ const { bytesRead } = await file.read(buffer, 0, unread, start)
313
+ text = buffer.subarray(0, bytesRead).toString('utf8')
314
+ } else {
315
+ const headBuf = Buffer.alloc(VIEW_WINDOW)
316
+ const headRead = await file.read(headBuf, 0, VIEW_WINDOW, start)
317
+ const tailStart = size - VIEW_WINDOW
318
+ const tailBuf = Buffer.alloc(VIEW_WINDOW)
319
+ const tailRead = await file.read(tailBuf, 0, VIEW_WINDOW, tailStart)
320
+ const head = headBuf.subarray(0, headRead.bytesRead).toString('utf8')
321
+ const tail = tailBuf.subarray(0, tailRead.bytesRead).toString('utf8')
322
+ const omitted = size - start - headRead.bytesRead - tailRead.bytesRead
323
+ text = `${head}\n\n[${omitted} bytes omitted, middle cut]\n\n${tail}`
324
+ }
325
+ rec.offset = size
326
+ return { text, start, end: size, size, offset: rec.offset }
327
+ } finally {
328
+ await file.close()
329
+ }
330
+ }
331
+
332
+ export async function readUnreadTail(
333
+ taskId: string,
334
+ maxBytes = 8 * 1024
335
+ ): Promise<{ text: string; start: number; end: number; size: number }> {
336
+ const rec = registry.get(taskId)
337
+ if (!rec) throw new Error(`No such task: ${taskId}`)
338
+ const file = await open(rec.logPath, 'r')
339
+ try {
340
+ const size = (await file.stat()).size
341
+ const start = Math.min(rec.offset, size)
342
+ if (start >= size) {
343
+ return { text: '', start, end: size, size }
344
+ }
345
+ const unread = size - start
346
+ if (unread <= maxBytes) {
347
+ const buffer = Buffer.alloc(unread)
348
+ const { bytesRead } = await file.read(buffer, 0, buffer.length, start)
349
+ return { text: buffer.subarray(0, bytesRead).toString('utf8'), start, end: start + bytesRead, size }
350
+ }
351
+ const headLen = Math.floor(maxBytes / 2)
352
+ const tailLen = maxBytes - headLen
353
+ const headBuf = Buffer.alloc(headLen)
354
+ const tailBuf = Buffer.alloc(tailLen)
355
+ const headRead = await file.read(headBuf, 0, headLen, start)
356
+ const tailRead = await file.read(tailBuf, 0, tailLen, size - tailLen)
357
+ const head = headBuf.subarray(0, headRead.bytesRead).toString('utf8')
358
+ const tail = tailBuf.subarray(0, tailRead.bytesRead).toString('utf8')
359
+ return { text: `${head}\n...\n${tail}`, start, end: size, size }
360
+ } finally {
361
+ await file.close()
362
+ }
363
+ }
364
+
365
+ export function watchEventMatches(filename: string | Buffer | null, fileName: string): boolean {
366
+ return filename === null || filename.toString() === fileName
367
+ }
368
+
369
+ export function watchForWrite(
370
+ taskId: string,
371
+ fromOffset: number,
372
+ onWrite: (text: string, start: number, end: number, size: number) => void,
373
+ onExit: () => void
374
+ ): AbortController {
375
+ const rec = registry.get(taskId)
376
+ if (!rec) throw new Error(`No such task: ${taskId}`)
377
+ const controller = new AbortController()
378
+ const dir = taskLogDir()
379
+ const fileName = basename(rec.logPath)
380
+ let watcher: ReturnType<typeof watch> | undefined
381
+ let pollTimer: ReturnType<typeof setInterval> | undefined
382
+ let settled = false
383
+ let checking: Promise<boolean> | undefined
384
+
385
+ const stopPolling = () => {
386
+ if (pollTimer) clearInterval(pollTimer)
387
+ pollTimer = undefined
388
+ }
389
+ const stop = () => {
390
+ if (settled) return
391
+ settled = true
392
+ watcher?.close()
393
+ stopPolling()
394
+ }
395
+
396
+ const check = (): Promise<boolean> => {
397
+ if (checking) return checking
398
+ checking = (async (): Promise<boolean> => {
399
+ if (settled) return false
400
+ try {
401
+ const st = await stat(rec.logPath)
402
+ if (st.size <= fromOffset) return false
403
+ const { text, start, end, size } = await readNewBytes(taskId, fromOffset)
404
+ stop()
405
+ onWrite(text, start, end, size)
406
+ return true
407
+ } catch {
408
+ return false
409
+ }
410
+ })().finally(() => {
411
+ checking = undefined
412
+ })
413
+ return checking
414
+ }
415
+
416
+ const startPolling = (): void => {
417
+ if (pollTimer) return
418
+ pollTimer = setInterval(() => void check(), 250)
419
+ pollTimer.unref()
420
+ }
421
+
422
+ const finishWithoutOutput = async (wrote: boolean): Promise<void> => {
423
+ if (wrote || settled) return
424
+ stop()
425
+ try {
426
+ onExit()
427
+ } catch {}
428
+ }
429
+
430
+ if (rec.exitCode !== null || rec.signal !== null) {
431
+ void check().then(finishWithoutOutput)
432
+ return controller
433
+ }
434
+
435
+ const exitBridge = () => {
436
+ if (settled) return
437
+ void (checking ?? Promise.resolve(false))
438
+ .then(() => check())
439
+ .then(finishWithoutOutput)
440
+ }
441
+ rec.exitWaiters.add(exitBridge)
442
+
443
+ try {
444
+ watcher = watch(dir, (_event, filename) => {
445
+ if (watchEventMatches(filename, fileName)) void check()
446
+ if (filename === null) startPolling()
447
+ })
448
+ } catch {
449
+ startPolling()
450
+ }
451
+
452
+ void check()
453
+
454
+ controller.signal.addEventListener('abort', () => {
455
+ rec.exitWaiters.delete(exitBridge)
456
+ stop()
457
+ })
458
+ return controller
459
+ }
460
+
461
+ interface MiddleOutView {
462
+ head: string
463
+ tail: string
464
+ omitted: number
465
+ total: number
466
+ }
467
+
468
+ export function benignExitNote(
469
+ isError: boolean,
470
+ command: string,
471
+ exitCode: number | undefined,
472
+ raisedText: string
473
+ ): string | undefined {
474
+ if (!isError) return undefined
475
+ if (exitCode === 1 && /\b(?:grep|rg)\b/.test(command)) {
476
+ return '\n[Note: exit 1 here means no matches found, not an error.]'
477
+ }
478
+ if (exitCode === undefined && /^Command timed out after\b/.test(raisedText.trimEnd().split('\n').at(-1) ?? '')) {
479
+ return '\n[Note: the command timed out and was killed; not a clean exit.]'
480
+ }
481
+ return undefined
482
+ }
483
+
484
+ export function middleOut(text: string, maxBytes: number): MiddleOutView {
485
+ const total = Buffer.byteLength(text, 'utf8')
486
+ if (total <= maxBytes) {
487
+ return { head: text, tail: '', omitted: 0, total }
488
+ }
489
+ const half = Math.floor(maxBytes / 2)
490
+ const buf = Buffer.from(text, 'utf8')
491
+ let headEnd = half
492
+ let headByte = headEnd < buf.length ? buf[headEnd] : undefined
493
+ while (headEnd > 0 && headByte !== undefined && (headByte & 0xc0) === 0x80) {
494
+ headEnd--
495
+ headByte = headEnd < buf.length ? buf[headEnd] : undefined
496
+ }
497
+ const head = buf.subarray(0, headEnd).toString('utf8')
498
+ let tailStart = Math.max(headEnd, total - (maxBytes - headEnd))
499
+ let tailByte = tailStart < buf.length ? buf[tailStart] : undefined
500
+ while (tailByte !== undefined && (tailByte & 0xc0) === 0x80) {
501
+ tailStart++
502
+ tailByte = tailStart < buf.length ? buf[tailStart] : undefined
503
+ }
504
+ const tail = buf.subarray(tailStart).toString('utf8')
505
+ const headBytes = headEnd
506
+ const tailBytes = buf.length - tailStart
507
+ return { head, tail, omitted: total - headBytes - tailBytes, total }
508
+ }