@sixb/cli 0.2.0 → 0.2.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.
Files changed (67) hide show
  1. package/dist/commands/agent.d.ts +4 -1
  2. package/dist/commands/agent.d.ts.map +1 -1
  3. package/dist/commands/connect.d.ts +13 -0
  4. package/dist/commands/connect.d.ts.map +1 -0
  5. package/dist/commands/db-migrate.d.ts.map +1 -1
  6. package/dist/commands/db-prepare.d.ts.map +1 -1
  7. package/dist/commands/desktop.d.ts.map +1 -1
  8. package/dist/lib/command-line.d.ts +11 -1
  9. package/dist/lib/command-line.d.ts.map +1 -1
  10. package/dist/{tui → lib}/connection.d.ts +11 -1
  11. package/dist/{tui → lib}/connection.d.ts.map +1 -1
  12. package/dist/lib/desktop.d.ts +4 -0
  13. package/dist/lib/desktop.d.ts.map +1 -1
  14. package/dist/lib/dev-supervisor.d.ts.map +1 -1
  15. package/dist/lib/profiles.d.ts +5 -0
  16. package/dist/lib/profiles.d.ts.map +1 -1
  17. package/dist/lib/runtime.d.ts.map +1 -1
  18. package/dist/runner/allowed-folders.d.ts +17 -0
  19. package/dist/runner/allowed-folders.d.ts.map +1 -0
  20. package/dist/runner/computer-connection.d.ts +70 -0
  21. package/dist/runner/computer-connection.d.ts.map +1 -0
  22. package/dist/runner/computer.d.ts.map +1 -0
  23. package/dist/runner/desktop-runner-main.d.ts +2 -0
  24. package/dist/runner/desktop-runner-main.d.ts.map +1 -0
  25. package/dist/runner/desktop-runner.d.ts +43 -0
  26. package/dist/runner/desktop-runner.d.ts.map +1 -0
  27. package/dist/runner/keep-awake.d.ts +11 -0
  28. package/dist/runner/keep-awake.d.ts.map +1 -0
  29. package/dist/runner/local-runner.d.ts +131 -0
  30. package/dist/runner/local-runner.d.ts.map +1 -0
  31. package/dist/tui/app.d.ts +2 -2
  32. package/dist/tui/app.d.ts.map +1 -1
  33. package/dist/tui/format.d.ts +29 -0
  34. package/dist/tui/format.d.ts.map +1 -1
  35. package/dist/tui/index.d.ts.map +1 -1
  36. package/dist/tui/settings.d.ts +5 -8
  37. package/dist/tui/settings.d.ts.map +1 -1
  38. package/package.json +17 -17
  39. package/src/commands/agent.ts +122 -39
  40. package/src/commands/connect.ts +197 -0
  41. package/src/commands/db-migrate.ts +1 -0
  42. package/src/commands/db-prepare.ts +1 -0
  43. package/src/commands/desktop.ts +2 -1
  44. package/src/index.tsx +13 -0
  45. package/src/lib/command-line.ts +22 -3
  46. package/src/{tui → lib}/connection.ts +64 -17
  47. package/src/lib/desktop.ts +8 -1
  48. package/src/lib/dev-supervisor.ts +7 -2
  49. package/src/lib/profiles.ts +15 -1
  50. package/src/lib/runtime.ts +1 -0
  51. package/src/lib/storage-migration.ts +1 -0
  52. package/src/runner/allowed-folders.ts +126 -0
  53. package/src/runner/computer-connection.ts +184 -0
  54. package/src/runner/desktop-runner-main.ts +9 -0
  55. package/src/runner/desktop-runner.ts +217 -0
  56. package/src/runner/keep-awake.ts +50 -0
  57. package/src/runner/local-runner.ts +427 -0
  58. package/src/tui/app.tsx +168 -12
  59. package/src/tui/format.ts +203 -6
  60. package/src/tui/index.tsx +14 -13
  61. package/src/tui/settings.ts +12 -44
  62. package/dist/tui/computer.d.ts.map +0 -1
  63. package/dist/tui/runner.d.ts +0 -75
  64. package/dist/tui/runner.d.ts.map +0 -1
  65. package/src/tui/runner.ts +0 -256
  66. /package/dist/{tui → runner}/computer.d.ts +0 -0
  67. /package/src/{tui → runner}/computer.ts +0 -0
@@ -0,0 +1,217 @@
1
+ import { realpath, stat } from "node:fs/promises"
2
+ import { normalizeApiUrl } from "../lib/api-client"
3
+ import {
4
+ type Connection,
5
+ connect,
6
+ profilesSignedInTo,
7
+ type SignedOut,
8
+ startSignInBeside,
9
+ } from "../lib/connection"
10
+ import { errorMessage } from "../lib/errors"
11
+ import { loadSettings } from "../tui/settings"
12
+ import { forgetFolderAt, setFoldersAllowed } from "./allowed-folders"
13
+ import { thisComputer } from "./computer"
14
+ import { ComputerConnection, type ComputerEvent, EXIT_SIGNED_OUT } from "./computer-connection"
15
+ import { stopInTime, stopOnHangUp } from "./local-runner"
16
+
17
+ /** How long until connecting is tried again, after the project didn't answer or anything else. */
18
+ const CONNECT_RETRY_MS = 10_000
19
+
20
+ /** What this prints, one line of JSON each. The desktop app reads them. */
21
+ export type DesktopRunnerEvent =
22
+ | ComputerEvent
23
+ | { readonly type: "computer"; readonly id: string; readonly name: string }
24
+ | { readonly type: "connected" }
25
+ | { readonly type: "signed-out-waiting" }
26
+ | { readonly type: "sign-in"; readonly url: string; readonly userCode: string }
27
+ | { readonly type: "sign-in-failed"; readonly message: string }
28
+ | { readonly type: "unreachable"; readonly message: string }
29
+
30
+ /** What this reads, one line of JSON each. Only the desktop app holds the other end. */
31
+ export type DesktopRunnerCommand =
32
+ | { readonly type: "allow"; readonly folder: string }
33
+ | { readonly type: "forget"; readonly folder: string }
34
+
35
+ function parseCommand(line: string): DesktopRunnerCommand | null {
36
+ try {
37
+ const parsed = JSON.parse(line) as Partial<DesktopRunnerCommand> | null
38
+ return (parsed?.type === "allow" || parsed?.type === "forget") &&
39
+ typeof parsed.folder === "string"
40
+ ? (parsed as DesktopRunnerCommand)
41
+ : null
42
+ } catch {
43
+ return null
44
+ }
45
+ }
46
+
47
+ /**
48
+ * This computer, connected for a desktop app: `sixb connect` with no person at a terminal to ask.
49
+ * Holding the sign-in here keeps it from the app's main process, and from the page beyond that: it
50
+ * goes beside the CLI's, where the agent's commands can't read it, and a sign-in from `sixb login`
51
+ * counts. It ends with its stdin, so it can't outlive the app that started it.
52
+ */
53
+ export async function runDesktopRunner(options: {
54
+ readonly apiUrl: string
55
+ /** Who the person is asked to approve, in the browser. */
56
+ readonly clientName: string
57
+ /** Where the app keeps its window's sign-in, as cookies a command could otherwise read. */
58
+ readonly windowData?: string
59
+ }): Promise<void> {
60
+ const { apiUrl, clientName, windowData } = options
61
+ const emit = (event: DesktopRunnerEvent): void => {
62
+ process.stdout.write(`${JSON.stringify(event)}\n`)
63
+ }
64
+ const { id, name } = await thisComputer()
65
+ emit({ type: "computer", id, name })
66
+
67
+ const { keepAwake } = await loadSettings()
68
+ let connection: Connection | null = null
69
+ let computer: ComputerConnection | null = null
70
+ let signingIn = false
71
+ let signInShown: DesktopRunnerEvent | null = null
72
+ let signedOutNow = false
73
+ let retry: ReturnType<typeof setTimeout> | null = null
74
+ // What was allowed before there was a project to allow it for.
75
+ let allowedMeanwhile: string[] = []
76
+ let finish: (code: number) => void = () => {}
77
+ const finished = new Promise<number>((resolve) => {
78
+ finish = resolve
79
+ })
80
+
81
+ const stop = () => stopInTime(computer)
82
+ const reportFailure = (error: unknown) => emit({ type: "error", message: errorMessage(error) })
83
+
84
+ const allow = async (signedIn: Connection, chosen: string) => {
85
+ // As the project keeps it, and the local sandbox compares it: its real path.
86
+ const folder = await realpath(chosen)
87
+ if (!(await stat(folder)).isDirectory()) throw new Error(`${folder} isn't a folder.`)
88
+ await setFoldersAllowed(signedIn, [folder], true)
89
+ }
90
+
91
+ /** The first sign-in here the project still takes: one that's ended mustn't hide a newer one. */
92
+ const firstThatConnects = async (): Promise<Connection | SignedOut> => {
93
+ for (const profile of await profilesSignedInTo(apiUrl)) {
94
+ const result = await connect({ profile })
95
+ if (!("reason" in result) || result.reason === "unreachable") return result
96
+ }
97
+ return connect({ apiUrl })
98
+ }
99
+
100
+ const tryConnecting = async (): Promise<void> => {
101
+ if (connection) return
102
+ const result = await firstThatConnects()
103
+ // A sign-in finishing and a retry coming due can both get here.
104
+ if (connection) return
105
+ if ("reason" in result) {
106
+ if (result.reason === "unreachable") {
107
+ emit({ type: "unreachable", message: result.message ?? `No answer from ${apiUrl}.` })
108
+ retry = setTimeout(connectOrRetry, CONNECT_RETRY_MS)
109
+ return
110
+ }
111
+ signedOutNow = true
112
+ emit({ type: "signed-out-waiting" })
113
+ if (allowedMeanwhile.length > 0) await signIn()
114
+ return
115
+ }
116
+
117
+ signedOutNow = false
118
+ connection = result
119
+ emit({ type: "connected" })
120
+ for (const folder of allowedMeanwhile.splice(0)) hear({ type: "allow", folder })
121
+
122
+ computer = new ComputerConnection(
123
+ result,
124
+ (event) => {
125
+ // Started again, this asks for a new sign-in.
126
+ if (event.type === "signed-out") void stop().finally(() => finish(EXIT_SIGNED_OUT))
127
+ emit(event)
128
+ },
129
+ keepAwake,
130
+ windowData ? [windowData] : []
131
+ )
132
+ await computer.start()
133
+ }
134
+
135
+ /** Whatever stopped it, such as a config it can't read, it's tried again: nothing else would. */
136
+ const connectOrRetry = (): void => {
137
+ void tryConnecting().catch((error: unknown) => {
138
+ reportFailure(error)
139
+ connection = null
140
+ computer = null
141
+ retry = setTimeout(connectOrRetry, CONNECT_RETRY_MS)
142
+ })
143
+ }
144
+
145
+ const signIn = async (): Promise<void> => {
146
+ if (connection) return
147
+ if (signingIn) {
148
+ // They closed the page, or never saw it: asking again is how they get back to it.
149
+ if (signInShown) emit(signInShown)
150
+ return
151
+ }
152
+ signingIn = true
153
+ try {
154
+ const pending = await startSignInBeside(apiUrl, clientName)
155
+ signInShown = { type: "sign-in", url: pending.url, userCode: pending.userCode }
156
+ emit(signInShown)
157
+ await pending.complete(new AbortController().signal)
158
+ // Not to be asked again while connecting finds that out.
159
+ signedOutNow = false
160
+ connectOrRetry()
161
+ } catch (error) {
162
+ emit({ type: "sign-in-failed", message: errorMessage(error) })
163
+ } finally {
164
+ signingIn = false
165
+ signInShown = null
166
+ }
167
+ }
168
+
169
+ const apply = async (command: DesktopRunnerCommand): Promise<void> => {
170
+ if (command.type === "forget") {
171
+ allowedMeanwhile = allowedMeanwhile.filter((folder) => folder !== command.folder)
172
+ await forgetFolderAt(normalizeApiUrl(apiUrl), command.folder)
173
+ } else if (connection) {
174
+ await allow(connection, command.folder)
175
+ } else {
176
+ allowedMeanwhile.push(command.folder)
177
+ if (signedOutNow) void signIn()
178
+ }
179
+ }
180
+
181
+ /** One at a time, as they came: a folder allowed and then forgotten stays forgotten. */
182
+ let commands: Promise<void> = Promise.resolve()
183
+ const hear = (command: DesktopRunnerCommand) => {
184
+ commands = commands.then(() => apply(command)).catch(reportFailure)
185
+ }
186
+
187
+ void (async () => {
188
+ let rest = ""
189
+ const decoder = new TextDecoder()
190
+ for await (const chunk of Bun.stdin.stream()) {
191
+ rest += decoder.decode(chunk, { stream: true })
192
+ const lines = rest.split("\n")
193
+ rest = lines.pop() ?? ""
194
+ for (const line of lines) {
195
+ const command = parseCommand(line)
196
+ if (command) hear(command)
197
+ }
198
+ }
199
+ // The app is gone, however it went: what it started goes too, after what it last asked for.
200
+ if (retry) clearTimeout(retry)
201
+ void commands.then(stop).finally(() => finish(0))
202
+ })()
203
+
204
+ // Ctrl+C in the terminal running `sixb dev --desktop` reaches this too. Its stdin closing, as the
205
+ // app goes, is what ends it, with a running turn's end recorded.
206
+ process.on("SIGINT", () => {})
207
+
208
+ const unhook = stopOnHangUp(
209
+ () => computer,
210
+ (signal) => finish(signal === "SIGHUP" ? 129 : 143)
211
+ )
212
+ connectOrRetry()
213
+
214
+ const code = await finished
215
+ unhook()
216
+ process.exit(code)
217
+ }
@@ -0,0 +1,50 @@
1
+ import { platform } from "node:os"
2
+
3
+ /** A hold on the computer's staying awake: ending it twice is ending it once. */
4
+ export type ReleaseAwake = () => void
5
+
6
+ /** Keeps the computer awake while any hold is held, however many turns run. */
7
+ export function createKeepAwake(start: () => (() => void) | null) {
8
+ let holds = 0
9
+ let stop: (() => void) | null = null
10
+
11
+ return {
12
+ hold(): ReleaseAwake {
13
+ holds += 1
14
+ if (holds === 1) stop = start()
15
+ let released = false
16
+ return () => {
17
+ if (released) return
18
+ released = true
19
+ holds -= 1
20
+ if (holds > 0) return
21
+ stop?.()
22
+ stop = null
23
+ }
24
+ },
25
+ }
26
+ }
27
+
28
+ /**
29
+ * On macOS, `caffeinate` for as long as this process lives: `-i` holds off idle sleep, on battery
30
+ * too, and `-w` ends it with this process, so a crash can't leave the computer awake. A closed lid
31
+ * still sleeps. Other systems stay as they are for now, and a failure only means no hold.
32
+ */
33
+ function startCaffeinate(): (() => void) | null {
34
+ if (platform() !== "darwin") return null
35
+ try {
36
+ const child = Bun.spawn(["caffeinate", "-i", "-w", String(process.pid)], {
37
+ stdin: "ignore",
38
+ stdout: "ignore",
39
+ stderr: "ignore",
40
+ })
41
+ // It must not keep this process alive: it waits for this process to end.
42
+ child.unref()
43
+ return () => child.kill()
44
+ } catch {
45
+ return null
46
+ }
47
+ }
48
+
49
+ /** One per process, as every folder's turns share one computer. */
50
+ export const keepAwake = createKeepAwake(startCaffeinate)
@@ -0,0 +1,427 @@
1
+ import { randomUUID } from "node:crypto"
2
+ import { homedir, tmpdir } from "node:os"
3
+ import { dirname, join } from "node:path"
4
+ import {
5
+ type ComputerBackgroundCommand,
6
+ type ComputerBackgroundCommandRef,
7
+ ComputerRunner,
8
+ } from "@sixb/agent"
9
+ import {
10
+ type GetAgentThreadResponses,
11
+ getAgentRun,
12
+ getAgentThread,
13
+ holdAgentComputerSession,
14
+ isSixbApiError,
15
+ releaseAgentComputerSession,
16
+ } from "@sixb/client"
17
+ import type { ConversationAgentRunRecord } from "@sixb/core/storage"
18
+ import { LocalSandboxFactory } from "@sixb/sandboxes-local"
19
+ import type { Connection } from "../lib/connection"
20
+ import { resolveConfigPath } from "../lib/profiles"
21
+ import { thisComputer, thisComputerId } from "./computer"
22
+ import { keepAwake, type ReleaseAwake } from "./keep-awake"
23
+
24
+ /** How long stopping waits for a running turn to record its end, or the project to answer. */
25
+ const STOP_WAIT_MS = 10_000
26
+ /** How often an open `sixb` renews its session, which lapses a minute after its last renewal. */
27
+ const SESSION_RENEW_MS = 20_000
28
+
29
+ /**
30
+ * What the agent's commands never read on this computer, whatever the folder: the CLI's own
31
+ * sign-in, and the credentials SSH and AWS keep.
32
+ */
33
+ export function deniedPaths(): readonly string[] {
34
+ return [dirname(resolveConfigPath()), join(homedir(), ".ssh"), join(homedir(), ".aws")]
35
+ }
36
+
37
+ export interface LocalRunnerOptions {
38
+ /**
39
+ * The session stopped renewing, or started again, or fails differently now: called when that
40
+ * changes, not at each renewal. A refusal from the project is a `SixbApiError`.
41
+ */
42
+ readonly onSessionChange?: (failure: unknown | null) => void
43
+ /** How a running turn keeps the computer awake. By default, `keepAwake`. */
44
+ readonly holdAwake?: () => ReleaseAwake
45
+ /** What the agent's commands also never read, beyond `deniedPaths`. */
46
+ readonly alsoDenied?: readonly string[]
47
+ }
48
+
49
+ /**
50
+ * This computer as a runner: it claims its owner's turns from the project and runs them in one
51
+ * folder, each until it ends or is stopped. While its session is open, the project knows `sixb` is
52
+ * open here, and the turns sent from elsewhere to the conversations of this folder run here too, one
53
+ * at a time: nobody may be watching, and two turns would edit the same files.
54
+ */
55
+ export class LocalRunner {
56
+ private readonly runner: ComputerRunner
57
+ private readonly running = new Map<
58
+ string,
59
+ { readonly stop: AbortController; readonly done: Promise<boolean> }
60
+ >()
61
+ private readonly elsewhereListeners = new Set<
62
+ (run: ConversationAgentRunRecord, ended: Promise<boolean>) => void
63
+ >()
64
+ private readonly backgroundListeners = new Set<() => void>()
65
+ private session: {
66
+ readonly id: string
67
+ readonly timer: ReturnType<typeof setInterval>
68
+ readonly renew: () => void
69
+ } | null = null
70
+ /** Why the session last failed, null while it renews. A change in why is news: see noteSession. */
71
+ private sessionFailure: string | null = null
72
+ /** Whether a running turn keeps the computer awake: the person's setting. */
73
+ keepsAwake = true
74
+ /** The session's last call: its release follows a renewal, which would open it again. */
75
+ private lastCall: Promise<void> = Promise.resolve()
76
+
77
+ constructor(
78
+ private readonly connection: Connection,
79
+ /** The folder `sixb` was opened in: its real path, as the project keeps it. */
80
+ readonly folder: string,
81
+ private readonly onFailure: (error: unknown) => void,
82
+ private readonly options: LocalRunnerOptions = {}
83
+ ) {
84
+ this.runner = new ComputerRunner({
85
+ apiUrl: connection.apiUrl,
86
+ authorization: () => connection.authorization(),
87
+ computer: thisComputer,
88
+ folder,
89
+ runFilesRoot: join(tmpdir(), "sixb-agent"),
90
+ onFailure,
91
+ // The web shows a command start and end at once, and so does the screen.
92
+ onBackgroundChange: () => {
93
+ this.session?.renew()
94
+ for (const listener of this.backgroundListeners) listener()
95
+ },
96
+ openSandbox: ({ workingDirectory, runFiles, credential, signal }) =>
97
+ new LocalSandboxFactory({
98
+ readWritePaths: [runFiles],
99
+ denyReadPaths: [...deniedPaths(), ...(options.alsoDenied ?? [])],
100
+ network: { mode: "all" },
101
+ }).create({
102
+ ...(workingDirectory === undefined ? {} : { workingDirectory }),
103
+ network: { mode: "all" },
104
+ requestCredentials: [credential],
105
+ signal,
106
+ }),
107
+ })
108
+ }
109
+
110
+ /** Hear each turn sent from elsewhere as it starts to run here. Returns the unsubscribe. */
111
+ onElsewhere(
112
+ listener: (run: ConversationAgentRunRecord, ended: Promise<boolean>) => void
113
+ ): () => void {
114
+ this.elsewhereListeners.add(listener)
115
+ return () => this.elsewhereListeners.delete(listener)
116
+ }
117
+
118
+ /** Whether this computer runs `runId` now. */
119
+ runs(runId: string): boolean {
120
+ return this.running.has(runId)
121
+ }
122
+
123
+ /**
124
+ * Claim a queued turn and run it, unless this computer runs it already. Resolves once the turn
125
+ * ended here: false when it was not this computer's to run, or could not be claimed.
126
+ */
127
+ claim(runId: string, onClaimed?: (run: ConversationAgentRunRecord) => void): Promise<boolean> {
128
+ const running = this.running.get(runId)
129
+ if (running) return running.done
130
+ const stop = new AbortController()
131
+ const holdAwake = this.options.holdAwake ?? keepAwake.hold
132
+ const releaseAwake = this.keepsAwake ? holdAwake() : null
133
+ const done = this.runner
134
+ .runTurn(runId, stop.signal, onClaimed)
135
+ .catch((error: unknown) => {
136
+ this.onFailure(error)
137
+ return false
138
+ })
139
+ .finally(() => {
140
+ this.running.delete(runId)
141
+ releaseAwake?.()
142
+ })
143
+ // What waited for this turn runs now, not at the next renewal. Only after one that ran: one that
144
+ // couldn't be claimed may be listed again, and asking at once would ask forever.
145
+ void done.then((ran) => {
146
+ if (ran) this.session?.renew()
147
+ })
148
+ this.running.set(runId, { stop, done })
149
+ return done
150
+ }
151
+
152
+ /**
153
+ * Hold this `sixb`'s session while it is open: the conversations of this folder read as online,
154
+ * and the turns waiting for them are claimed. Idempotent.
155
+ */
156
+ openSession(): void {
157
+ if (this.session) return
158
+ const id = `cs_${randomUUID()}`
159
+ const hold = async () => {
160
+ // Read as it is sent, so a renewal that waited its turn reports the commands as they are.
161
+ const backgroundCommands = this.runner.backgroundCommands()
162
+ const stalled = new AbortController()
163
+ const giveUp = setTimeout(() => stalled.abort(), SESSION_RENEW_MS)
164
+
165
+ const { data, error } = await holdAgentComputerSession({
166
+ client: this.connection.client,
167
+ path: { sessionId: id },
168
+ body: {
169
+ computer: { ...(await thisComputer()), folder: this.folder },
170
+ ...(backgroundCommands.length > 0 ? { backgroundCommands: [...backgroundCommands] } : {}),
171
+ },
172
+ signal: stalled.signal,
173
+ }).finally(() => clearTimeout(giveUp))
174
+
175
+ if (error) throw error
176
+ this.noteSession(id, null)
177
+ void this.claimFirst(id, data?.waiting ?? [])
178
+ if (this.session?.id !== id) return
179
+ for (const ref of data?.stop ?? []) void this.stopBackground(ref)
180
+ }
181
+
182
+ // One renewal at a time, in order, so an older report never lands after a newer one; one
183
+ // asked for while another waits its turn is that one. One that stalls gives up when the next
184
+ // is due, so it can't hold up those behind it. A missed renewal is retried at the next; the
185
+ // session lasts three of them.
186
+ let queued = false
187
+ const renew = () => {
188
+ if (queued) return
189
+ queued = true
190
+ this.lastCall = this.lastCall
191
+ .then(() => {
192
+ queued = false
193
+ return hold()
194
+ })
195
+ .catch((error: unknown) => this.noteSession(id, error))
196
+ }
197
+ this.session = { id, timer: setInterval(renew, SESSION_RENEW_MS), renew }
198
+ renew()
199
+ }
200
+
201
+ /**
202
+ * Renew the session now rather than at its next renewal, when the project says something
203
+ * changed for this folder: a stop asked for from the web is in the answer.
204
+ */
205
+ renewSession(): void {
206
+ this.session?.renew()
207
+ }
208
+
209
+ /** This folder's background commands, by thread: the running ones, then the latest to end. */
210
+ backgroundCommands(threadId?: string): readonly ComputerBackgroundCommand[] {
211
+ const all = this.runner.backgroundCommands()
212
+ return threadId === undefined ? all : all.filter((command) => command.threadId === threadId)
213
+ }
214
+
215
+ /** Hear each background command start and end. Returns the unsubscribe. */
216
+ onBackground(listener: () => void): () => void {
217
+ this.backgroundListeners.add(listener)
218
+ return () => this.backgroundListeners.delete(listener)
219
+ }
220
+
221
+ /**
222
+ * Stop a background command, and everything it started, as the agent's `bash_stop` does. False
223
+ * when it ended already, or is not this `sixb`'s.
224
+ */
225
+ async stopBackground(ref: ComputerBackgroundCommandRef): Promise<boolean> {
226
+ try {
227
+ return await this.runner.stopBackgroundCommand(ref)
228
+ } catch (error) {
229
+ this.onFailure(error)
230
+ return false
231
+ }
232
+ }
233
+
234
+ /** Close the session: the conversations of this folder read as offline at once. */
235
+ async closeSession(): Promise<void> {
236
+ const session = this.session
237
+ if (session) {
238
+ this.session = null
239
+ this.sessionFailure = null
240
+ clearInterval(session.timer)
241
+ // Whoever closes it next waits for this one, as quitting does after the screen let go.
242
+ this.lastCall = this.lastCall
243
+ .then(() =>
244
+ releaseAgentComputerSession({
245
+ client: this.connection.client,
246
+ path: { sessionId: session.id },
247
+ })
248
+ )
249
+ .then(
250
+ () => {},
251
+ () => {}
252
+ )
253
+ }
254
+ await this.lastCall
255
+ }
256
+
257
+ /**
258
+ * Claim a turn sent from elsewhere when this computer runs its conversation: its owner's, on this
259
+ * computer and in this folder, and still queued, while the session is open. A running turn is
260
+ * another sixb's, or one whose sixb closed, which the API ends interrupted: claiming it again
261
+ * would run its commands twice.
262
+ */
263
+ async claimIfHere(threadId: string, runId?: string): Promise<void> {
264
+ if (!this.session || (runId && this.running.has(runId))) return
265
+ const { client } = this.connection
266
+ const { data: thread } = await getAgentThread({ client, path: { threadId } })
267
+ if (thread) await this.offer(thread, runId)
268
+ }
269
+
270
+ /** As `claimIfHere`, for a caller that has read the thread already. */
271
+ async offer(thread: GetAgentThreadResponses[200], runId?: string): Promise<void> {
272
+ if (!this.session || !this.runsHere(thread, await thisComputerId())) return
273
+
274
+ const turn = runId ?? thread.activeRunId
275
+ if (!turn) return
276
+ const { client } = this.connection
277
+ const { data: run } = await getAgentRun({ client, path: { runId: turn } })
278
+ if (run?.status === "queued" && this.session) void this.claimElsewhere(turn)
279
+ }
280
+
281
+ /** Whether this `sixb` runs `thread`'s turns: its owner's, on this computer, in this folder. */
282
+ runsHere(thread: GetAgentThreadResponses[200], computerId: string): boolean {
283
+ return (
284
+ thread.runsOn === "computer" &&
285
+ owns(this.connection, thread) &&
286
+ thread.computer?.id === computerId &&
287
+ thread.computer.folder === this.folder
288
+ )
289
+ }
290
+
291
+ /** After a stop was asked for: the turn hears it now, not at its next lease renewal. */
292
+ hearStop(runId: string): void {
293
+ this.runner.renewNow(runId)
294
+ }
295
+
296
+ /** Whether a turn runs here now. */
297
+ get busy(): boolean {
298
+ return this.running.size > 0
299
+ }
300
+
301
+ /** Whether a background command a turn started here runs now. */
302
+ get runsBackgroundCommands(): boolean {
303
+ return this.runner.runsBackgroundCommands
304
+ }
305
+
306
+ /**
307
+ * Stop every turn this computer runs, each ending interrupted with its end recorded, and the
308
+ * background commands they left running, and close the session.
309
+ */
310
+ async stop(): Promise<void> {
311
+ const running = [...this.running.values()]
312
+ for (const { stop } of running) stop.abort()
313
+ await Promise.allSettled([...running.map(({ done }) => done), this.closeSession()])
314
+ await this.runner.stopBackgroundCommands()
315
+ await this.runner.drain()
316
+ }
317
+
318
+ /**
319
+ * Claim a turn sent from elsewhere, and say so. Left waiting while a turn runs here: it runs once
320
+ * that one ends, or at a later renewal.
321
+ */
322
+ claimElsewhere(runId: string): Promise<boolean> {
323
+ if (this.running.size > 0) return Promise.resolve(false)
324
+ return this.claim(runId, (run) => {
325
+ const ended = this.running.get(run.id)?.done ?? Promise.resolve(false)
326
+ for (const listener of this.elsewhereListeners) listener(run, ended)
327
+ })
328
+ }
329
+
330
+ /**
331
+ * The first that can be claimed, so one that keeps failing can't hold up those behind it. Until
332
+ * `sessionId` closes, with the setting or by quitting: what waits keeps waiting. Trying one can
333
+ * take as long as a turn, so that's asked before each.
334
+ */
335
+ private async claimFirst(sessionId: string, runIds: readonly string[]): Promise<void> {
336
+ for (const runId of runIds) {
337
+ if (this.session?.id !== sessionId) return
338
+ if (await this.claimElsewhere(runId)) return
339
+ }
340
+ }
341
+
342
+ /** A renewal that lands after its session closed says nothing about the one now, if any. */
343
+ private noteSession(sessionId: string, failure: unknown | null): void {
344
+ if (this.session?.id !== sessionId) return
345
+ const reason = failure === null ? null : failureReason(failure)
346
+ if (reason === this.sessionFailure) return
347
+ this.sessionFailure = reason
348
+ if (this.options.onSessionChange) {
349
+ this.options.onSessionChange(failure)
350
+ } else if (failure !== null) {
351
+ this.onFailure(failure)
352
+ }
353
+ }
354
+ }
355
+
356
+ function failureReason(failure: unknown): string {
357
+ if (isSixbApiError(failure)) return `${failure.status}`
358
+ return failure instanceof Error ? failure.message : String(failure)
359
+ }
360
+
361
+ /** Whether the person signed in owns `thread`: with sign-in off, the system owns what it starts. */
362
+ export function owns(
363
+ connection: Pick<Connection, "user">,
364
+ thread: Pick<GetAgentThreadResponses[200], "ownerPrincipal">
365
+ ): boolean {
366
+ const owner = thread.ownerPrincipal
367
+ return connection.user
368
+ ? owner.type === "user" && owner.id === connection.user.id
369
+ : owner.type === "system"
370
+ }
371
+
372
+ /** Stop, for as long as a person or a service manager should wait for that. */
373
+ export async function stopInTime(running: Pick<LocalRunner, "stop"> | null): Promise<void> {
374
+ let timer: ReturnType<typeof setTimeout> | undefined
375
+ const waited = new Promise<void>((resolve) => {
376
+ timer = setTimeout(resolve, STOP_WAIT_MS)
377
+ })
378
+ await Promise.race([running?.stop(), waited])
379
+ clearTimeout(timer)
380
+ }
381
+
382
+ /**
383
+ * Quitting `sixb`: the turns running here end interrupted, their end recorded, the background
384
+ * commands they left stop, and the session closes, within `waitMs`, whether a turn runs or not.
385
+ * `note` says what it waits for.
386
+ */
387
+ export async function stopOnQuit(
388
+ runner: Pick<LocalRunner, "busy" | "runsBackgroundCommands" | "stop">,
389
+ waitMs: number,
390
+ note: (text: string) => void
391
+ ): Promise<void> {
392
+ if (runner.busy) note("Stopping the turn running here…")
393
+ else if (runner.runsBackgroundCommands) note("Stopping the background commands running here…")
394
+
395
+ let timer: ReturnType<typeof setTimeout> | undefined
396
+ await Promise.race([
397
+ runner.stop(),
398
+ new Promise<void>((resolve) => {
399
+ timer = setTimeout(resolve, waitMs)
400
+ }),
401
+ ])
402
+ clearTimeout(timer)
403
+ }
404
+
405
+ /**
406
+ * A closed terminal, or a kill, ends sixb as quitting does: the turns running here stop, each
407
+ * ending interrupted with its end recorded, instead of renewing their lease from a process nobody
408
+ * sees, and the session closes. Then `exit`, after a bounded wait. Returns the removal of the
409
+ * handlers.
410
+ */
411
+ export function stopOnHangUp(
412
+ runner: () => Pick<LocalRunner, "stop"> | null,
413
+ exit: (signal: "SIGHUP" | "SIGTERM") => void
414
+ ): () => void {
415
+ const hangUp = (signal: "SIGHUP" | "SIGTERM") => {
416
+ void stopInTime(runner()).finally(() => exit(signal))
417
+ }
418
+
419
+ const onHangUp = () => hangUp("SIGHUP")
420
+ const onTerminate = () => hangUp("SIGTERM")
421
+ process.on("SIGHUP", onHangUp)
422
+ process.on("SIGTERM", onTerminate)
423
+ return () => {
424
+ process.off("SIGHUP", onHangUp)
425
+ process.off("SIGTERM", onTerminate)
426
+ }
427
+ }