@namzu/computer-use 3.1.0 → 4.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (125) hide show
  1. package/CHANGELOG.md +64 -1
  2. package/README.md +3 -3
  3. package/dist/SubprocessComputerUseHost.d.ts +58 -10
  4. package/dist/SubprocessComputerUseHost.d.ts.map +1 -1
  5. package/dist/SubprocessComputerUseHost.js +214 -47
  6. package/dist/SubprocessComputerUseHost.js.map +1 -1
  7. package/dist/adapters/cua-driver/adapter.d.ts +171 -10
  8. package/dist/adapters/cua-driver/adapter.d.ts.map +1 -1
  9. package/dist/adapters/cua-driver/adapter.js +1479 -161
  10. package/dist/adapters/cua-driver/adapter.js.map +1 -1
  11. package/dist/adapters/cua-driver/client.d.ts +16 -0
  12. package/dist/adapters/cua-driver/client.d.ts.map +1 -1
  13. package/dist/adapters/cua-driver/client.js +54 -5
  14. package/dist/adapters/cua-driver/client.js.map +1 -1
  15. package/dist/adapters/cua-driver/escalation.d.ts +67 -0
  16. package/dist/adapters/cua-driver/escalation.d.ts.map +1 -0
  17. package/dist/adapters/cua-driver/escalation.js +82 -0
  18. package/dist/adapters/cua-driver/escalation.js.map +1 -0
  19. package/dist/adapters/cua-driver/keys.d.ts +5 -0
  20. package/dist/adapters/cua-driver/keys.d.ts.map +1 -1
  21. package/dist/adapters/cua-driver/keys.js +23 -0
  22. package/dist/adapters/cua-driver/keys.js.map +1 -1
  23. package/dist/adapters/cua-driver/observe.d.ts +99 -0
  24. package/dist/adapters/cua-driver/observe.d.ts.map +1 -0
  25. package/dist/adapters/cua-driver/observe.js +227 -0
  26. package/dist/adapters/cua-driver/observe.js.map +1 -0
  27. package/dist/adapters/cua-driver/provision.d.ts +13 -13
  28. package/dist/adapters/cua-driver/provision.js +13 -13
  29. package/dist/adapters/cua-driver/ui-tree.d.ts +75 -2
  30. package/dist/adapters/cua-driver/ui-tree.d.ts.map +1 -1
  31. package/dist/adapters/cua-driver/ui-tree.js +142 -14
  32. package/dist/adapters/cua-driver/ui-tree.js.map +1 -1
  33. package/dist/adapters/types.d.ts +4 -4
  34. package/dist/adapters/types.d.ts.map +1 -1
  35. package/dist/adapters/types.js.map +1 -1
  36. package/dist/adapters/win32.d.ts +10 -0
  37. package/dist/adapters/win32.d.ts.map +1 -1
  38. package/dist/adapters/win32.js +12 -2
  39. package/dist/adapters/win32.js.map +1 -1
  40. package/dist/errors.d.ts +19 -0
  41. package/dist/errors.d.ts.map +1 -1
  42. package/dist/errors.js +26 -0
  43. package/dist/errors.js.map +1 -1
  44. package/dist/foreground/guard.d.ts +31 -0
  45. package/dist/foreground/guard.d.ts.map +1 -0
  46. package/dist/foreground/guard.js +156 -0
  47. package/dist/foreground/guard.js.map +1 -0
  48. package/dist/foreground/index.d.ts +11 -0
  49. package/dist/foreground/index.d.ts.map +1 -0
  50. package/dist/foreground/index.js +7 -0
  51. package/dist/foreground/index.js.map +1 -0
  52. package/dist/foreground/ladder.d.ts +143 -0
  53. package/dist/foreground/ladder.d.ts.map +1 -0
  54. package/dist/foreground/ladder.js +505 -0
  55. package/dist/foreground/ladder.js.map +1 -0
  56. package/dist/foreground/lease.d.ts +69 -0
  57. package/dist/foreground/lease.d.ts.map +1 -0
  58. package/dist/foreground/lease.js +182 -0
  59. package/dist/foreground/lease.js.map +1 -0
  60. package/dist/foreground/types.d.ts +287 -0
  61. package/dist/foreground/types.d.ts.map +1 -0
  62. package/dist/foreground/types.js +32 -0
  63. package/dist/foreground/types.js.map +1 -0
  64. package/dist/foreground/windows-helper-script.d.ts +19 -0
  65. package/dist/foreground/windows-helper-script.d.ts.map +1 -0
  66. package/dist/foreground/windows-helper-script.js +472 -0
  67. package/dist/foreground/windows-helper-script.js.map +1 -0
  68. package/dist/foreground/windows-monitor.d.ts +75 -0
  69. package/dist/foreground/windows-monitor.d.ts.map +1 -0
  70. package/dist/foreground/windows-monitor.js +216 -0
  71. package/dist/foreground/windows-monitor.js.map +1 -0
  72. package/dist/foreground/windows.d.ts +21 -0
  73. package/dist/foreground/windows.d.ts.map +1 -0
  74. package/dist/foreground/windows.js +54 -0
  75. package/dist/foreground/windows.js.map +1 -0
  76. package/dist/index.d.ts +6 -1
  77. package/dist/index.d.ts.map +1 -1
  78. package/dist/index.js +3 -1
  79. package/dist/index.js.map +1 -1
  80. package/dist/presence/helper-script.d.ts +39 -0
  81. package/dist/presence/helper-script.d.ts.map +1 -0
  82. package/dist/presence/helper-script.js +320 -0
  83. package/dist/presence/helper-script.js.map +1 -0
  84. package/dist/presence/index.d.ts +6 -0
  85. package/dist/presence/index.d.ts.map +1 -0
  86. package/dist/presence/index.js +4 -0
  87. package/dist/presence/index.js.map +1 -0
  88. package/dist/presence/presence.d.ts +70 -0
  89. package/dist/presence/presence.d.ts.map +1 -0
  90. package/dist/presence/presence.js +147 -0
  91. package/dist/presence/presence.js.map +1 -0
  92. package/dist/presence/windows.d.ts +19 -0
  93. package/dist/presence/windows.d.ts.map +1 -0
  94. package/dist/presence/windows.js +39 -0
  95. package/dist/presence/windows.js.map +1 -0
  96. package/dist/util/call-scope.d.ts +34 -0
  97. package/dist/util/call-scope.d.ts.map +1 -0
  98. package/dist/util/call-scope.js +58 -0
  99. package/dist/util/call-scope.js.map +1 -0
  100. package/package.json +2 -2
  101. package/src/SubprocessComputerUseHost.ts +288 -46
  102. package/src/adapters/cua-driver/adapter.ts +1754 -175
  103. package/src/adapters/cua-driver/client.ts +59 -2
  104. package/src/adapters/cua-driver/escalation.ts +137 -0
  105. package/src/adapters/cua-driver/keys.ts +20 -0
  106. package/src/adapters/cua-driver/observe.ts +310 -0
  107. package/src/adapters/cua-driver/provision.ts +13 -13
  108. package/src/adapters/cua-driver/ui-tree.ts +219 -15
  109. package/src/adapters/types.ts +8 -3
  110. package/src/adapters/win32.ts +26 -3
  111. package/src/errors.ts +32 -0
  112. package/src/foreground/guard.ts +182 -0
  113. package/src/foreground/index.ts +45 -0
  114. package/src/foreground/ladder.ts +616 -0
  115. package/src/foreground/lease.ts +232 -0
  116. package/src/foreground/types.ts +318 -0
  117. package/src/foreground/windows-helper-script.ts +471 -0
  118. package/src/foreground/windows-monitor.ts +288 -0
  119. package/src/foreground/windows.ts +73 -0
  120. package/src/index.ts +15 -1
  121. package/src/presence/helper-script.ts +323 -0
  122. package/src/presence/index.ts +17 -0
  123. package/src/presence/presence.ts +195 -0
  124. package/src/presence/windows.ts +54 -0
  125. package/src/util/call-scope.ts +73 -0
@@ -0,0 +1,616 @@
1
+ import { CallAbortedError, abortable } from '../util/call-scope.js'
2
+ import { type LeaseAttempt, ScreenLease } from './lease.js'
3
+ import {
4
+ type BurstContext,
5
+ BurstInterrupted,
6
+ type EditTextRequest,
7
+ type EditTextResult,
8
+ type ForegroundApprover,
9
+ type ForegroundBlock,
10
+ type ForegroundMonitor,
11
+ type ForegroundOutcome,
12
+ type ForegroundSubject,
13
+ type MenuCommandRequest,
14
+ type MenuCommandResult,
15
+ type MonitorBurstEnd,
16
+ type MonitorState,
17
+ PROTECTED_PROCESSES,
18
+ type SelectItemRequest,
19
+ type SelectItemResult,
20
+ } from './types.js'
21
+
22
+ /** Time, replaceable so the waits below run on a fake clock in tests. */
23
+ export interface LadderClock {
24
+ now(): number
25
+ sleep(ms: number, signal?: AbortSignal): Promise<void>
26
+ }
27
+
28
+ export const realClock: LadderClock = {
29
+ now: () => Date.now(),
30
+ sleep(ms, signal) {
31
+ return new Promise((resolve) => {
32
+ if (signal?.aborted) return resolve()
33
+ const timer = setTimeout(done, ms)
34
+ function done() {
35
+ clearTimeout(timer)
36
+ signal?.removeEventListener('abort', done)
37
+ resolve()
38
+ }
39
+ signal?.addEventListener('abort', done, { once: true })
40
+ })
41
+ },
42
+ }
43
+
44
+ /** The thresholds and bounds of the ladder. Every wait is bounded. */
45
+ export interface LadderTiming {
46
+ /**
47
+ * How long the user must have been still before the screen is used.
48
+ * 2 000 ms: on the machine this was measured on, the gaps between a person's
49
+ * inputs rarely reach 5 s while 2 s is common between bursts of activity,
50
+ * and a keep-awake nudge every ~26 s leaves 24 s of every 26 free.
51
+ */
52
+ readonly idleMs: number
53
+ /** Idle needed once the user has agreed to give up the screen for a moment. */
54
+ readonly approvedIdleMs: number
55
+ /** How often the monitor is read while waiting. */
56
+ readonly pollMs: number
57
+ /** How long to wait for the user to go idle before asking them. */
58
+ readonly userActiveWaitMs: number
59
+ /** How long to keep waiting after they agreed. */
60
+ readonly approvedWaitMs: number
61
+ /** Where nobody can be asked (exec, scheduled): how long to wait for a still moment. */
62
+ readonly parkMs: number
63
+ readonly parkPollMs: number
64
+ /** How long to wait for another session to release the lease. */
65
+ readonly leaseWaitMs: number
66
+ readonly leasePollMs: number
67
+ /** How often a held lease is refreshed while a burst runs (well inside its time-to-live). */
68
+ readonly leaseBeatMs: number
69
+ /** Most time one turn may spend parked, over all its calls. */
70
+ readonly parkTurnMs: number
71
+ }
72
+
73
+ export const DEFAULT_TIMING: LadderTiming = {
74
+ idleMs: 2_000,
75
+ approvedIdleMs: 500,
76
+ pollMs: 50,
77
+ userActiveWaitMs: 15_000,
78
+ approvedWaitMs: 30_000,
79
+ parkMs: 120_000,
80
+ parkPollMs: 250,
81
+ leaseWaitMs: 30_000,
82
+ leasePollMs: 200,
83
+ leaseBeatMs: 8_000,
84
+ parkTurnMs: 600_000,
85
+ }
86
+
87
+ export interface ForegroundLadderOptions {
88
+ /** A fresh monitor each time one is needed (it is stopped between turns). */
89
+ readonly createMonitor: () => ForegroundMonitor
90
+ /** Full path of the lease file. */
91
+ readonly leasePath: string
92
+ readonly session?: string
93
+ /** Present where a person can be asked. */
94
+ readonly approve?: ForegroundApprover
95
+ readonly timing?: Partial<LadderTiming>
96
+ readonly clock?: LadderClock
97
+ readonly lease?: ScreenLease
98
+ }
99
+
100
+ /** What the model reads once Escape has stopped the turn. Fixed on purpose. */
101
+ export const STOPPED_TEXT =
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
+
104
+ const seconds = (ms: number): string => `${Math.max(1, Math.round(ms / 1000))} s`
105
+
106
+ const BLOCKS = {
107
+ locked_desktop: (): ForegroundBlock => ({
108
+ code: 'locked_desktop',
109
+ detail:
110
+ 'The computer is locked or showing a sign-in screen, so nothing was sent. Ask the user to unlock it, then continue. Do not try to work around it.',
111
+ }),
112
+ secure_desktop: (): ForegroundBlock => ({
113
+ code: 'secure_desktop',
114
+ detail:
115
+ 'A system prompt that only the user can answer has the screen (an administrator-permission prompt, for example), so nothing was sent. Ask the user to answer it themselves. Never try to work around it.',
116
+ }),
117
+ uac_prompt: (): ForegroundBlock => ({
118
+ code: 'uac_prompt',
119
+ detail:
120
+ 'An administrator-permission prompt is in front, so nothing was sent. Ask the user to answer it themselves. Never try to work around it.',
121
+ }),
122
+ elevated_target: (inFront = false): ForegroundBlock => ({
123
+ code: 'elevated_target',
124
+ detail: inFront
125
+ ? 'An administrator window is in front; Namzu cannot type into it, so nothing was sent. Ask the user to click away from it, or to do this step themselves. Do not try to work around it.'
126
+ : 'This program runs with administrator rights, so input from here is blocked and nothing was sent. Ask the user to act in it, or to restart it without administrator rights. Do not try to work around it.',
127
+ }),
128
+ monitor_unavailable: (reason: string): ForegroundBlock => ({
129
+ 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. Use controls by ref (ui_act) in the background, or ask the user to do this step.`,
131
+ }),
132
+ declined: (app: string): ForegroundBlock => ({
133
+ code: 'declined',
134
+ detail: `The user did not allow ${app} to use the screen for this, so nothing was sent. Do not ask again this turn; tell them what you could not do.`,
135
+ }),
136
+ stopped: (): ForegroundBlock => ({ code: 'stopped', detail: STOPPED_TEXT }),
137
+ lease_busy: (waited: number): ForegroundBlock => ({
138
+ code: 'lease_busy',
139
+ detail: `Another Namzu session has been using the screen for the last ${seconds(waited)}, so nothing was sent. Try this action again in a moment.`,
140
+ }),
141
+ user_active: (waited: number, asked: boolean): ForegroundBlock => ({
142
+ code: 'user_active',
143
+ detail: `The user kept using the keyboard or mouse for ${seconds(waited)}${asked ? ' even after agreeing' : ''}, so the screen was not taken and nothing was sent. Do other work that does not need the screen, or try this action again later.`,
144
+ }),
145
+ }
146
+
147
+ /** Times a burst start is retried because input arrived between the last look and the start. */
148
+ const MAX_INTERFERED_STARTS = 3
149
+
150
+ interface Stop {
151
+ readonly turnId: string | undefined
152
+ }
153
+
154
+ /** What one burst asks of the ladder. */
155
+ export interface LadderRequest {
156
+ readonly subject: ForegroundSubject
157
+ /** The burst leaves the cursor where it put it (a `mouse_move`). */
158
+ readonly keepCursor?: boolean
159
+ /** Stops waiting for the screen (the idle gate, the lease) when aborted. */
160
+ readonly signal?: AbortSignal
161
+ /** The burst sends keyboard or mouse input: the outcome says whether the system registered it. */
162
+ readonly sendsInput?: boolean
163
+ /**
164
+ * Awaited after the burst function returns or throws and before the window
165
+ * and cursor are put back: calls a cancelled burst left in flight must
166
+ * finish first, or they would act after the restore.
167
+ */
168
+ readonly settle?: () => Promise<void>
169
+ }
170
+
171
+ /**
172
+ * The foreground ladder. `run` takes a burst (a function that sends input
173
+ * which can only be delivered in the foreground) through:
174
+ *
175
+ * 1. the lease: one session at a time, a stale lease taken over;
176
+ * 2. the safety checks: lock screen, system prompts, administrator windows;
177
+ * 3. the idle gate: the user still for `idleMs`;
178
+ * 4. if the user stays busy for `userActiveWaitMs`: one question to them, or,
179
+ * where nobody can be asked, a bounded wait that retries;
180
+ * 5. the burst, watched for real input from start to end;
181
+ * 6. a conditional restore of the window and cursor that were there before.
182
+ *
183
+ * Nothing here sends input itself and nothing waits without a bound.
184
+ */
185
+ export class ForegroundLadder {
186
+ private readonly timing: LadderTiming
187
+ private readonly clock: LadderClock
188
+ private readonly lease: ScreenLease
189
+ private monitor: ForegroundMonitor | undefined
190
+ private queue: Promise<unknown> = Promise.resolve()
191
+ /** The restore of a cancelled burst, which runs after its caller has been answered. */
192
+ private background: Promise<void> = Promise.resolve()
193
+ private stop: Stop | undefined
194
+ private readonly leaseBeatMs: number
195
+ private parkedMs = 0
196
+ private turn: string | undefined
197
+ private readonly allowed = new Set<string>()
198
+ private readonly denied = new Set<string>()
199
+
200
+ constructor(private readonly options: ForegroundLadderOptions) {
201
+ this.timing = { ...DEFAULT_TIMING, ...options.timing }
202
+ this.clock = options.clock ?? realClock
203
+ this.leaseBeatMs = this.timing.leaseBeatMs
204
+ this.lease =
205
+ options.lease ??
206
+ new ScreenLease({
207
+ path: options.leasePath,
208
+ session: options.session ?? 'session',
209
+ now: () => this.clock.now(),
210
+ })
211
+ }
212
+
213
+ /** True after a physical Escape, until the next user turn. */
214
+ get stopped(): boolean {
215
+ return this.stop !== undefined
216
+ }
217
+
218
+ /**
219
+ * The model's turn `turnId` is starting a tool call. A new turn lifts an
220
+ * Escape stop and forgets refused permissions. A caller that has no turn id
221
+ * passes undefined, which always counts as a new turn.
222
+ */
223
+ beginTurn(turnId: string | undefined): void {
224
+ if (this.stop && (turnId === undefined || turnId !== this.stop.turnId)) this.stop = undefined
225
+ if (turnId === undefined || turnId !== this.turn) {
226
+ this.denied.clear()
227
+ this.parkedMs = 0
228
+ }
229
+ this.turn = turnId
230
+ }
231
+
232
+ /**
233
+ * Reads or changes a classic edit control by window message through the
234
+ * monitor. It uses neither the screen nor the lease: nothing is raised and
235
+ * no input is sent. Undefined where no monitor can reach controls.
236
+ */
237
+ async editText(request: EditTextRequest): Promise<EditTextResult | undefined> {
238
+ const monitor = await this.ensureMonitor()
239
+ if (!monitor.ok || !monitor.monitor.editText) return undefined
240
+ try {
241
+ return await abortable('edit_text', monitor.monitor.editText(request))
242
+ } catch (error) {
243
+ if (error instanceof CallAbortedError) throw error
244
+ return undefined
245
+ }
246
+ }
247
+
248
+ /**
249
+ * Selects one list or tree item through its selection pattern. Like
250
+ * `editText` it uses neither the screen nor the lease. Undefined where no
251
+ * monitor can reach controls.
252
+ */
253
+ async selectItem(request: SelectItemRequest): Promise<SelectItemResult | undefined> {
254
+ const monitor = await this.ensureMonitor()
255
+ if (!monitor.ok || !monitor.monitor.selectItem) return undefined
256
+ try {
257
+ return await abortable('select_item', monitor.monitor.selectItem(request))
258
+ } catch (error) {
259
+ if (error instanceof CallAbortedError) throw error
260
+ return undefined
261
+ }
262
+ }
263
+
264
+ /**
265
+ * Sends the menu command a shortcut stands for, as a window message: no
266
+ * screen, no lease, no key. Undefined where no monitor can reach windows.
267
+ */
268
+ async menuCommand(request: MenuCommandRequest): Promise<MenuCommandResult | undefined> {
269
+ const monitor = await this.ensureMonitor()
270
+ if (!monitor.ok || !monitor.monitor.menuCommand) return undefined
271
+ try {
272
+ return await abortable('menu_command', monitor.monitor.menuCommand(request))
273
+ } catch (error) {
274
+ if (error instanceof CallAbortedError) throw error
275
+ return undefined
276
+ }
277
+ }
278
+
279
+ /**
280
+ * Whether the computer is locked, read from the long-lived helper (cheap once
281
+ * it runs): the input desktop is not the normal one, or the lock screen's own
282
+ * program is in front. `null` when unsure (no helper, or a state that is not
283
+ * clearly either), so a caller treats it as unlocked.
284
+ */
285
+ async lockState(): Promise<'locked' | 'unlocked' | null> {
286
+ const monitor = await this.ensureMonitor()
287
+ if (!monitor.ok) return null
288
+ try {
289
+ const state = await abortable('lock_state', monitor.monitor.state())
290
+ const desktop = state.desktop.toLowerCase()
291
+ if (desktop === 'default') {
292
+ const front = state.foreground?.exe.toLowerCase()
293
+ return front !== undefined && PROTECTED_PROCESSES.get(front) === 'locked_desktop'
294
+ ? 'locked'
295
+ : 'unlocked'
296
+ }
297
+ // A desktop that cannot be read says nothing; a named one that is not the normal one is a lock or sign-in screen.
298
+ return desktop === '(unreadable)' ? null : 'locked'
299
+ } catch (error) {
300
+ if (error instanceof CallAbortedError) throw error
301
+ return null
302
+ }
303
+ }
304
+
305
+ /** The model's turn ended or was interrupted: nothing stays watched or held. */
306
+ async endTurn(): Promise<void> {
307
+ this.denied.clear()
308
+ // A burst in flight puts its window and cursor back through the monitor
309
+ // when it ends; dropping the monitor first would restore under it.
310
+ await this.queue
311
+ await this.dropMonitor()
312
+ }
313
+
314
+ async dispose(): Promise<void> {
315
+ this.allowed.clear()
316
+ await this.endTurn()
317
+ }
318
+
319
+ run<T>(
320
+ request: LadderRequest,
321
+ burst: (context: BurstContext) => Promise<T>,
322
+ ): Promise<ForegroundOutcome<T>> {
323
+ const run = this.queue.then(() => this.runOne(request, burst))
324
+ // The next burst, and the end of the turn, wait for the restore a cancelled burst left running.
325
+ this.queue = run.catch(() => undefined).then(() => this.background)
326
+ return run
327
+ }
328
+
329
+ private async runOne<T>(
330
+ request: LadderRequest,
331
+ burst: (context: BurstContext) => Promise<T>,
332
+ attempt = 0,
333
+ ): Promise<ForegroundOutcome<T>> {
334
+ const { subject, signal } = request
335
+ if (this.stop) return { kind: 'blocked', block: BLOCKS.stopped() }
336
+ const monitor = await this.ensureMonitor()
337
+ if (!monitor.ok)
338
+ return {
339
+ kind: 'blocked',
340
+ block: BLOCKS.monitor_unavailable(monitor.reason),
341
+ }
342
+
343
+ const leaseStart = this.clock.now()
344
+ const token = await this.acquireLease(signal)
345
+ if (token === undefined)
346
+ return {
347
+ kind: 'blocked',
348
+ block: BLOCKS.lease_busy(this.clock.now() - leaseStart),
349
+ }
350
+ let deferred = false
351
+ try {
352
+ const state = await this.gate(monitor.monitor, subject, signal)
353
+ if ('block' in state) return { kind: 'blocked', block: state.block }
354
+ const startedAt = this.clock.now()
355
+ const begun = await monitor.monitor.begin({
356
+ leasePath: this.lease.path,
357
+ token,
358
+ // Checked by the monitor before it raises anything, so a person who
359
+ // started typing after the last look is not displaced.
360
+ idleMs: state.needed,
361
+ ...(subject.hwnd !== undefined ? { raise: subject.hwnd } : {}),
362
+ })
363
+ // A person touched input between the last look and now: not yet.
364
+ if (begun.refused === true || begun.userInputs !== state.state.userInputs) {
365
+ if (attempt >= MAX_INTERFERED_STARTS) {
366
+ await monitor.monitor.end({ restore: true }).catch(() => undefined)
367
+ return {
368
+ kind: 'blocked',
369
+ block: BLOCKS.user_active(this.clock.now() - startedAt, false),
370
+ }
371
+ }
372
+ return await this.retryAfterInterference(
373
+ monitor.monitor,
374
+ request,
375
+ burst,
376
+ token,
377
+ attempt + 1,
378
+ )
379
+ }
380
+ const beat = setInterval(
381
+ () => void this.lease.heartbeat(token),
382
+ Math.max(1, Math.floor(this.leaseBeatMs)),
383
+ )
384
+ beat.unref?.()
385
+ let value: T | undefined
386
+ let failure: { readonly error: unknown } | undefined
387
+ try {
388
+ value = await burst({
389
+ checkpoint: async () => {
390
+ if (!this.lease.heartbeat(token)) throw new BurstInterrupted()
391
+ const now = await monitor.monitor.state()
392
+ if (now.userInputs !== begun.userInputs) throw new BurstInterrupted()
393
+ // The hooks see nothing typed into a window above this program's rights,
394
+ // so a person there cannot be told from silence: stop rather than guess.
395
+ // Only a window positively read above this program's rights counts; one
396
+ // that cannot be read (no front window, a closing menu) is not a reason.
397
+ const above = now.foreground?.integrity
398
+ if (
399
+ !now.selfElevated &&
400
+ above !== undefined &&
401
+ above >= 0 &&
402
+ above > (now.selfIntegrity ?? Number.MAX_SAFE_INTEGER)
403
+ )
404
+ throw new BurstInterrupted('administrator_window')
405
+ },
406
+ })
407
+ } catch (error) {
408
+ failure = { error }
409
+ } finally {
410
+ clearInterval(beat)
411
+ }
412
+ // Calls the burst abandoned (an abort) may still be sending: they finish
413
+ // before the window and cursor are put back. The burst ends, and what it
414
+ // moved is put back, whether it returned or threw; an Escape pressed on
415
+ // the way stops the turn either way.
416
+ const finish = async (): Promise<MonitorBurstEnd | undefined> => {
417
+ await request.settle?.().catch(() => undefined)
418
+ const result = await monitor.monitor
419
+ .end({
420
+ restore: true,
421
+ ...(request.keepCursor ? { keepCursor: true } : {}),
422
+ })
423
+ .catch(() => undefined)
424
+ if ((result?.escapesDuring ?? 0) > 0) this.stop = { turnId: this.turn }
425
+ return result
426
+ }
427
+ if (failure && request.signal?.aborted) {
428
+ // A cancelled turn does not wait for the driver to let go: the caller gets
429
+ // its answer now, and the screen is given back, and the lease released,
430
+ // once the abandoned calls have finished. The next burst and the end of
431
+ // the turn wait for that (see `background`).
432
+ deferred = true
433
+ this.background = finish()
434
+ .then(() => undefined)
435
+ .finally(() => {
436
+ this.lease.release(token)
437
+ return this.monitor
438
+ ?.release({ leasePath: this.lease.path, token })
439
+ .catch(() => undefined)
440
+ })
441
+ throw failure.error
442
+ }
443
+ const ended = await finish()
444
+ const stopped = (ended?.escapesDuring ?? 0) > 0
445
+ if (failure) throw failure.error
446
+ // A tick that did not move proves a drop only when a window above this
447
+ // program's rights was positively in front: input posted as messages
448
+ // does not move it, and calling that dropped would invite a duplicate.
449
+ const dropped =
450
+ request.sendsInput === true &&
451
+ ended?.inputMoved === false &&
452
+ ended.inputsDuring === 0 &&
453
+ ended.frontElevated === true
454
+ return {
455
+ kind: 'ran',
456
+ value: value as T,
457
+ // Input went out; if the monitor cannot say what happened around it,
458
+ // the result is not proof either way.
459
+ interfered: ended === undefined || ended.inputsDuring > 0,
460
+ stopped,
461
+ restoredForeground: ended?.restoredForeground ?? false,
462
+ restoredCursor: ended?.restoredCursor ?? false,
463
+ ...(ended?.restoreNote ? { restoreNote: ended.restoreNote } : {}),
464
+ ...(request.sendsInput === true && (dropped || ended?.inputMoved === true)
465
+ ? { inputLanded: !dropped }
466
+ : {}),
467
+ ...(dropped
468
+ ? {
469
+ inputDroppedWhy: 'An administrator window is in front; Namzu cannot type into it.',
470
+ }
471
+ : {}),
472
+ heldMs: this.clock.now() - startedAt,
473
+ }
474
+ } finally {
475
+ if (!deferred) {
476
+ this.lease.release(token)
477
+ await this.monitor?.release({ leasePath: this.lease.path, token }).catch(() => undefined)
478
+ }
479
+ }
480
+ }
481
+
482
+ private async retryAfterInterference<T>(
483
+ monitor: ForegroundMonitor,
484
+ request: LadderRequest,
485
+ burst: (context: BurstContext) => Promise<T>,
486
+ token: string,
487
+ attempt: number,
488
+ ): Promise<ForegroundOutcome<T>> {
489
+ // A raise that happened just before a person's input is undone too.
490
+ await monitor.end({ restore: true }).catch(() => undefined)
491
+ // The lease is ours until runOne's finally; release it so the nested run takes it afresh.
492
+ this.lease.release(token)
493
+ return this.runOne(request, burst, attempt)
494
+ }
495
+
496
+ private async ensureMonitor(): Promise<
497
+ { readonly ok: true; readonly monitor: ForegroundMonitor } | { ok: false; reason: string }
498
+ > {
499
+ if (this.monitor) return { ok: true, monitor: this.monitor }
500
+ const monitor = this.options.createMonitor()
501
+ try {
502
+ await monitor.start()
503
+ } catch (error) {
504
+ await monitor.dispose().catch(() => undefined)
505
+ return {
506
+ ok: false,
507
+ reason: error instanceof Error ? error.message : String(error),
508
+ }
509
+ }
510
+ this.monitor = monitor
511
+ return { ok: true, monitor }
512
+ }
513
+
514
+ private async dropMonitor(): Promise<void> {
515
+ const monitor = this.monitor
516
+ this.monitor = undefined
517
+ await monitor?.dispose().catch(() => undefined)
518
+ }
519
+
520
+ private async acquireLease(signal?: AbortSignal): Promise<string | undefined> {
521
+ const deadline = this.clock.now() + this.timing.leaseWaitMs
522
+ for (;;) {
523
+ const attempt: LeaseAttempt = this.lease.tryAcquire()
524
+ if (attempt.held) return attempt.token
525
+ if (this.clock.now() >= deadline || signal?.aborted) return undefined
526
+ await this.clock.sleep(this.timing.leasePollMs, signal)
527
+ }
528
+ }
529
+
530
+ /** Safety checks and the idle gate, with the one question to the user. */
531
+ private async gate(
532
+ monitor: ForegroundMonitor,
533
+ subject: ForegroundSubject,
534
+ signal?: AbortSignal,
535
+ ): Promise<
536
+ { readonly state: MonitorState; readonly needed: number } | { readonly block: ForegroundBlock }
537
+ > {
538
+ const started = this.clock.now()
539
+ let phase: 'gate' | 'approved' | 'parked' = 'gate'
540
+ let phaseStart = started
541
+ let asked = false
542
+ let first = true
543
+ for (;;) {
544
+ const state = await monitor.state(subject.pid !== undefined ? { pid: subject.pid } : {})
545
+ const unsafe = this.unsafe(state)
546
+ if (unsafe) return { block: unsafe }
547
+ const who = effectiveSubject(subject, state)
548
+ const key = (who.exe ?? who.app).toLowerCase()
549
+ if (first && this.allowed.has(key)) {
550
+ phase = 'approved'
551
+ asked = true
552
+ }
553
+ first = false
554
+ const needed = phase === 'approved' ? this.timing.approvedIdleMs : this.timing.idleMs
555
+ if (state.userIdleMs >= needed) return { state, needed }
556
+ const now = this.clock.now()
557
+ const limit =
558
+ phase === 'gate'
559
+ ? this.timing.userActiveWaitMs
560
+ : phase === 'approved'
561
+ ? this.timing.approvedWaitMs
562
+ : this.timing.parkMs
563
+ if (
564
+ now - phaseStart >= limit ||
565
+ signal?.aborted ||
566
+ (phase === 'parked' && this.parkedMs >= this.timing.parkTurnMs)
567
+ ) {
568
+ if (phase === 'gate' && !signal?.aborted) {
569
+ if (this.denied.has(key)) return { block: BLOCKS.declined(who.app) }
570
+ const answer = (await this.options.approve?.(who, signal)) ?? 'unavailable'
571
+ if (answer === 'deny') {
572
+ this.denied.add(key)
573
+ return { block: BLOCKS.declined(who.app) }
574
+ }
575
+ if (answer === 'allow') {
576
+ this.allowed.add(key)
577
+ phase = 'approved'
578
+ asked = true
579
+ } else {
580
+ phase = 'parked'
581
+ }
582
+ phaseStart = this.clock.now()
583
+ continue
584
+ }
585
+ return { block: BLOCKS.user_active(now - started, asked) }
586
+ }
587
+ const wait = phase === 'parked' ? this.timing.parkPollMs : this.timing.pollMs
588
+ if (phase === 'parked') this.parkedMs += wait
589
+ await this.clock.sleep(wait, signal)
590
+ }
591
+ }
592
+
593
+ private unsafe(state: MonitorState): ForegroundBlock | undefined {
594
+ if (state.desktop.toLowerCase() !== 'default') return BLOCKS.secure_desktop()
595
+ const front = state.foreground?.exe.toLowerCase()
596
+ const protectedKind = front === undefined ? undefined : PROTECTED_PROCESSES.get(front)
597
+ if (protectedKind) return BLOCKS[protectedKind]()
598
+ if (state.selfElevated) return undefined
599
+ if (state.target?.elevated) return BLOCKS.elevated_target()
600
+ // Windows will not let a program with lower rights take the front from one
601
+ // with higher rights, so the burst could neither raise its target nor type.
602
+ if (state.foreground?.elevated) return BLOCKS.elevated_target(true)
603
+ return undefined
604
+ }
605
+ }
606
+
607
+ /** A burst for the desktop as such is for whichever program is in front when it starts. */
608
+ function effectiveSubject(subject: ForegroundSubject, state: MonitorState): ForegroundSubject {
609
+ if (subject.exe !== undefined || subject.pid !== undefined || !state.foreground) return subject
610
+ const exe = state.foreground.exe
611
+ return {
612
+ app: exe.replace(/\.exe$/i, '') || subject.app,
613
+ exe,
614
+ pid: state.foreground.pid,
615
+ }
616
+ }