@namzu/computer-use 4.3.0 → 4.4.0
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 +18 -0
- package/README.md +5 -1
- package/dist/SubprocessComputerUseHost.d.ts +14 -1
- package/dist/SubprocessComputerUseHost.d.ts.map +1 -1
- package/dist/SubprocessComputerUseHost.js +52 -11
- package/dist/SubprocessComputerUseHost.js.map +1 -1
- package/dist/a11y/a11y.d.ts +1 -0
- package/dist/a11y/a11y.d.ts.map +1 -1
- package/dist/a11y/a11y.js +11 -0
- package/dist/a11y/a11y.js.map +1 -1
- package/dist/a11y/interface.d.ts +5 -0
- package/dist/a11y/interface.d.ts.map +1 -1
- package/dist/a11y/interface.js.map +1 -1
- package/dist/adapters/cua-driver/adapter.d.ts +26 -0
- package/dist/adapters/cua-driver/adapter.d.ts.map +1 -1
- package/dist/adapters/cua-driver/adapter.js +176 -3
- package/dist/adapters/cua-driver/adapter.js.map +1 -1
- package/dist/adapters/cua-driver/client.d.ts +5 -0
- package/dist/adapters/cua-driver/client.d.ts.map +1 -1
- package/dist/adapters/cua-driver/client.js +31 -0
- package/dist/adapters/cua-driver/client.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/types.d.ts +5 -0
- package/dist/adapters/types.d.ts.map +1 -1
- package/dist/adapters/types.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.d.ts.map +1 -1
- package/dist/foreground/guard.js +2 -0
- package/dist/foreground/guard.js.map +1 -1
- package/dist/presence/presence.d.ts +8 -0
- package/dist/presence/presence.d.ts.map +1 -1
- package/dist/presence/presence.js +15 -0
- package/dist/presence/presence.js.map +1 -1
- package/package.json +2 -2
- package/src/SubprocessComputerUseHost.ts +55 -9
- package/src/a11y/a11y.ts +11 -0
- package/src/a11y/interface.ts +5 -0
- package/src/adapters/cua-driver/adapter.ts +190 -2
- package/src/adapters/cua-driver/client.ts +27 -0
- package/src/adapters/cua-driver/provision.ts +72 -2
- package/src/adapters/types.ts +5 -0
- package/src/adapters/win32.ts +3 -0
- package/src/foreground/guard.ts +1 -0
- package/src/presence/presence.ts +20 -0
|
@@ -52,6 +52,7 @@ import { menuAcceleratorOf, translateKeyForCuaDriver } from './keys.js'
|
|
|
52
52
|
import {
|
|
53
53
|
type Observation,
|
|
54
54
|
type ObservedVerdict,
|
|
55
|
+
changeBetween,
|
|
55
56
|
judgeEdit,
|
|
56
57
|
judgeEditBetween,
|
|
57
58
|
judgeObserved,
|
|
@@ -154,6 +155,8 @@ const SPARSE_TREE = 12
|
|
|
154
155
|
const CHOICE_ROLES = /^(ComboBox|List|ListBox)$/i
|
|
155
156
|
/** Waits (ms) before each read that looks for an input's effect: at once, then a little later. */
|
|
156
157
|
const OBSERVE_WAITS_MS = [0, 80, 200, 450] as const
|
|
158
|
+
/** expand and collapse: a first read after the click, and a second one this much later that must agree. */
|
|
159
|
+
const EXPAND_WAITS_MS = [150, 450] as const
|
|
157
160
|
/**
|
|
158
161
|
* How old (ms) the window list read just before an input may be and still
|
|
159
162
|
* stand for the check that the window has not moved. A list takes over a
|
|
@@ -430,6 +433,8 @@ export class CuaDriverAdapter implements Adapter {
|
|
|
430
433
|
private driverCursorOff: boolean | undefined
|
|
431
434
|
/** cua-driver's screenshot resize registry is per PID, so only this capture may drive input. */
|
|
432
435
|
private windowFrame: WindowCaptureFrame | undefined
|
|
436
|
+
/** The process count at the last idle release, for a screenshot taken from that process. */
|
|
437
|
+
private releasedStarts: number | undefined
|
|
433
438
|
/** Capture and scoped input must not race over cua-driver's per-PID resize ratio. */
|
|
434
439
|
private windowOperation: Promise<void> = Promise.resolve()
|
|
435
440
|
/** Refs the model holds, by the adapter's ref. A handle is usable only in its window's latest read; otherwise the ref is found again. */
|
|
@@ -714,6 +719,27 @@ export class CuaDriverAdapter implements Adapter {
|
|
|
714
719
|
return this.serializeWindowOperation(() => this.captureWindowInternal(id))
|
|
715
720
|
}
|
|
716
721
|
|
|
722
|
+
/**
|
|
723
|
+
* Read the window again with a screenshot, so the driver can place pixels of `frame` on it.
|
|
724
|
+
* True when that read has the size of the screenshot the model is looking at.
|
|
725
|
+
*/
|
|
726
|
+
private async restoreDriverFrame(frame: WindowCaptureFrame): Promise<boolean> {
|
|
727
|
+
const hwnd = parseWindowId(frame.window.id)
|
|
728
|
+
if (hwnd === undefined) return false
|
|
729
|
+
try {
|
|
730
|
+
const result = await this.callTool('get_window_state', {
|
|
731
|
+
pid: frame.window.pid,
|
|
732
|
+
window_id: hwnd,
|
|
733
|
+
include_accessibility_tree: false,
|
|
734
|
+
include_screenshot: true,
|
|
735
|
+
})
|
|
736
|
+
const facts = structured(result, 'get_window_state')
|
|
737
|
+
return facts.screenshot_width === frame.width && facts.screenshot_height === frame.height
|
|
738
|
+
} catch {
|
|
739
|
+
return false
|
|
740
|
+
}
|
|
741
|
+
}
|
|
742
|
+
|
|
717
743
|
private async captureWindowInternal(id: string): Promise<WindowScreenshotResult> {
|
|
718
744
|
const target = await this.resolveWindow(id)
|
|
719
745
|
// A failed or overlapping capture invalidates the old resize ratio even
|
|
@@ -884,6 +910,7 @@ export class CuaDriverAdapter implements Adapter {
|
|
|
884
910
|
action: WindowInputAction,
|
|
885
911
|
route: InputRoute,
|
|
886
912
|
): Promise<WindowInputResult | undefined> {
|
|
913
|
+
await this.carryFrameOver(captureId)
|
|
887
914
|
const frame = this.windowFrame
|
|
888
915
|
const watched =
|
|
889
916
|
action.type === 'type_text' || action.type === 'key' || action.type === 'mouse_click'
|
|
@@ -1100,6 +1127,7 @@ export class CuaDriverAdapter implements Adapter {
|
|
|
1100
1127
|
route: InputRoute = { foreground: false, onScreen: false },
|
|
1101
1128
|
listing?: WindowListing,
|
|
1102
1129
|
): Promise<WindowInputResult | undefined> {
|
|
1130
|
+
await this.carryFrameOver(captureId)
|
|
1103
1131
|
const frame = this.windowFrame
|
|
1104
1132
|
if (!frame || frame.id !== captureId)
|
|
1105
1133
|
throw new Error(
|
|
@@ -1150,7 +1178,18 @@ export class CuaDriverAdapter implements Adapter {
|
|
|
1150
1178
|
)
|
|
1151
1179
|
this.showPresence(frame, current.bounds, name, args)
|
|
1152
1180
|
await this.markForSettle(target.window_id as number)
|
|
1153
|
-
|
|
1181
|
+
const sendOnce = () =>
|
|
1182
|
+
this.callTool(name, { ...target, ...args }, undefined, undefined, undefined, frame)
|
|
1183
|
+
try {
|
|
1184
|
+
return await sendOnce()
|
|
1185
|
+
} catch (error) {
|
|
1186
|
+
// The driver keeps one latest read per window, and a read of the controls (made just before
|
|
1187
|
+
// an input to judge it) replaces a screenshot with one that has none. It then refuses a
|
|
1188
|
+
// pixel input and sends nothing. The window is unchanged (checked above), so the same
|
|
1189
|
+
// screenshot is taken again for the driver and the input goes once more.
|
|
1190
|
+
if (!isNoDriverFrame(error) || !(await this.restoreDriverFrame(frame))) throw error
|
|
1191
|
+
return await sendOnce()
|
|
1192
|
+
}
|
|
1154
1193
|
}
|
|
1155
1194
|
// The driver's hotkey finds a shortcut only through an accelerator the window names, and refuses (sending
|
|
1156
1195
|
// nothing) when there is none; the same combination as a key with modifiers is real input.
|
|
@@ -1676,9 +1715,10 @@ export class CuaDriverAdapter implements Adapter {
|
|
|
1676
1715
|
)
|
|
1677
1716
|
try {
|
|
1678
1717
|
switch (action) {
|
|
1679
|
-
case 'invoke':
|
|
1680
1718
|
case 'expand':
|
|
1681
1719
|
case 'collapse':
|
|
1720
|
+
return await this.expandAndWatch(facts, uiRef, action)
|
|
1721
|
+
case 'invoke':
|
|
1682
1722
|
// cua-driver's click on an element token performs the control's
|
|
1683
1723
|
// own pattern in the background (Invoke, or a posted click at its
|
|
1684
1724
|
// centre), with no pointer move and no change of foreground.
|
|
@@ -2008,6 +2048,91 @@ export class CuaDriverAdapter implements Adapter {
|
|
|
2008
2048
|
}
|
|
2009
2049
|
}
|
|
2010
2050
|
|
|
2051
|
+
/**
|
|
2052
|
+
* expand or collapse, which the driver sends as a click and cannot read back: the control reports no
|
|
2053
|
+
* expanded state. What counts is what the window shows afterwards, and it has to still be there a
|
|
2054
|
+
* moment later. A menu that opened and closed again is not an expanded menu.
|
|
2055
|
+
*/
|
|
2056
|
+
private async expandAndWatch(
|
|
2057
|
+
facts: UiRefEntry,
|
|
2058
|
+
uiRef: { readonly ref: string; readonly facts: UiRefEntry },
|
|
2059
|
+
want: 'expand' | 'collapse',
|
|
2060
|
+
): Promise<UiActResult> {
|
|
2061
|
+
const target = { hwnd: facts.hwnd, pid: facts.pid }
|
|
2062
|
+
const before = await this.observe(target)
|
|
2063
|
+
const windows = await this.windowIdsOf(target.pid)
|
|
2064
|
+
// Each read of the window replaces the driver's handles: click through the refreshed one.
|
|
2065
|
+
const current = this.uiRefs.get(uiRef.ref) ?? facts
|
|
2066
|
+
const sent = await this.clickRef(current, { ref: uiRef.ref, facts: current })
|
|
2067
|
+
if (!sent.ok || sent.delivery === 'not_delivered') return sent
|
|
2068
|
+
const what = describeEvidence(current)
|
|
2069
|
+
const unverified = (detail: string): UiActResult => ({
|
|
2070
|
+
ok: true,
|
|
2071
|
+
delivery: 'delivered_unverified',
|
|
2072
|
+
retrySafety: 'unsafe',
|
|
2073
|
+
detail,
|
|
2074
|
+
})
|
|
2075
|
+
if (!before)
|
|
2076
|
+
return unverified(
|
|
2077
|
+
`the click on ${what} was sent, but the window could not be read to see whether it ${want === 'expand' ? 'opened' : 'closed'}. Look at the window before repeating it.`,
|
|
2078
|
+
)
|
|
2079
|
+
const readState = async (): Promise<
|
|
2080
|
+
{ shown: string | undefined; held: boolean } | undefined
|
|
2081
|
+
> => {
|
|
2082
|
+
const newWindow = windows ? await this.newWindowOf(target.pid, windows) : undefined
|
|
2083
|
+
const after = await this.observe(target)
|
|
2084
|
+
if (!after) return undefined
|
|
2085
|
+
const change = changeBetween(before, after)
|
|
2086
|
+
const gone = windows ? await this.windowGone(target.pid, windows) : false
|
|
2087
|
+
if (want === 'expand') {
|
|
2088
|
+
const shown = newWindow?.title.trim() || change.added[0]
|
|
2089
|
+
return { shown, held: newWindow !== undefined || change.added.length > 0 }
|
|
2090
|
+
}
|
|
2091
|
+
return { shown: change.removed[0], held: gone || change.removed.length > 0 }
|
|
2092
|
+
}
|
|
2093
|
+
await this.settle(EXPAND_WAITS_MS[0])
|
|
2094
|
+
const first = await readState()
|
|
2095
|
+
if (!first)
|
|
2096
|
+
return unverified(
|
|
2097
|
+
`the click on ${what} was sent, but the window could not be read afterwards. Look at the window before repeating it.`,
|
|
2098
|
+
)
|
|
2099
|
+
await this.settle(EXPAND_WAITS_MS[1])
|
|
2100
|
+
const second = await readState()
|
|
2101
|
+
if (first.held && second?.held)
|
|
2102
|
+
return {
|
|
2103
|
+
ok: true,
|
|
2104
|
+
delivery: 'delivered_verified',
|
|
2105
|
+
retrySafety: 'unsafe',
|
|
2106
|
+
...(second.shown !== undefined ? { readBack: { observed: trimText(second.shown) } } : {}),
|
|
2107
|
+
detail:
|
|
2108
|
+
want === 'expand'
|
|
2109
|
+
? `${what} is open: the window shows what it opened, and still did a moment later.`
|
|
2110
|
+
: `${what} is closed: what it showed is gone, and stayed gone a moment later.`,
|
|
2111
|
+
}
|
|
2112
|
+
if (first.held && second && !second.held)
|
|
2113
|
+
return unverified(
|
|
2114
|
+
want === 'expand'
|
|
2115
|
+
? `${what} opened and closed again, so it is not open now. Look at the window; a menu that closes on its own may need the keyboard (alt+letter) or a click in the foreground.`
|
|
2116
|
+
: `${what} looked closed, but what it showed is back. Look at the window before repeating it.`,
|
|
2117
|
+
)
|
|
2118
|
+
return unverified(
|
|
2119
|
+
want === 'expand'
|
|
2120
|
+
? `the click on ${what} was sent, but no menu or new control showed in the window afterwards, so it may not be open. Look at the window (a window screenshot) before repeating it.`
|
|
2121
|
+
: `the click on ${what} was sent, but nothing in the window changed, so it may still be open. Look at the window before repeating it.`,
|
|
2122
|
+
)
|
|
2123
|
+
}
|
|
2124
|
+
|
|
2125
|
+
/** Whether a window the program had before (a popup that was open) is no longer listed. */
|
|
2126
|
+
private async windowGone(pid: number, known: ReadonlySet<string>): Promise<boolean> {
|
|
2127
|
+
try {
|
|
2128
|
+
const now = new Set((await this.listWindows()).filter((w) => w.pid === pid).map((w) => w.id))
|
|
2129
|
+
for (const id of known) if (!now.has(id)) return true
|
|
2130
|
+
return false
|
|
2131
|
+
} catch {
|
|
2132
|
+
return false
|
|
2133
|
+
}
|
|
2134
|
+
}
|
|
2135
|
+
|
|
2011
2136
|
/**
|
|
2012
2137
|
* A click on a control by its driver token, in the background. Where the
|
|
2013
2138
|
* driver says the window cannot take background input (or is covered) the
|
|
@@ -2111,6 +2236,46 @@ export class CuaDriverAdapter implements Adapter {
|
|
|
2111
2236
|
await this.client.dispose()
|
|
2112
2237
|
}
|
|
2113
2238
|
|
|
2239
|
+
/**
|
|
2240
|
+
* Let go of the driver process (and the agent cursor it draws) while nobody is using it. The next
|
|
2241
|
+
* call starts it again; every screenshot and ref taken from the old process is then stale, which
|
|
2242
|
+
* the process counter already says.
|
|
2243
|
+
*/
|
|
2244
|
+
async release(stillIdle: () => boolean = () => true): Promise<void> {
|
|
2245
|
+
const before = this.client.starts
|
|
2246
|
+
const ended = await this.client.release()
|
|
2247
|
+
// Nothing below runs unless the process really ended and no call began while it wound down;
|
|
2248
|
+
// a call that did started its own process, and its frame and helpers are not ours to clear.
|
|
2249
|
+
if (!ended || this.client.starts !== before || !stillIdle()) return
|
|
2250
|
+
// The refs read from the old process are dead. The window screenshot is kept: the model may
|
|
2251
|
+
// still be looking at it, and the first input on it reads the window again for the new process.
|
|
2252
|
+
this.windowReads.clear()
|
|
2253
|
+
this.releasedStarts = before
|
|
2254
|
+
// The helpers started beside it (the overlay, the accessibility host) are processes too; the
|
|
2255
|
+
// next window list starts them again.
|
|
2256
|
+
this.presence?.release?.()
|
|
2257
|
+
this.a11y?.release?.()
|
|
2258
|
+
}
|
|
2259
|
+
|
|
2260
|
+
/**
|
|
2261
|
+
* After an idle release the screenshot the model took is still the one it acts on. Read the window
|
|
2262
|
+
* again for the new process (the same size is required) and carry the screenshot over to it.
|
|
2263
|
+
*/
|
|
2264
|
+
private async carryFrameOver(captureId: string): Promise<void> {
|
|
2265
|
+
const frame = this.windowFrame
|
|
2266
|
+
if (
|
|
2267
|
+
!frame ||
|
|
2268
|
+
frame.id !== captureId ||
|
|
2269
|
+
this.releasedStarts !== frame.processStarts ||
|
|
2270
|
+
frame.generation !== this.sessionGeneration
|
|
2271
|
+
)
|
|
2272
|
+
return
|
|
2273
|
+
if (!(await this.restoreDriverFrame(frame))) return
|
|
2274
|
+
if (this.windowFrame !== frame) return
|
|
2275
|
+
this.windowFrame = { ...frame, processStarts: this.client.starts }
|
|
2276
|
+
this.releasedStarts = undefined
|
|
2277
|
+
}
|
|
2278
|
+
|
|
2114
2279
|
/** Tells the overlay where the agent is about to act in a window; never waits and never fails the action. */
|
|
2115
2280
|
private showPresence(
|
|
2116
2281
|
frame: WindowCaptureFrame,
|
|
@@ -2465,6 +2630,12 @@ export function failureDelivery(error: McpToolError): WindowInputResult {
|
|
|
2465
2630
|
typeof refusal?.message === 'string' ? refusal.message : error.message,
|
|
2466
2631
|
)
|
|
2467
2632
|
}
|
|
2633
|
+
if (isNoDriverFrame(error))
|
|
2634
|
+
return verdict(
|
|
2635
|
+
'not_delivered',
|
|
2636
|
+
'safe',
|
|
2637
|
+
'the driver had no screenshot of this window to place the pixels on, so nothing was sent. Take a new window screenshot and click again.',
|
|
2638
|
+
)
|
|
2468
2639
|
if (/stale (window|screenshot)/i.test(error.message))
|
|
2469
2640
|
return verdict('not_delivered', 'safe', trimText(error.message, 300))
|
|
2470
2641
|
if (/stale/i.test(`${error.message} ${JSON.stringify(facts)}`))
|
|
@@ -2482,6 +2653,11 @@ export function failureDelivery(error: McpToolError): WindowInputResult {
|
|
|
2482
2653
|
)
|
|
2483
2654
|
}
|
|
2484
2655
|
|
|
2656
|
+
/** The driver refused a pixel input because it holds no screenshot of the window (nothing was sent). */
|
|
2657
|
+
function isNoDriverFrame(error: unknown): boolean {
|
|
2658
|
+
return error instanceof McpToolError && /No screenshot frame for/i.test(error.message)
|
|
2659
|
+
}
|
|
2660
|
+
|
|
2485
2661
|
/** The driver refused a handle a newer read of its window replaced (nothing was sent). */
|
|
2486
2662
|
function isStaleHandle(error: McpToolError): boolean {
|
|
2487
2663
|
if (/stale (window|screenshot)/i.test(error.message)) return false
|
|
@@ -2640,6 +2816,18 @@ export function windowIdOf(hwnd: number): string {
|
|
|
2640
2816
|
}
|
|
2641
2817
|
|
|
2642
2818
|
export function parseWindowId(value: unknown): number | undefined {
|
|
2819
|
+
// A handle as an object ({ hwnd }, { id }, { window_id } ...) is read by the id inside it.
|
|
2820
|
+
if (typeof value === 'object' && value !== null && !Array.isArray(value)) {
|
|
2821
|
+
const record = value as Record<string, unknown>
|
|
2822
|
+
for (const key of ['window_id', 'windowId', 'hwnd', 'handle', 'id', 'value']) {
|
|
2823
|
+
if (record[key] === undefined || typeof record[key] === 'object') continue
|
|
2824
|
+
const found = parseWindowId(record[key])
|
|
2825
|
+
if (found !== undefined) return found
|
|
2826
|
+
}
|
|
2827
|
+
return undefined
|
|
2828
|
+
}
|
|
2829
|
+
if (typeof value === 'bigint')
|
|
2830
|
+
return value > 0n && value <= BigInt(Number.MAX_SAFE_INTEGER) ? Number(value) : undefined
|
|
2643
2831
|
if (typeof value === 'number') return Number.isSafeInteger(value) && value > 0 ? value : undefined
|
|
2644
2832
|
if (typeof value !== 'string') return undefined
|
|
2645
2833
|
const text = value.trim().toLowerCase()
|
|
@@ -199,6 +199,33 @@ export class McpStdioClient {
|
|
|
199
199
|
}
|
|
200
200
|
}
|
|
201
201
|
|
|
202
|
+
/**
|
|
203
|
+
* Stop the running process and keep the client: the next call starts a new one (the same path as
|
|
204
|
+
* after a crash). For a client nobody is using, so it holds no process while it waits.
|
|
205
|
+
*/
|
|
206
|
+
async release(): Promise<boolean> {
|
|
207
|
+
if (this.inFlight > 0) return false
|
|
208
|
+
const running = this.running ?? (await this.starting?.catch(() => undefined))
|
|
209
|
+
if (!running) return true
|
|
210
|
+
if (running.exited) return true
|
|
211
|
+
if (this.inFlight > 0) return false
|
|
212
|
+
// A call that arrives while it winds down starts a new process; it never meets this one.
|
|
213
|
+
if (this.running === running) this.running = undefined
|
|
214
|
+
running.killedFor = 'dispose'
|
|
215
|
+
running.child.stdin.end()
|
|
216
|
+
let timer: NodeJS.Timeout | undefined
|
|
217
|
+
const late = new Promise<'late'>((resolve) => {
|
|
218
|
+
timer = setTimeout(() => resolve('late'), 2_000)
|
|
219
|
+
})
|
|
220
|
+
const outcome = await Promise.race([running.closed.then(() => 'closed' as const), late])
|
|
221
|
+
clearTimeout(timer)
|
|
222
|
+
if (outcome === 'late') {
|
|
223
|
+
running.child.kill('SIGKILL')
|
|
224
|
+
await running.closed
|
|
225
|
+
}
|
|
226
|
+
return true
|
|
227
|
+
}
|
|
228
|
+
|
|
202
229
|
private async ensureStarted(): Promise<Running> {
|
|
203
230
|
if (this.disposed) throw new Error(`${this.options.command}: the client was disposed.`)
|
|
204
231
|
if (this.running && !this.running.exited) return this.running
|
|
@@ -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/types.ts
CHANGED
|
@@ -62,6 +62,11 @@ export interface Adapter {
|
|
|
62
62
|
/** With `capabilities.uiTree`. */
|
|
63
63
|
uiAct?(ref: string, action: UiElementAction, value?: string): Promise<UiActResult>
|
|
64
64
|
dispose?(): Promise<void>
|
|
65
|
+
/**
|
|
66
|
+
* Lets go of what the adapter keeps running while nobody uses it; the next call starts it again.
|
|
67
|
+
* Optional: an adapter that holds nothing between calls has nothing to let go of.
|
|
68
|
+
*/
|
|
69
|
+
release?(stillIdle?: () => boolean): Promise<void>
|
|
65
70
|
}
|
|
66
71
|
|
|
67
72
|
/**
|
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
|
@@ -117,6 +117,7 @@ export function guardForeground(adapter: Adapter, ladder: ForegroundLadder): Ada
|
|
|
117
117
|
await adapter.dispose?.()
|
|
118
118
|
},
|
|
119
119
|
}
|
|
120
|
+
if (adapter.release) guarded.release = adapter.release.bind(adapter)
|
|
120
121
|
if (adapter.listWindows) {
|
|
121
122
|
const list = adapter.listWindows.bind(adapter)
|
|
122
123
|
guarded.listWindows = async () => {
|
package/src/presence/presence.ts
CHANGED
|
@@ -29,6 +29,11 @@ export interface Presence {
|
|
|
29
29
|
warm(): void
|
|
30
30
|
/** Removes both at once: the task ended or the session stopped. */
|
|
31
31
|
hide(): void
|
|
32
|
+
/**
|
|
33
|
+
* Ends the helper process while nobody is using it; the next `warm()` or `mark()` starts it again.
|
|
34
|
+
* Optional: a presence that holds no process has nothing to end.
|
|
35
|
+
*/
|
|
36
|
+
release?(): void
|
|
32
37
|
dispose(): Promise<void>
|
|
33
38
|
}
|
|
34
39
|
|
|
@@ -103,6 +108,8 @@ export class WindowsPresence implements Presence {
|
|
|
103
108
|
private dead = false
|
|
104
109
|
private restarts = 0
|
|
105
110
|
private disposed = false
|
|
111
|
+
/** Helpers let go of on purpose: their exit is not a crash. */
|
|
112
|
+
private readonly released = new WeakSet<PresenceProcess>()
|
|
106
113
|
|
|
107
114
|
constructor(private readonly options: WindowsPresenceOptions) {}
|
|
108
115
|
|
|
@@ -131,6 +138,15 @@ export class WindowsPresence implements Presence {
|
|
|
131
138
|
if (this.proc && this.available) this.proc.write(JSON.stringify({ cmd: 'hide' }))
|
|
132
139
|
}
|
|
133
140
|
|
|
141
|
+
release(): void {
|
|
142
|
+
const proc = this.proc
|
|
143
|
+
if (!proc) return
|
|
144
|
+
this.released.add(proc)
|
|
145
|
+
this.proc = undefined
|
|
146
|
+
this.starting = undefined
|
|
147
|
+
proc.kill()
|
|
148
|
+
}
|
|
149
|
+
|
|
134
150
|
async dispose(): Promise<void> {
|
|
135
151
|
this.disposed = true
|
|
136
152
|
const proc = this.proc
|
|
@@ -164,6 +180,10 @@ export class WindowsPresence implements Presence {
|
|
|
164
180
|
timer.unref()
|
|
165
181
|
proc.onExit(() => {
|
|
166
182
|
clearTimeout(timer)
|
|
183
|
+
if (this.released.has(proc)) {
|
|
184
|
+
resolve(false)
|
|
185
|
+
return
|
|
186
|
+
}
|
|
167
187
|
// A helper that was running and ended (it crashed, or its host closed it) is
|
|
168
188
|
// started again by the next action, a few times; one that never came up stays off.
|
|
169
189
|
if (greeted && this.proc === proc && !this.disposed && this.restarts < MAX_RESTARTS) {
|