@namzu/computer-use 4.2.1 → 4.3.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/CHANGELOG.md +16 -0
- package/README.md +5 -1
- package/dist/SubprocessComputerUseHost.d.ts +1 -1
- package/dist/SubprocessComputerUseHost.d.ts.map +1 -1
- package/dist/adapters/cua-driver/adapter.d.ts +1 -1
- package/dist/adapters/cua-driver/adapter.d.ts.map +1 -1
- package/dist/adapters/cua-driver/adapter.js +4 -3
- package/dist/adapters/cua-driver/adapter.js.map +1 -1
- package/dist/adapters/cua-driver/provision.d.ts +20 -0
- package/dist/adapters/cua-driver/provision.d.ts.map +1 -1
- package/dist/adapters/cua-driver/provision.js +59 -2
- package/dist/adapters/cua-driver/provision.js.map +1 -1
- package/dist/adapters/win32.d.ts +2 -0
- package/dist/adapters/win32.d.ts.map +1 -1
- package/dist/adapters/win32.js +1 -0
- package/dist/adapters/win32.js.map +1 -1
- package/dist/foreground/guard.js +3 -3
- package/dist/foreground/guard.js.map +1 -1
- package/dist/foreground/ladder.d.ts +15 -1
- package/dist/foreground/ladder.d.ts.map +1 -1
- package/dist/foreground/ladder.js +131 -33
- package/dist/foreground/ladder.js.map +1 -1
- package/dist/foreground/types.d.ts +15 -0
- package/dist/foreground/types.d.ts.map +1 -1
- package/dist/foreground/types.js.map +1 -1
- package/dist/foreground/windows-helper-script.d.ts.map +1 -1
- package/dist/foreground/windows-helper-script.js +8 -1
- package/dist/foreground/windows-helper-script.js.map +1 -1
- package/dist/foreground/windows-monitor.d.ts +33 -1
- package/dist/foreground/windows-monitor.d.ts.map +1 -1
- package/dist/foreground/windows-monitor.js +129 -6
- package/dist/foreground/windows-monitor.js.map +1 -1
- package/package.json +2 -2
- package/src/SubprocessComputerUseHost.ts +1 -1
- package/src/adapters/cua-driver/adapter.ts +9 -4
- package/src/adapters/cua-driver/provision.ts +72 -2
- package/src/adapters/win32.ts +3 -0
- package/src/foreground/guard.ts +3 -3
- package/src/foreground/ladder.ts +128 -27
- package/src/foreground/types.ts +15 -0
- package/src/foreground/windows-helper-script.ts +8 -1
- package/src/foreground/windows-monitor.ts +150 -7
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { createHash } from 'node:crypto'
|
|
2
|
-
import { chmod, mkdir, readFile, rename, rm, stat, writeFile } from 'node:fs/promises'
|
|
2
|
+
import { chmod, mkdir, readFile, readdir, rename, rm, stat, writeFile } from 'node:fs/promises'
|
|
3
3
|
import { homedir } from 'node:os'
|
|
4
|
-
import { join } from 'node:path'
|
|
4
|
+
import { basename, dirname, join, resolve } from 'node:path'
|
|
5
5
|
import { extractZipEntry } from './zip.js'
|
|
6
6
|
|
|
7
7
|
/**
|
|
@@ -61,6 +61,11 @@ export interface ResolveCuaDriverOptions {
|
|
|
61
61
|
readonly env?: NodeJS.ProcessEnv
|
|
62
62
|
/** How long the archive download may take. Default 180 s. */
|
|
63
63
|
readonly downloadTimeoutMs?: number
|
|
64
|
+
/**
|
|
65
|
+
* Told, once and in plain words, before the pinned build is downloaded, so a person
|
|
66
|
+
* waiting on the first use knows why. Not called when the build is cached.
|
|
67
|
+
*/
|
|
68
|
+
readonly onDownload?: (notice: string) => void
|
|
64
69
|
/** For tests. */
|
|
65
70
|
readonly fetch?: typeof fetch
|
|
66
71
|
/** For tests: another pin than the architecture's. */
|
|
@@ -127,6 +132,7 @@ export async function resolveCuaDriver(
|
|
|
127
132
|
const exe = join(dir, EXE_NAME)
|
|
128
133
|
|
|
129
134
|
if (await isPinnedExecutable(exe, asset.exeSize, asset.exeSha256)) {
|
|
135
|
+
await removeSupersededCuaDrivers(dir, { env: options.env })
|
|
130
136
|
return { path: exe, source: 'cache' }
|
|
131
137
|
}
|
|
132
138
|
if (options.download === false) {
|
|
@@ -136,6 +142,9 @@ export async function resolveCuaDriver(
|
|
|
136
142
|
}
|
|
137
143
|
|
|
138
144
|
const url = cuaDriverDownloadUrl(asset.archive)
|
|
145
|
+
options.onDownload?.(
|
|
146
|
+
`Namzu is downloading the computer-use helper (cua-driver ${CUA_DRIVER_RELEASE.version}, about ${Math.max(1, Math.round(asset.archiveSize / 1_000_000))} MB) once. It is checked before it is used, so the first use takes a little longer.`,
|
|
147
|
+
)
|
|
139
148
|
const archive = await download(url, options.fetch ?? fetch, options.downloadTimeoutMs ?? 180_000)
|
|
140
149
|
if (archive.length !== asset.archiveSize || sha256(archive) !== asset.archiveSha256) {
|
|
141
150
|
throw new CuaDriverUnavailableError(
|
|
@@ -163,9 +172,70 @@ export async function resolveCuaDriver(
|
|
|
163
172
|
}
|
|
164
173
|
const written = await stat(exe)
|
|
165
174
|
verified.set(exe, `${written.size}:${written.mtimeMs}`)
|
|
175
|
+
await removeSupersededCuaDrivers(dir, { env: options.env })
|
|
166
176
|
return { path: exe, source: 'download' }
|
|
167
177
|
}
|
|
168
178
|
|
|
179
|
+
/** A cache folder named like a release: `0.28.2`. Nothing else in the cache is Namzu's to remove. */
|
|
180
|
+
const VERSION_FOLDER = /^\d+\.\d+\.\d+$/
|
|
181
|
+
|
|
182
|
+
/** A folder touched within this long is not cleaned: someone may be writing into it or about to run it. */
|
|
183
|
+
const RECENT_MS = 60 * 60 * 1000
|
|
184
|
+
|
|
185
|
+
export interface RemoveSupersededOptions {
|
|
186
|
+
readonly env?: NodeJS.ProcessEnv | undefined
|
|
187
|
+
/** The clock, for tests. */
|
|
188
|
+
readonly now?: number
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
const versionParts = (name: string): number[] => name.split('.').map(Number)
|
|
192
|
+
|
|
193
|
+
function isOlder(candidate: string, pinned: string): boolean {
|
|
194
|
+
const a = versionParts(candidate)
|
|
195
|
+
const b = versionParts(pinned)
|
|
196
|
+
for (let i = 0; i < 3; i++) {
|
|
197
|
+
if ((a[i] ?? 0) !== (b[i] ?? 0)) return (a[i] ?? 0) < (b[i] ?? 0)
|
|
198
|
+
}
|
|
199
|
+
return false
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
/**
|
|
203
|
+
* Removes the older builds beside the one in use. `keep` is the folder of the build now in use.
|
|
204
|
+
* Only when it sits in Namzu's own cache (`<NAMZU_HOME>/computer-use/cua-driver/<version>`) are its
|
|
205
|
+
* sibling folders looked at; a cache directory the caller chose is never swept. Only a folder named
|
|
206
|
+
* like a version and strictly older than `keep` is removed, so a newer Namzu's build is never
|
|
207
|
+
* deleted by an older one. A file, a link, a folder with any other name, a folder holding a
|
|
208
|
+
* `.partial` download or touched within the last hour, and the kept folder are left alone, and a
|
|
209
|
+
* build that cannot be removed (still running) is skipped.
|
|
210
|
+
*/
|
|
211
|
+
export async function removeSupersededCuaDrivers(
|
|
212
|
+
keep: string,
|
|
213
|
+
options: RemoveSupersededOptions = {},
|
|
214
|
+
): Promise<string[]> {
|
|
215
|
+
const pinned = basename(keep)
|
|
216
|
+
if (!VERSION_FOLDER.test(pinned)) return []
|
|
217
|
+
const parent = dirname(keep)
|
|
218
|
+
if (resolve(parent) !== resolve(dirname(defaultCuaDriverCacheDir(options.env)))) return []
|
|
219
|
+
const now = options.now ?? Date.now()
|
|
220
|
+
const entries = await readdir(parent, { withFileTypes: true }).catch(() => [])
|
|
221
|
+
const removed: string[] = []
|
|
222
|
+
for (const entry of entries) {
|
|
223
|
+
if (!entry.isDirectory() || !VERSION_FOLDER.test(entry.name)) continue
|
|
224
|
+
if (!isOlder(entry.name, pinned)) continue
|
|
225
|
+
const folder = join(parent, entry.name)
|
|
226
|
+
try {
|
|
227
|
+
const found = await stat(folder)
|
|
228
|
+
if (now - found.mtimeMs < RECENT_MS) continue
|
|
229
|
+
if ((await readdir(folder)).some((name) => name.endsWith('.partial'))) continue
|
|
230
|
+
await rm(folder, { recursive: true })
|
|
231
|
+
removed.push(entry.name)
|
|
232
|
+
} catch {
|
|
233
|
+
// In use or protected: it stays, and the next start tries again.
|
|
234
|
+
}
|
|
235
|
+
}
|
|
236
|
+
return removed
|
|
237
|
+
}
|
|
238
|
+
|
|
169
239
|
async function isPinnedExecutable(path: string, size: number, digest: string): Promise<boolean> {
|
|
170
240
|
const found = await stat(path).catch(() => undefined)
|
|
171
241
|
if (!found?.isFile() || found.size !== size) return false
|
package/src/adapters/win32.ts
CHANGED
|
@@ -31,6 +31,8 @@ export interface Win32AdapterOptions {
|
|
|
31
31
|
readonly cacheDir?: string
|
|
32
32
|
/** Download the pinned build when it is missing. Default true. */
|
|
33
33
|
readonly download?: boolean
|
|
34
|
+
/** Told once, in plain words, before the pinned build is downloaded. */
|
|
35
|
+
readonly onNotice?: (notice: string) => void
|
|
34
36
|
readonly env?: NodeJS.ProcessEnv
|
|
35
37
|
readonly platform?: NodeJS.Platform
|
|
36
38
|
/**
|
|
@@ -123,6 +125,7 @@ export class Win32Adapter {
|
|
|
123
125
|
...(cuaDriverPath !== undefined ? { path: cuaDriverPath } : {}),
|
|
124
126
|
...(options.cacheDir !== undefined ? { cacheDir: options.cacheDir } : {}),
|
|
125
127
|
...(options.download !== undefined ? { download: options.download } : {}),
|
|
128
|
+
...(options.onNotice ? { onDownload: options.onNotice } : {}),
|
|
126
129
|
}
|
|
127
130
|
const resolved = await (options.resolve ?? resolveCuaDriver)(resolveOptions)
|
|
128
131
|
const wsl = isWsl(env, platform, probes)
|
package/src/foreground/guard.ts
CHANGED
|
@@ -7,7 +7,7 @@ import type {
|
|
|
7
7
|
import type { Adapter } from '../adapters/types.js'
|
|
8
8
|
import { currentCallSignal } from '../util/call-scope.js'
|
|
9
9
|
import type { ForegroundLadder } from './ladder.js'
|
|
10
|
-
import { STOPPED_TEXT } from './ladder.js'
|
|
10
|
+
import { STOPPED_TEXT, blockDetailWithRefAdvice } from './ladder.js'
|
|
11
11
|
import type { ForegroundOutcome, ForegroundSubject } from './types.js'
|
|
12
12
|
|
|
13
13
|
/** Display actions that put input on the user's screen. */
|
|
@@ -98,7 +98,7 @@ export function guardForeground(adapter: Adapter, ladder: ForegroundLadder): Ada
|
|
|
98
98
|
type: 'ok',
|
|
99
99
|
delivery: 'not_delivered',
|
|
100
100
|
retrySafety: 'safe',
|
|
101
|
-
detail: outcome.block
|
|
101
|
+
detail: blockDetailWithRefAdvice(outcome.block),
|
|
102
102
|
}
|
|
103
103
|
const dropped = droppedInputNote(outcome)
|
|
104
104
|
if (dropped)
|
|
@@ -150,7 +150,7 @@ export function guardForeground(adapter: Adapter, ladder: ForegroundLadder): Ada
|
|
|
150
150
|
focusedId: null,
|
|
151
151
|
delivery: 'not_delivered',
|
|
152
152
|
retrySafety: 'safe',
|
|
153
|
-
detail: outcome.block
|
|
153
|
+
detail: blockDetailWithRefAdvice(outcome.block),
|
|
154
154
|
}
|
|
155
155
|
const note = interferenceNote(outcome)
|
|
156
156
|
return note ? { ...outcome.value, detail: note } : outcome.value
|
package/src/foreground/ladder.ts
CHANGED
|
@@ -101,6 +101,23 @@ export interface ForegroundLadderOptions {
|
|
|
101
101
|
export const STOPPED_TEXT =
|
|
102
102
|
'The user pressed Escape, so computer use is stopped for the rest of this turn. Stop now: tell the user what is still undone, and do not call computer_use again until they send a new message.'
|
|
103
103
|
|
|
104
|
+
/**
|
|
105
|
+
* A block's detail for a caller where controls by ref (ui_act) are a real
|
|
106
|
+
* alternative to the screen (display actions, window actions): the helper
|
|
107
|
+
* being down does not touch them, so it says so.
|
|
108
|
+
*/
|
|
109
|
+
export function blockDetailWithRefAdvice(block: ForegroundBlock): string {
|
|
110
|
+
return block.code === 'monitor_unavailable'
|
|
111
|
+
? `${block.detail} Controls by ref (ui_act) still work in the background.`
|
|
112
|
+
: block.detail
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
/** A block's detail for ui_act's own fallbacks to the screen: the model must not be sent back into ui_act. */
|
|
116
|
+
export function uiActBlockDetail(block: ForegroundBlock): string {
|
|
117
|
+
if (block.code !== 'monitor_unavailable') return block.detail
|
|
118
|
+
return `The control could not be pressed in the background, and the screen could not be used because this computer cannot watch for the user's keyboard and mouse (${block.reason ?? 'the helper is not available'}). Nothing was sent. Try another control, or ask the user to do this step.`
|
|
119
|
+
}
|
|
120
|
+
|
|
104
121
|
const seconds = (ms: number): string => `${Math.max(1, Math.round(ms / 1000))} s`
|
|
105
122
|
|
|
106
123
|
const BLOCKS = {
|
|
@@ -127,7 +144,8 @@ const BLOCKS = {
|
|
|
127
144
|
}),
|
|
128
145
|
monitor_unavailable: (reason: string): ForegroundBlock => ({
|
|
129
146
|
code: 'monitor_unavailable',
|
|
130
|
-
detail: `This computer cannot watch for the user's keyboard and mouse (${reason}), so the screen is not used and nothing was sent.
|
|
147
|
+
detail: `This computer cannot watch for the user's keyboard and mouse (${reason}), so the screen is not used and nothing was sent. Ask the user to do this step if it needs the screen.`,
|
|
148
|
+
reason,
|
|
131
149
|
}),
|
|
132
150
|
declined: (app: string): ForegroundBlock => ({
|
|
133
151
|
code: 'declined',
|
|
@@ -147,6 +165,25 @@ const BLOCKS = {
|
|
|
147
165
|
/** Times a burst start is retried because input arrived between the last look and the start. */
|
|
148
166
|
const MAX_INTERFERED_STARTS = 3
|
|
149
167
|
|
|
168
|
+
/** What the monitor says when a request or the start gets no answer. */
|
|
169
|
+
const NO_ANSWER = 'did not answer in time'
|
|
170
|
+
|
|
171
|
+
function isNoAnswer(error: unknown): boolean {
|
|
172
|
+
return error instanceof Error && error.message.includes(NO_ANSWER)
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
/**
|
|
176
|
+
* A call made before anything was sent failed because the helper is gone or
|
|
177
|
+
* hung, so it can be replaced and the run repeated. An error the helper
|
|
178
|
+
* reports about one command while it runs is not this.
|
|
179
|
+
*/
|
|
180
|
+
function helperGone(monitor: ForegroundMonitor, error: unknown): boolean {
|
|
181
|
+
return monitor.running === false || isNoAnswer(error)
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
/** The helper ended while a burst was sending; said to the caller as the burst's failure. */
|
|
185
|
+
export const HELPER_STOPPED_MID_BURST = 'the keyboard-and-mouse helper stopped during the action'
|
|
186
|
+
|
|
150
187
|
interface Stop {
|
|
151
188
|
readonly turnId: string | undefined
|
|
152
189
|
}
|
|
@@ -196,6 +233,10 @@ export class ForegroundLadder {
|
|
|
196
233
|
private turn: string | undefined
|
|
197
234
|
private readonly allowed = new Set<string>()
|
|
198
235
|
private readonly denied = new Set<string>()
|
|
236
|
+
/** Programs the user could not be asked about this turn; they are not asked again. */
|
|
237
|
+
private readonly unanswered = new Set<string>()
|
|
238
|
+
/** Why the helper could not be started twice in a row; answered until the turn ends. */
|
|
239
|
+
private startFailure: string | undefined
|
|
199
240
|
|
|
200
241
|
constructor(private readonly options: ForegroundLadderOptions) {
|
|
201
242
|
this.timing = { ...DEFAULT_TIMING, ...options.timing }
|
|
@@ -224,6 +265,8 @@ export class ForegroundLadder {
|
|
|
224
265
|
if (this.stop && (turnId === undefined || turnId !== this.stop.turnId)) this.stop = undefined
|
|
225
266
|
if (turnId === undefined || turnId !== this.turn) {
|
|
226
267
|
this.denied.clear()
|
|
268
|
+
this.unanswered.clear()
|
|
269
|
+
this.startFailure = undefined
|
|
227
270
|
this.parkedMs = 0
|
|
228
271
|
}
|
|
229
272
|
this.turn = turnId
|
|
@@ -305,9 +348,12 @@ export class ForegroundLadder {
|
|
|
305
348
|
/** The model's turn ended or was interrupted: nothing stays watched or held. */
|
|
306
349
|
async endTurn(): Promise<void> {
|
|
307
350
|
this.denied.clear()
|
|
351
|
+
this.unanswered.clear()
|
|
308
352
|
// A burst in flight puts its window and cursor back through the monitor
|
|
309
353
|
// when it ends; dropping the monitor first would restore under it.
|
|
310
354
|
await this.queue
|
|
355
|
+
// After the wait: a queued run that finished meanwhile may have set it.
|
|
356
|
+
this.startFailure = undefined
|
|
311
357
|
await this.dropMonitor()
|
|
312
358
|
}
|
|
313
359
|
|
|
@@ -330,6 +376,7 @@ export class ForegroundLadder {
|
|
|
330
376
|
request: LadderRequest,
|
|
331
377
|
burst: (context: BurstContext) => Promise<T>,
|
|
332
378
|
attempt = 0,
|
|
379
|
+
restarted = false,
|
|
333
380
|
): Promise<ForegroundOutcome<T>> {
|
|
334
381
|
const { subject, signal } = request
|
|
335
382
|
if (this.stop) return { kind: 'blocked', block: BLOCKS.stopped() }
|
|
@@ -349,17 +396,44 @@ export class ForegroundLadder {
|
|
|
349
396
|
}
|
|
350
397
|
let deferred = false
|
|
351
398
|
try {
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
399
|
+
let state: Awaited<ReturnType<ForegroundLadder['gate']>>
|
|
400
|
+
let begun: Awaited<ReturnType<ForegroundMonitor['begin']>>
|
|
401
|
+
let startedAt: number
|
|
402
|
+
let beginSent = false
|
|
403
|
+
try {
|
|
404
|
+
state = await this.gate(monitor.monitor, subject, signal)
|
|
405
|
+
if ('block' in state) return { kind: 'blocked', block: state.block }
|
|
406
|
+
startedAt = this.clock.now()
|
|
407
|
+
beginSent = true
|
|
408
|
+
begun = await monitor.monitor.begin({
|
|
409
|
+
leasePath: this.lease.path,
|
|
410
|
+
token,
|
|
411
|
+
// Checked by the monitor before it raises anything, so a person who
|
|
412
|
+
// started typing after the last look is not displaced.
|
|
413
|
+
idleMs: state.needed,
|
|
414
|
+
...(subject.hwnd !== undefined ? { raise: subject.hwnd } : {}),
|
|
415
|
+
})
|
|
416
|
+
} catch (error) {
|
|
417
|
+
if (error instanceof CallAbortedError) throw error
|
|
418
|
+
const gone = helperGone(monitor.monitor, error)
|
|
419
|
+
// A helper that is still answering may have raised the target window
|
|
420
|
+
// before it failed: put it back, as an interfered start does.
|
|
421
|
+
if (beginSent && !gone) await monitor.monitor.end({ restore: true }).catch(() => undefined)
|
|
422
|
+
// An error the live helper reported about this command is the caller's.
|
|
423
|
+
if (!gone) throw error
|
|
424
|
+
// Nothing has been sent yet: a helper that died or hung here is replaced,
|
|
425
|
+
// once, and the run goes again. A second failure is a block, never a throw.
|
|
426
|
+
await this.dropMonitor()
|
|
427
|
+
if (restarted)
|
|
428
|
+
return {
|
|
429
|
+
kind: 'blocked',
|
|
430
|
+
block: BLOCKS.monitor_unavailable(
|
|
431
|
+
error instanceof Error ? error.message : String(error),
|
|
432
|
+
),
|
|
433
|
+
}
|
|
434
|
+
this.lease.release(token)
|
|
435
|
+
return await this.runOne(request, burst, attempt, true)
|
|
436
|
+
}
|
|
363
437
|
// A person touched input between the last look and now: not yet.
|
|
364
438
|
if (begun.refused === true || begun.userInputs !== state.state.userInputs) {
|
|
365
439
|
if (attempt >= MAX_INTERFERED_STARTS) {
|
|
@@ -375,6 +449,7 @@ export class ForegroundLadder {
|
|
|
375
449
|
burst,
|
|
376
450
|
token,
|
|
377
451
|
attempt + 1,
|
|
452
|
+
restarted,
|
|
378
453
|
)
|
|
379
454
|
}
|
|
380
455
|
const beat = setInterval(
|
|
@@ -388,7 +463,11 @@ export class ForegroundLadder {
|
|
|
388
463
|
value = await burst({
|
|
389
464
|
checkpoint: async () => {
|
|
390
465
|
if (!this.lease.heartbeat(token)) throw new BurstInterrupted()
|
|
391
|
-
const now = await monitor.monitor.state()
|
|
466
|
+
const now = await monitor.monitor.state().catch((error: unknown) => {
|
|
467
|
+
// A helper that ended mid-burst is never restarted inside it: the burst stops here.
|
|
468
|
+
if (monitor.monitor.running === false) throw new Error(HELPER_STOPPED_MID_BURST)
|
|
469
|
+
throw error
|
|
470
|
+
})
|
|
392
471
|
if (now.userInputs !== begun.userInputs) throw new BurstInterrupted()
|
|
393
472
|
// The hooks see nothing typed into a window above this program's rights,
|
|
394
473
|
// so a person there cannot be told from silence: stop rather than guess.
|
|
@@ -405,7 +484,13 @@ export class ForegroundLadder {
|
|
|
405
484
|
},
|
|
406
485
|
})
|
|
407
486
|
} catch (error) {
|
|
408
|
-
failure
|
|
487
|
+
// A helper that ended during the burst's own calls is the burst's failure, in the same words.
|
|
488
|
+
failure = {
|
|
489
|
+
error:
|
|
490
|
+
monitor.monitor.running === false && !(error instanceof BurstInterrupted)
|
|
491
|
+
? new Error(HELPER_STOPPED_MID_BURST)
|
|
492
|
+
: error,
|
|
493
|
+
}
|
|
409
494
|
} finally {
|
|
410
495
|
clearInterval(beat)
|
|
411
496
|
}
|
|
@@ -485,30 +570,42 @@ export class ForegroundLadder {
|
|
|
485
570
|
burst: (context: BurstContext) => Promise<T>,
|
|
486
571
|
token: string,
|
|
487
572
|
attempt: number,
|
|
573
|
+
restarted: boolean,
|
|
488
574
|
): Promise<ForegroundOutcome<T>> {
|
|
489
575
|
// A raise that happened just before a person's input is undone too.
|
|
490
576
|
await monitor.end({ restore: true }).catch(() => undefined)
|
|
491
577
|
// The lease is ours until runOne's finally; release it so the nested run takes it afresh.
|
|
492
578
|
this.lease.release(token)
|
|
493
|
-
return this.runOne(request, burst, attempt)
|
|
579
|
+
return this.runOne(request, burst, attempt, restarted)
|
|
494
580
|
}
|
|
495
581
|
|
|
496
582
|
private async ensureMonitor(): Promise<
|
|
497
583
|
{ readonly ok: true; readonly monitor: ForegroundMonitor } | { ok: false; reason: string }
|
|
498
584
|
> {
|
|
499
|
-
if (this.monitor)
|
|
500
|
-
|
|
501
|
-
|
|
502
|
-
await
|
|
503
|
-
}
|
|
504
|
-
|
|
505
|
-
|
|
506
|
-
|
|
507
|
-
|
|
585
|
+
if (this.monitor) {
|
|
586
|
+
if (this.monitor.running !== false) return { ok: true, monitor: this.monitor }
|
|
587
|
+
// The helper ended since it was last used: it is replaced, not reported.
|
|
588
|
+
await this.dropMonitor()
|
|
589
|
+
}
|
|
590
|
+
if (this.startFailure !== undefined) return { ok: false, reason: this.startFailure }
|
|
591
|
+
let reason = ''
|
|
592
|
+
// A transient spawn or pipe failure gets one more try before it costs the user the action.
|
|
593
|
+
for (let attempt = 0; attempt < 2; attempt++) {
|
|
594
|
+
const monitor = this.options.createMonitor()
|
|
595
|
+
try {
|
|
596
|
+
await monitor.start()
|
|
597
|
+
} catch (error) {
|
|
598
|
+
await monitor.dispose().catch(() => undefined)
|
|
599
|
+
reason = error instanceof Error ? error.message : String(error)
|
|
600
|
+
// A start that waited out its whole timeout is not tried again: that would wait twice as long.
|
|
601
|
+
if (isNoAnswer(error)) break
|
|
602
|
+
continue
|
|
508
603
|
}
|
|
604
|
+
this.monitor = monitor
|
|
605
|
+
return { ok: true, monitor }
|
|
509
606
|
}
|
|
510
|
-
this.
|
|
511
|
-
return { ok:
|
|
607
|
+
this.startFailure = reason
|
|
608
|
+
return { ok: false, reason }
|
|
512
609
|
}
|
|
513
610
|
|
|
514
611
|
private async dropMonitor(): Promise<void> {
|
|
@@ -567,7 +664,11 @@ export class ForegroundLadder {
|
|
|
567
664
|
) {
|
|
568
665
|
if (phase === 'gate' && !signal?.aborted) {
|
|
569
666
|
if (this.denied.has(key)) return { block: BLOCKS.declined(who.app) }
|
|
570
|
-
|
|
667
|
+
// A run repeated with a fresh helper does not put the question again.
|
|
668
|
+
const answer = this.unanswered.has(key)
|
|
669
|
+
? 'unavailable'
|
|
670
|
+
: ((await this.options.approve?.(who, signal)) ?? 'unavailable')
|
|
671
|
+
if (answer === 'unavailable') this.unanswered.add(key)
|
|
571
672
|
if (answer === 'deny') {
|
|
572
673
|
this.denied.add(key)
|
|
573
674
|
return { block: BLOCKS.declined(who.app) }
|
package/src/foreground/types.ts
CHANGED
|
@@ -181,6 +181,15 @@ export interface MenuCommandResult {
|
|
|
181
181
|
export interface ForegroundMonitor {
|
|
182
182
|
/** Starts watching. Rejects when real input cannot be observed: the burst is then refused. */
|
|
183
183
|
start(): Promise<void>
|
|
184
|
+
/**
|
|
185
|
+
* False once a started monitor can no longer answer (the helper process
|
|
186
|
+
* ended). The ladder then replaces it before its next use. Optional: a
|
|
187
|
+
* monitor that leaves it out is taken to keep running.
|
|
188
|
+
*
|
|
189
|
+
* A helper that ends in the middle of a burst cannot put the window and
|
|
190
|
+
* cursor back: the burst fails with a clear error and is never restarted.
|
|
191
|
+
*/
|
|
192
|
+
readonly running?: boolean
|
|
184
193
|
state(query?: { readonly pid?: number }): Promise<MonitorState>
|
|
185
194
|
/**
|
|
186
195
|
* A burst is about to start. The monitor remembers the window in front, the
|
|
@@ -249,6 +258,12 @@ export interface ForegroundBlock {
|
|
|
249
258
|
readonly code: ForegroundBlockCode
|
|
250
259
|
/** In words the model can act on: what is blocking, and what to do next. */
|
|
251
260
|
readonly detail: string
|
|
261
|
+
/**
|
|
262
|
+
* For `monitor_unavailable`: the bare cause ("the Windows helper stopped
|
|
263
|
+
* while starting (exit code 1): ..."), for a caller that words the advice
|
|
264
|
+
* itself.
|
|
265
|
+
*/
|
|
266
|
+
readonly reason?: string
|
|
252
267
|
}
|
|
253
268
|
|
|
254
269
|
export type ForegroundOutcome<T> =
|
|
@@ -19,6 +19,12 @@ export const WINDOWS_HELPER_SCRIPT = String.raw`
|
|
|
19
19
|
$ErrorActionPreference = 'Stop'
|
|
20
20
|
[Console]::OutputEncoding = New-Object System.Text.UTF8Encoding($false)
|
|
21
21
|
[Console]::InputEncoding = New-Object System.Text.UTF8Encoding($false)
|
|
22
|
+
function NzFail($what, $e) {
|
|
23
|
+
$o = @{ ok = $false; hooks = $false; hookError = ('{0}: {1}' -f $what, $e.Exception.Message); languageMode = [string]$ExecutionContext.SessionState.LanguageMode }
|
|
24
|
+
[Console]::Out.WriteLine((ConvertTo-Json -InputObject $o -Compress))
|
|
25
|
+
exit 1
|
|
26
|
+
}
|
|
27
|
+
try {
|
|
22
28
|
Add-Type -TypeDefinition @"
|
|
23
29
|
using System; using System.Text; using System.Threading; using System.Runtime.InteropServices;
|
|
24
30
|
public static class NzG {
|
|
@@ -301,7 +307,8 @@ public static class NzG {
|
|
|
301
307
|
}
|
|
302
308
|
}
|
|
303
309
|
"@
|
|
304
|
-
$
|
|
310
|
+
} catch { NzFail 'the hook library did not compile' $_ }
|
|
311
|
+
try { $hooks = [NzG]::StartHooks() } catch { NzFail 'the hooks did not start' $_ }
|
|
305
312
|
$selfIntegrity = [NzG]::SelfIntegrity()
|
|
306
313
|
$selfElevated = ($selfIntegrity -ge 12288)
|
|
307
314
|
$ownStart = 0; $ownEnd = 0
|