@tduyng/pi-shell 0.0.0-stage → 0.0.2

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,71 @@
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
+ ## Stall check
50
+
51
+ A task the model parked on with `wait: "exit"` also gets a silence check. Every 30 seconds it reads the log size. After 10 minutes with no new bytes, the agent is woken once with the elapsed time and the log path. The wake fires again only after output resumes and stops again. No model call runs for the check.
52
+
53
+ ## Footer indicator
54
+
55
+ 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.
56
+
57
+ ## Task lifecycle
58
+
59
+ 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.
60
+
61
+ ## Install
62
+
63
+ ```bash
64
+ pi install npm:@tduyng/pi-shell
65
+ ```
66
+
67
+ Local checkout: `pi install /path/to/dotfiles/pi/agent/extensions/pi-shell`
68
+
69
+ ## Configure
70
+
71
+ - `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.2",
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,394 @@
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
+ isNoMatchCommand,
20
+ pidForPort,
21
+ readNewBytes,
22
+ readUnreadTail,
23
+ registry,
24
+ spawnTask,
25
+ watchForWrite
26
+ } from './process.js'
27
+ import { watchStall } from './stall.js'
28
+ import type { TaskRecord } from './process.js'
29
+ const isString = new Validator(t.string()).isValidObject
30
+
31
+ const OUTPUT_VIEW_MAX_BYTES = 8 * 1024
32
+ const WAKE_TAIL_MAX_BYTES = 8 * 1024
33
+ const MIN_WAKE_TAIL_BYTES = 1024
34
+
35
+ const STATE_TYPE = 'shell'
36
+ const WAKE_TYPE = 'shell-wake'
37
+ const ENABLED = !/^(0|false|no|off)$/i.test(process.env['SHELL'] ?? '')
38
+ const LOG_PREFIX = 'Full log: '
39
+
40
+ const bgSchema = t.object({
41
+ action: t.string({ enum: ['start', 'output', 'kill', 'status'] }),
42
+ command: t.optional(t.string()),
43
+ timeout: t.optional(t.number()),
44
+ task_id: t.optional(t.string()),
45
+ from_offset: t.optional(t.number()),
46
+ wait: t.optional(t.union([t.literal('now'), t.literal('next_write'), t.literal('exit')])),
47
+ pid: t.optional(t.number()),
48
+ port: t.optional(t.number())
49
+ })
50
+
51
+ type BgInput = Infer<typeof bgSchema>
52
+
53
+ function describeExit(exitCode: number | null, signal: string | null): string {
54
+ if (exitCode !== null) {
55
+ if (exitCode === 0) return 'exited 0'
56
+ return `exited ${exitCode}`
57
+ }
58
+ if (signal) {
59
+ const match = /^(SIG[A-Z]+)\s*\((.*)\)$/.exec(signal)
60
+ if (match) {
61
+ return `killed (${match[1]}, ${match[2]})`
62
+ }
63
+ if (signal.startsWith('SIGKILL')) return `killed (${signal})`
64
+ if (signal.startsWith('SIGTERM')) return `terminated (${signal})`
65
+ return `killed by ${signal}`
66
+ }
67
+ return 'exited (unknown status)'
68
+ }
69
+
70
+ function textResult(text: string): AgentToolResult<unknown> {
71
+ return { content: [{ type: 'text', text }], details: {} }
72
+ }
73
+
74
+ export function owedWakes(): TaskRecord[] {
75
+ return registry
76
+ .all()
77
+ .filter((rec) => rec.wakeRequested && !rec.wakeSent && (rec.exitCode !== null || rec.signal !== null))
78
+ }
79
+
80
+ export async function buildWakeText(records: TaskRecord[], budget = WAKE_TAIL_MAX_BYTES): Promise<string> {
81
+ const share = Math.max(MIN_WAKE_TAIL_BYTES, Math.floor(budget / records.length))
82
+ const blocks: string[] = []
83
+ for (const rec of records) {
84
+ const benign = isBenignNoMatch(rec) ? ' (no matches found, not an error)' : ''
85
+ const note = describeExit(rec.exitCode, rec.signal)
86
+ let tailText = ''
87
+ try {
88
+ const tail = await readUnreadTail(rec.taskId, share)
89
+ if (tail.text) {
90
+ const omitted = tail.end - tail.start - Buffer.byteLength(tail.text)
91
+ tailText = omitted > 0 ? `\n${tail.text}\n[${omitted} bytes omitted, middle cut]` : `\n${tail.text}`
92
+ }
93
+ } catch {}
94
+ blocks.push(`bg task ${rec.taskId} ${note}${benign}.${tailText}\n${LOG_PREFIX}${rec.logPath}`)
95
+ }
96
+ return blocks.join('\n\n')
97
+ }
98
+
99
+ export async function sendBackgroundWake(pi: Pick<ExtensionAPI, 'sendMessage'>, text: string): Promise<void> {
100
+ await pi.sendMessage(
101
+ { customType: WAKE_TYPE, content: text, display: true },
102
+ { deliverAs: 'followUp', triggerTurn: true }
103
+ )
104
+ }
105
+
106
+ async function flushWakes(pi: ExtensionAPI): Promise<boolean> {
107
+ const owed = owedWakes()
108
+ if (owed.length === 0) return false
109
+ const text = await buildWakeText(owed)
110
+ try {
111
+ await sendBackgroundWake(pi, text)
112
+ for (const rec of owed) rec.wakeSent = true
113
+ return true
114
+ } catch {
115
+ return false
116
+ }
117
+ }
118
+
119
+ function isBenignNoMatch(rec: Pick<TaskRecord, 'command' | 'exitCode' | 'signal'>): boolean {
120
+ if (rec.exitCode !== 1 || rec.signal !== null) return false
121
+ return isNoMatchCommand(rec.command)
122
+ }
123
+
124
+ interface PersistedTask {
125
+ taskId: string
126
+ command: string
127
+ logPath: string
128
+ startedAt: number
129
+ }
130
+
131
+ const StructuredResultSchema = t.object({ exit_code: t.optional(t.number()) }, { additionalProperties: true })
132
+ const isStructuredResultSchema = new Validator(StructuredResultSchema).isValidObject
133
+
134
+ const PersistedTaskSchema = t.object({
135
+ taskId: t.string({ minLength: 1 }),
136
+ command: t.string(),
137
+ logPath: t.string(),
138
+ startedAt: t.number()
139
+ })
140
+ const isPersistedTaskSchema = new Validator(PersistedTaskSchema).isValidObject
141
+
142
+ function isPersistedTask(value: unknown): value is PersistedTask {
143
+ return isPersistedTaskSchema(value)
144
+ }
145
+
146
+ function reconstructTasks(ctx: ExtensionContext): void {
147
+ for (const entry of ctx.sessionManager.getBranch()) {
148
+ if (entry.type !== 'custom' || entry.customType !== STATE_TYPE) continue
149
+ if (!isPersistedTask(entry.data)) continue
150
+ const task = entry.data
151
+ if (registry.has(task.taskId)) continue
152
+ registry.set(task.taskId, {
153
+ taskId: task.taskId,
154
+ pid: 0,
155
+ command: task.command,
156
+ logPath: task.logPath,
157
+ offset: 0,
158
+ exitCode: null,
159
+ signal: 'session ended',
160
+ wakeRequested: false,
161
+ wakeSent: true,
162
+ startedAt: task.startedAt,
163
+ exitWaiters: new Set()
164
+ })
165
+ }
166
+ }
167
+
168
+ async function bgAction(pi: ExtensionAPI, ctx: ExtensionContext, params: BgInput): Promise<AgentToolResult<unknown>> {
169
+ const rec = params.task_id !== undefined ? registry.get(params.task_id) : undefined
170
+ if (params.action === 'output') {
171
+ if (!rec) throw new Error(`No such task: ${params.task_id}`)
172
+ const from = params.from_offset ?? rec.offset
173
+ const wait = params.wait ?? 'now'
174
+ const read = await readNewBytes(params.task_id!, from)
175
+ const view = middleOut(read.text, OUTPUT_VIEW_MAX_BYTES)
176
+ const omittedNote =
177
+ view.omitted > 0 ? `\n[${view.omitted} bytes omitted, middle cut. Full log: ${rec.logPath}]` : ''
178
+ const body = view.head + (view.omitted > 0 ? `\n...\n${view.tail}` : view.tail)
179
+
180
+ if (wait === 'exit' && (rec.exitCode !== null || rec.signal !== null)) {
181
+ rec.wakeSent = true
182
+ const benign = isBenignNoMatch(rec) ? ' (no matches found, not an error)' : ''
183
+ return textResult(
184
+ `task ${params.task_id} ${describeExit(rec.exitCode, rec.signal)}${benign}. ` +
185
+ `bytes ${read.start}-${read.end} of ${read.size} since offset ${from}.\n` +
186
+ `${body || '(no new output)'}${omittedNote}\n${LOG_PREFIX}${rec.logPath}`
187
+ )
188
+ }
189
+
190
+ if (wait === 'now') {
191
+ if (rec.exitCode !== null || rec.signal !== null) {
192
+ rec.wakeSent = true
193
+ }
194
+ return textResult(
195
+ `task ${params.task_id}: bytes ${read.start}-${read.end} of ${read.size}\n` +
196
+ `${body || '(no new output)'}${omittedNote}\n${LOG_PREFIX}${rec.logPath}`
197
+ )
198
+ }
199
+
200
+ if (wait === 'next_write') {
201
+ const controller = watchForWrite(
202
+ params.task_id!,
203
+ read.end,
204
+ (text, start, end, size) => {
205
+ const v = middleOut(text, OUTPUT_VIEW_MAX_BYTES)
206
+ const omitted =
207
+ v.omitted > 0 ? `\n[${v.omitted} bytes omitted, middle cut. Full log: ${rec.logPath}]` : ''
208
+ void sendBackgroundWake(
209
+ pi,
210
+ `bg task ${params.task_id} wrote new output (bytes ${start}-${end} of ${size}).\n` +
211
+ `${v.head}${v.omitted > 0 ? `\n...\n${v.tail}` : v.tail}${omitted}\n${LOG_PREFIX}${rec.logPath}`
212
+ ).catch(() => undefined)
213
+ },
214
+ () => {
215
+ if (rec.exitCode === null && rec.signal === null) return
216
+ const benign = isBenignNoMatch(rec) ? ' (no matches found, not an error)' : ''
217
+ void sendBackgroundWake(
218
+ pi,
219
+ `bg task ${params.task_id} exited ${describeExit(rec.exitCode, rec.signal)}${benign} with no new output. ${LOG_PREFIX}${rec.logPath}`
220
+ ).catch(() => undefined)
221
+ }
222
+ )
223
+ ctx.signal?.addEventListener('abort', () => controller.abort(), { once: true })
224
+ return textResult(
225
+ `Watching task ${params.task_id} (bytes ${read.start}-${read.end} of ${read.size}). ` +
226
+ `The agent will be woken when new output appears. ${LOG_PREFIX}${rec.logPath}`
227
+ )
228
+ }
229
+
230
+ if (!rec.wakeRequested) {
231
+ watchStall(rec, (silentMs) => {
232
+ void sendBackgroundWake(
233
+ pi,
234
+ `bg task ${params.task_id} has written no output for ${Math.round(silentMs / 60000)} min and is still running. Check its log, or kill it if it is stuck. ${LOG_PREFIX}${rec.logPath}`
235
+ ).catch(() => undefined)
236
+ })
237
+ }
238
+ rec.wakeRequested = true
239
+ return textResult(
240
+ `Watching task ${params.task_id} (bytes ${read.start}-${read.end} of ${read.size}). ` +
241
+ `The agent will be woken when it exits. ${LOG_PREFIX}${rec.logPath}`
242
+ )
243
+ }
244
+
245
+ if (params.action === 'kill') {
246
+ if (params.task_id !== undefined) {
247
+ const target = registry.get(params.task_id)
248
+ if (!target) throw new Error(`No such task: ${params.task_id}`)
249
+ if (target.exitCode !== null || target.signal !== null) {
250
+ return textResult(
251
+ `Task ${params.task_id} already finished (${describeExit(target.exitCode, target.signal)}).`
252
+ )
253
+ }
254
+ target.wakeSent = true
255
+ killTask(params.task_id)
256
+ return textResult(`Sent SIGTERM to task ${params.task_id} (pid ${target.pid}).`)
257
+ }
258
+ if (params.pid !== undefined) {
259
+ const target = registry.all().find((r) => r.pid === params.pid)
260
+ if (!target) throw new Error(`pid ${params.pid} is not a background task of this session`)
261
+ if (target.exitCode !== null || target.signal !== null) {
262
+ return textResult(`pid ${params.pid} (task ${target.taskId}) already finished.`)
263
+ }
264
+ target.wakeSent = true
265
+ killTask(target.taskId)
266
+ return textResult(`Sent SIGTERM to pid ${params.pid} (task ${target.taskId}).`)
267
+ }
268
+ if (params.port !== undefined) {
269
+ const pid = await pidForPort(params.port)
270
+ if (pid === undefined) {
271
+ return textResult(`No process listening on port ${params.port}.`)
272
+ }
273
+ const target = registry.all().find((r) => r.pid === pid)
274
+ if (!target) throw new Error(`pid ${pid} on port ${params.port} is not a background task of this session`)
275
+ if (target.exitCode !== null || target.signal !== null) {
276
+ return textResult(`pid ${pid} on port ${params.port} (task ${target.taskId}) already finished.`)
277
+ }
278
+ target.wakeSent = true
279
+ killTask(target.taskId)
280
+ return textResult(`Sent SIGTERM to pid ${pid} on port ${params.port} (task ${target.taskId}).`)
281
+ }
282
+ throw new Error('bg action kill needs one of task_id, pid, or port')
283
+ }
284
+
285
+ const tasks = registry.all()
286
+ if (tasks.length === 0) {
287
+ return textResult('No background tasks.')
288
+ }
289
+ const lines = tasks.map((r) => {
290
+ const state = r.exitCode !== null || r.signal !== null ? describeExit(r.exitCode, r.signal) : 'running'
291
+ const benign = isBenignNoMatch(r) ? ' (no matches)' : ''
292
+ return `${r.taskId} ${r.pid} ${state}${benign} offset ${r.offset} ${r.command.slice(0, 80)}`
293
+ })
294
+ return textResult(lines.join('\n'))
295
+ }
296
+
297
+ let statusCtx: ExtensionContext | undefined
298
+
299
+ function refreshBgStatus(): void {
300
+ if (!statusCtx) return
301
+ try {
302
+ const running = registry.all().filter((r) => r.exitCode === null && r.signal === null).length
303
+ statusCtx.ui.setStatus('shell', running > 0 ? `● ${running} bg running` : undefined)
304
+ } catch {
305
+ statusCtx = undefined
306
+ }
307
+ }
308
+
309
+ function agentIsIdle(): boolean {
310
+ if (!statusCtx) return false
311
+ try {
312
+ return statusCtx.isIdle() && !statusCtx.hasPendingMessages()
313
+ } catch {
314
+ statusCtx = undefined
315
+ return false
316
+ }
317
+ }
318
+
319
+ export default function shellExtension(pi: ExtensionAPI): void {
320
+ if (!ENABLED) return
321
+
322
+ pi.on('session_start', async (_event, ctx) => {
323
+ reconstructTasks(ctx)
324
+ statusCtx = ctx
325
+ refreshBgStatus()
326
+ })
327
+ pi.on('session_tree', async (_event, ctx) => {
328
+ reconstructTasks(ctx)
329
+ statusCtx = ctx
330
+ refreshBgStatus()
331
+ })
332
+
333
+ pi.registerTool({
334
+ name: 'bg',
335
+ label: 'bg',
336
+ description:
337
+ '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.',
338
+ promptSnippet: 'Run background commands',
339
+ annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: false },
340
+ promptGuidelines: [
341
+ 'For long work, start it with bg, then request output with wait "exit" instead of polling a foreground shell.'
342
+ ],
343
+ parameters: bgSchema,
344
+ async execute(_toolCallId, params: BgInput, _signal, _onUpdate, ctx) {
345
+ if (params.action === 'start') {
346
+ if (!params.command) throw new Error('bg action start needs a command.')
347
+ statusCtx = ctx
348
+ const rec = spawnTask({
349
+ command: params.command,
350
+ cwd: ctx.cwd,
351
+ timeout: params.timeout,
352
+ onExit: () => {
353
+ queueMicrotask(() => {
354
+ refreshBgStatus()
355
+ if (!agentIsIdle()) return
356
+ void flushWakes(pi)
357
+ })
358
+ }
359
+ })
360
+ refreshBgStatus()
361
+ return textResult(
362
+ `task_id: ${rec.taskId}\npid: ${rec.pid}\nlog: ${rec.logPath}\n` +
363
+ `Started in background. Use bg (action output, wait "exit") to be woken when it finishes.`
364
+ )
365
+ }
366
+ return bgAction(pi, ctx, params)
367
+ }
368
+ })
369
+
370
+ pi.on('agent_settled', async (event, ctx) => {
371
+ statusCtx = ctx
372
+ refreshBgStatus()
373
+ if (event.aborted) return
374
+ if (!ctx.isIdle() || ctx.hasPendingMessages()) return
375
+ if (owedWakes().length === 0) return
376
+ queueMicrotask(() => {
377
+ void flushWakes(pi)
378
+ })
379
+ })
380
+
381
+ pi.on('tool_result', (event, _ctx): ToolResultPatch | undefined => {
382
+ if (!isBashToolResult(event)) return undefined
383
+ const resultText = event.content.map((c) => (c.type === 'text' ? c.text : '')).join('')
384
+ const rawCommand = event.input['command']
385
+ const command = isString(rawCommand) ? rawCommand : ''
386
+ const exitCode = isStructuredResultSchema(event.structuredContent)
387
+ ? event.structuredContent.exit_code
388
+ : undefined
389
+ const note = benignExitNote(event.isError, command, exitCode, resultText)
390
+
391
+ if (note === undefined) return undefined
392
+ return { content: [...event.content, { type: 'text' as const, text: note }] }
393
+ })
394
+ }
package/src/process.ts ADDED
@@ -0,0 +1,519 @@
1
+ import { spawn } from 'node:child_process'
2
+ import type { ChildProcess } from 'node:child_process'
3
+ import { randomUUID } from 'node:crypto'
4
+ import { appendFileSync, 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
+ appendFileSync(logPath, '')
135
+ const stream: WriteStream = createWriteStream(logPath, { flags: 'a' })
136
+
137
+ const shell = resolveShell()
138
+ const child = spawn(shell.shell, shell.fromStdin ? shell.args : [...shell.args, options.command], {
139
+ cwd: options.cwd,
140
+ detached: process.platform !== 'win32',
141
+ stdio: shell.fromStdin ? ['pipe', 'pipe', 'pipe'] : ['ignore', 'pipe', 'pipe']
142
+ })
143
+ if (shell.fromStdin) {
144
+ child.stdin?.on('error', () => {})
145
+ child.stdin?.end(options.command)
146
+ }
147
+ child.stdout?.pipe(stream, { end: false })
148
+ child.stderr?.pipe(stream, { end: false })
149
+
150
+ const record: TaskRecord = {
151
+ taskId,
152
+ pid: child.pid ?? 0,
153
+ command: options.command,
154
+ logPath,
155
+ offset: 0,
156
+ exitCode: null,
157
+ signal: null,
158
+ wakeRequested: false,
159
+ wakeSent: false,
160
+ startedAt: Date.now(),
161
+ child,
162
+ exitWaiters: new Set()
163
+ }
164
+ registry.set(taskId, record)
165
+
166
+ let killTimer: NodeJS.Timeout | undefined
167
+ let finalized = false
168
+ const finalize = (): void => {
169
+ if (finalized) return
170
+ finalized = true
171
+ finalizeRecord(taskId, killTimer, options.onExit)
172
+ }
173
+ if (timeout > 0) {
174
+ killTimer = setTimeout(() => {
175
+ const rec = registry.get(taskId)
176
+ if (rec && rec.exitCode === null && rec.signal === null) {
177
+ killTree(rec.pid)
178
+ rec.signal = 'SIGKILL (timeout)'
179
+ }
180
+ }, timeout * 1000)
181
+ }
182
+
183
+ child.once('error', (err) => {
184
+ const rec = registry.get(taskId)
185
+ if (rec) {
186
+ rec.exitCode = 1
187
+ rec.signal = `spawn error: ${err.message}`
188
+ finalize()
189
+ }
190
+ })
191
+
192
+ child.once('exit', (code, signal) => {
193
+ const rec = registry.get(taskId)
194
+ if (rec) {
195
+ rec.exitCode = code
196
+ if (rec.signal === null) {
197
+ rec.signal = signal
198
+ }
199
+ finalize()
200
+ }
201
+ })
202
+
203
+ stream.on('error', () => {
204
+ const rec = registry.get(taskId)
205
+ if (!rec || finalized) return
206
+ killTree(rec.pid)
207
+ rec.exitCode = 1
208
+ rec.signal = 'log stream error'
209
+ finalize()
210
+ })
211
+
212
+ const pipes = [child.stdout, child.stderr].filter((pipe) => pipe !== undefined && pipe !== null)
213
+ let pipesClosed = 0
214
+ const onPipeClose = () => {
215
+ pipesClosed += 1
216
+ if (pipesClosed >= pipes.length) stream.end()
217
+ }
218
+ if (pipes.length === 0) {
219
+ stream.end()
220
+ } else {
221
+ for (const pipe of pipes) pipe.once('close', onPipeClose)
222
+ }
223
+
224
+ return record
225
+ }
226
+
227
+ function finalizeRecord(
228
+ taskId: string,
229
+ killTimer: NodeJS.Timeout | undefined,
230
+ onExit?: (taskId: string) => void
231
+ ): void {
232
+ const rec = registry.get(taskId)
233
+ if (rec) {
234
+ rec.child = undefined
235
+ rec.exitWaiters.forEach((w) => w())
236
+ rec.exitWaiters.clear()
237
+ }
238
+ if (killTimer) clearTimeout(killTimer)
239
+ onExit?.(taskId)
240
+ }
241
+
242
+ export function killTask(taskId: string): boolean {
243
+ const rec = registry.get(taskId)
244
+ if (!rec) return false
245
+ if (rec.exitCode !== null || rec.signal !== null) return true
246
+ const pid = rec.pid
247
+ if (!pid) return true
248
+ try {
249
+ process.kill(process.platform === 'win32' ? pid : -pid, 'SIGTERM')
250
+ } catch {
251
+ return true
252
+ }
253
+ const deadline = Date.now() + 1000
254
+ const poll = setInterval(() => {
255
+ const recNow = registry.get(taskId)
256
+ if (!recNow || recNow.exitCode !== null || recNow.signal !== null || Date.now() >= deadline) {
257
+ clearInterval(poll)
258
+ if (recNow && recNow.exitCode === null && recNow.signal === null) {
259
+ killTree(pid)
260
+ }
261
+ }
262
+ }, 50)
263
+ return true
264
+ }
265
+
266
+ export async function pidForPort(port: number): Promise<number | undefined> {
267
+ const { execFile } = await import('node:child_process')
268
+ const { promisify } = await import('node:util')
269
+ try {
270
+ const execFileP = promisify(execFile)
271
+ const out = await execFileP('lsof', ['-ti', `tcp:${port}`])
272
+ const stdout = String((out as { stdout?: unknown }).stdout ?? '')
273
+ const pid = stdout.trim().split('\n')[0]?.trim()
274
+ if (!pid) return undefined
275
+ const n = Number.parseInt(pid, 10)
276
+ return Number.isFinite(n) ? n : undefined
277
+ } catch {
278
+ return undefined
279
+ }
280
+ }
281
+
282
+ export async function readNewBytes(
283
+ taskId: string,
284
+ fromOffset: number
285
+ ): Promise<{
286
+ text: string
287
+ start: number
288
+ end: number
289
+ size: number
290
+ offset: number
291
+ }> {
292
+ const rec = registry.get(taskId)
293
+ if (!rec) throw new Error(`No such task: ${taskId}`)
294
+ let file
295
+ try {
296
+ file = await open(rec.logPath, 'r')
297
+ } catch {
298
+ rec.offset = fromOffset
299
+ return { text: '', start: fromOffset, end: fromOffset, size: 0, offset: fromOffset }
300
+ }
301
+ try {
302
+ const size = (await file.stat()).size
303
+ const start = Math.max(0, Math.min(fromOffset, size))
304
+ if (start >= size) {
305
+ rec.offset = size
306
+ return { text: '', start, end: size, size, offset: size }
307
+ }
308
+ const unread = size - start
309
+ const VIEW_WINDOW = 16 * 1024
310
+ let text: string
311
+ if (unread <= VIEW_WINDOW * 2) {
312
+ const buffer = Buffer.alloc(unread)
313
+ const { bytesRead } = await file.read(buffer, 0, unread, start)
314
+ text = buffer.subarray(0, bytesRead).toString('utf8')
315
+ } else {
316
+ const headBuf = Buffer.alloc(VIEW_WINDOW)
317
+ const headRead = await file.read(headBuf, 0, VIEW_WINDOW, start)
318
+ const tailStart = size - VIEW_WINDOW
319
+ const tailBuf = Buffer.alloc(VIEW_WINDOW)
320
+ const tailRead = await file.read(tailBuf, 0, VIEW_WINDOW, tailStart)
321
+ const head = headBuf.subarray(0, headRead.bytesRead).toString('utf8')
322
+ const tail = tailBuf.subarray(0, tailRead.bytesRead).toString('utf8')
323
+ const omitted = size - start - headRead.bytesRead - tailRead.bytesRead
324
+ text = `${head}\n\n[${omitted} bytes omitted, middle cut]\n\n${tail}`
325
+ }
326
+ rec.offset = size
327
+ return { text, start, end: size, size, offset: rec.offset }
328
+ } finally {
329
+ await file.close()
330
+ }
331
+ }
332
+
333
+ export async function readUnreadTail(
334
+ taskId: string,
335
+ maxBytes = 8 * 1024
336
+ ): Promise<{ text: string; start: number; end: number; size: number }> {
337
+ const rec = registry.get(taskId)
338
+ if (!rec) throw new Error(`No such task: ${taskId}`)
339
+ const file = await open(rec.logPath, 'r')
340
+ try {
341
+ const size = (await file.stat()).size
342
+ const start = Math.min(rec.offset, size)
343
+ if (start >= size) {
344
+ return { text: '', start, end: size, size }
345
+ }
346
+ const unread = size - start
347
+ if (unread <= maxBytes) {
348
+ const buffer = Buffer.alloc(unread)
349
+ const { bytesRead } = await file.read(buffer, 0, buffer.length, start)
350
+ return { text: buffer.subarray(0, bytesRead).toString('utf8'), start, end: start + bytesRead, size }
351
+ }
352
+ const headLen = Math.floor(maxBytes / 2)
353
+ const tailLen = maxBytes - headLen
354
+ const headBuf = Buffer.alloc(headLen)
355
+ const tailBuf = Buffer.alloc(tailLen)
356
+ const headRead = await file.read(headBuf, 0, headLen, start)
357
+ const tailRead = await file.read(tailBuf, 0, tailLen, size - tailLen)
358
+ const head = headBuf.subarray(0, headRead.bytesRead).toString('utf8')
359
+ const tail = tailBuf.subarray(0, tailRead.bytesRead).toString('utf8')
360
+ return { text: `${head}\n...\n${tail}`, start, end: size, size }
361
+ } finally {
362
+ await file.close()
363
+ }
364
+ }
365
+
366
+ export function watchEventMatches(filename: string | Buffer | null, fileName: string): boolean {
367
+ return filename === null || filename.toString() === fileName
368
+ }
369
+
370
+ export function watchForWrite(
371
+ taskId: string,
372
+ fromOffset: number,
373
+ onWrite: (text: string, start: number, end: number, size: number) => void,
374
+ onExit: () => void
375
+ ): AbortController {
376
+ const rec = registry.get(taskId)
377
+ if (!rec) throw new Error(`No such task: ${taskId}`)
378
+ const controller = new AbortController()
379
+ const dir = taskLogDir()
380
+ const fileName = basename(rec.logPath)
381
+ let watcher: ReturnType<typeof watch> | undefined
382
+ let pollTimer: ReturnType<typeof setInterval> | undefined
383
+ let settled = false
384
+ let checking: Promise<boolean> | undefined
385
+ let pending = false
386
+
387
+ const stopPolling = () => {
388
+ if (pollTimer) clearInterval(pollTimer)
389
+ pollTimer = undefined
390
+ }
391
+ const stop = () => {
392
+ if (settled) return
393
+ settled = true
394
+ watcher?.close()
395
+ stopPolling()
396
+ }
397
+
398
+ const check = (): Promise<boolean> => {
399
+ if (checking) {
400
+ pending = true
401
+ return checking
402
+ }
403
+ checking = (async (): Promise<boolean> => {
404
+ if (settled) return false
405
+ try {
406
+ const st = await stat(rec.logPath)
407
+ if (st.size <= fromOffset) return false
408
+ const { text, start, end, size } = await readNewBytes(taskId, fromOffset)
409
+ stop()
410
+ onWrite(text, start, end, size)
411
+ return true
412
+ } catch {
413
+ return false
414
+ }
415
+ })().finally(() => {
416
+ checking = undefined
417
+ if (pending && !settled) {
418
+ pending = false
419
+ void check()
420
+ }
421
+ })
422
+ return checking
423
+ }
424
+
425
+ const startPolling = (): void => {
426
+ if (pollTimer) return
427
+ pollTimer = setInterval(() => void check(), 250)
428
+ pollTimer.unref()
429
+ }
430
+
431
+ const finishWithoutOutput = async (wrote: boolean): Promise<void> => {
432
+ if (wrote || settled) return
433
+ stop()
434
+ try {
435
+ onExit()
436
+ } catch {}
437
+ }
438
+
439
+ if (rec.exitCode !== null || rec.signal !== null) {
440
+ void check().then(finishWithoutOutput)
441
+ return controller
442
+ }
443
+
444
+ const exitBridge = () => {
445
+ if (settled) return
446
+ void (checking ?? Promise.resolve(false)).then(() => check()).then(finishWithoutOutput)
447
+ }
448
+ rec.exitWaiters.add(exitBridge)
449
+
450
+ try {
451
+ watcher = watch(dir, (_event, filename) => {
452
+ if (watchEventMatches(filename, fileName)) void check()
453
+ if (filename === null) startPolling()
454
+ })
455
+ } catch {
456
+ startPolling()
457
+ }
458
+
459
+ void check()
460
+
461
+ controller.signal.addEventListener('abort', () => {
462
+ rec.exitWaiters.delete(exitBridge)
463
+ stop()
464
+ })
465
+ return controller
466
+ }
467
+
468
+ interface MiddleOutView {
469
+ head: string
470
+ tail: string
471
+ omitted: number
472
+ total: number
473
+ }
474
+
475
+ export function benignExitNote(
476
+ isError: boolean,
477
+ command: string,
478
+ exitCode: number | undefined,
479
+ raisedText: string
480
+ ): string | undefined {
481
+ if (!isError) return undefined
482
+ if (exitCode === 1 && isNoMatchCommand(command)) {
483
+ return '\n[Note: exit 1 here means no matches found, not an error.]'
484
+ }
485
+ if (exitCode === undefined && /^Command timed out after\b/.test(raisedText.trimEnd().split('\n').at(-1) ?? '')) {
486
+ return '\n[Note: the command timed out and was killed; not a clean exit.]'
487
+ }
488
+ return undefined
489
+ }
490
+
491
+ export function isNoMatchCommand(command: string): boolean {
492
+ return /^(?:grep|rg)\b[^|&;\n]*$/.test(command.trim())
493
+ }
494
+
495
+ export function middleOut(text: string, maxBytes: number): MiddleOutView {
496
+ const total = Buffer.byteLength(text, 'utf8')
497
+ if (total <= maxBytes) {
498
+ return { head: text, tail: '', omitted: 0, total }
499
+ }
500
+ const half = Math.floor(maxBytes / 2)
501
+ const buf = Buffer.from(text, 'utf8')
502
+ let headEnd = half
503
+ let headByte = headEnd < buf.length ? buf[headEnd] : undefined
504
+ while (headEnd > 0 && headByte !== undefined && (headByte & 0xc0) === 0x80) {
505
+ headEnd--
506
+ headByte = headEnd < buf.length ? buf[headEnd] : undefined
507
+ }
508
+ const head = buf.subarray(0, headEnd).toString('utf8')
509
+ let tailStart = Math.max(headEnd, total - (maxBytes - headEnd))
510
+ let tailByte = tailStart < buf.length ? buf[tailStart] : undefined
511
+ while (tailByte !== undefined && (tailByte & 0xc0) === 0x80) {
512
+ tailStart++
513
+ tailByte = tailStart < buf.length ? buf[tailStart] : undefined
514
+ }
515
+ const tail = buf.subarray(tailStart).toString('utf8')
516
+ const headBytes = headEnd
517
+ const tailBytes = buf.length - tailStart
518
+ return { head, tail, omitted: total - headBytes - tailBytes, total }
519
+ }
package/src/stall.ts ADDED
@@ -0,0 +1,46 @@
1
+ import { statSync } from 'node:fs'
2
+
3
+ import { registry } from './process.js'
4
+ import type { TaskRecord } from './process.js'
5
+
6
+ export const STALL_MS = 10 * 60 * 1000
7
+ const STALL_CHECK_MS = 30 * 1000
8
+
9
+ export interface StallState {
10
+ size: number
11
+ since: number
12
+ reported: boolean
13
+ }
14
+
15
+ export interface StallStep {
16
+ next: StallState
17
+ report: boolean
18
+ }
19
+
20
+ export function advanceStall(prev: StallState, size: number, now: number): StallStep {
21
+ if (size !== prev.size) return { next: { size, since: now, reported: false }, report: false }
22
+ if (prev.reported || now - prev.since < STALL_MS) return { next: prev, report: false }
23
+ return { next: { ...prev, reported: true }, report: true }
24
+ }
25
+
26
+ export function watchStall(rec: TaskRecord, onStall: (silentMs: number) => void): void {
27
+ let state: StallState = { size: -1, since: Date.now(), reported: false }
28
+ const timer = setInterval(() => {
29
+ const live = registry.get(rec.taskId)
30
+ if (!live || live.exitCode !== null || live.signal !== null) {
31
+ clearInterval(timer)
32
+ return
33
+ }
34
+ let size: number
35
+ try {
36
+ size = statSync(rec.logPath).size
37
+ } catch {
38
+ return
39
+ }
40
+ const now = Date.now()
41
+ const step = advanceStall(state, size, now)
42
+ state = step.next
43
+ if (step.report) onStall(now - state.since)
44
+ }, STALL_CHECK_MS)
45
+ timer.unref()
46
+ }