@sixb/cli 0.2.1 → 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
@@ -1,4 +1,4 @@
1
- import { readFile, rename, writeFile } from "node:fs/promises"
1
+ import { readFile, writeFile } from "node:fs/promises"
2
2
  import { type as osType } from "node:os"
3
3
  import { dirname, join } from "node:path"
4
4
  import type { ListModelsResponses } from "@sixb/client"
@@ -21,15 +21,19 @@ export interface Settings {
21
21
  /**
22
22
  * Whether your messages from the web, or another device, run in this folder: while it is on,
23
23
  * `sixb` tells the project it is open here, and runs the turns sent to its conversations here.
24
- * Kept per folder, apart from the settings every `sixb` rewrites: see {@link rememberWebMessages}.
24
+ * Kept per folder and project, apart from the settings every `sixb` rewrites, and read once
25
+ * connected, so it is off until then: `runner/allowed-folders.ts`.
25
26
  */
26
27
  readonly continueFromWeb: boolean
28
+ /** Whether a turn running on this computer keeps it from going to sleep. */
29
+ readonly keepAwake: boolean
27
30
  }
28
31
 
29
32
  export const DEFAULT_SETTINGS: Settings = {
30
33
  place: "computer",
31
34
  approvalMode: "manual",
32
- continueFromWeb: true,
35
+ continueFromWeb: false,
36
+ keepAwake: true,
33
37
  }
34
38
 
35
39
  export const APPROVAL_MODES: readonly {
@@ -70,44 +74,7 @@ export function placeLabel(place: Place): string {
70
74
 
71
75
  const SETTINGS_FILE = () => join(dirname(resolveConfigPath()), "tui.json")
72
76
 
73
- /** The folders where the person turned off messages from the web. */
74
- const WEB_MESSAGES_OFF_FILE = () => join(dirname(resolveConfigPath()), "web-messages-off.json")
75
-
76
- async function foldersWithWebMessagesOff(): Promise<readonly string[]> {
77
- const text = await readFile(WEB_MESSAGES_OFF_FILE(), "utf8").catch((error: unknown) => {
78
- if ((error as NodeJS.ErrnoException).code === "ENOENT") return "[]"
79
- throw error
80
- })
81
- const stored: unknown = JSON.parse(text)
82
- if (!Array.isArray(stored)) throw new Error("[SixbCLI] Unreadable web-messages-off.json.")
83
- return stored.filter((folder): folder is string => typeof folder === "string")
84
- }
85
-
86
- /** On unless turned off in `folder`. A choice it can't read stays off rather than run turns here. */
87
- async function webMessagesOnIn(folder: string): Promise<boolean> {
88
- return foldersWithWebMessagesOff().then(
89
- (folders) => !folders.includes(folder),
90
- () => false
91
- )
92
- }
93
-
94
- /**
95
- * Keep the choice for this folder alone. Reads the file first, as another `sixb` may have written
96
- * it, and refuses one it can't read rather than lose the other folders' choices. Written whole, so
97
- * no reader ever finds half of it.
98
- */
99
- export async function rememberWebMessages(folder: string, on: boolean): Promise<void> {
100
- const others = (await foldersWithWebMessagesOff()).filter((other) => other !== folder)
101
- const path = WEB_MESSAGES_OFF_FILE()
102
- const written = `${path}.${process.pid}`
103
- await writeFile(written, `${JSON.stringify(on ? others : [...others, folder], null, 2)}\n`, {
104
- mode: 0o600,
105
- })
106
- await rename(written, path)
107
- }
108
-
109
- export async function loadSettings(folder: string): Promise<Settings> {
110
- const continueFromWeb = await webMessagesOnIn(folder)
77
+ export async function loadSettings(): Promise<Settings> {
111
78
  try {
112
79
  const stored = JSON.parse(await readFile(SETTINGS_FILE(), "utf8")) as Partial<Settings>
113
80
  return {
@@ -117,15 +84,16 @@ export async function loadSettings(folder: string): Promise<Settings> {
117
84
  : DEFAULT_SETTINGS.approvalMode,
118
85
  ...(stored.model?.provider && stored.model.modelId ? { model: stored.model } : {}),
119
86
  ...(stored.reasoning ? { reasoning: stored.reasoning } : {}),
120
- continueFromWeb,
87
+ continueFromWeb: false,
88
+ keepAwake: stored.keepAwake !== false,
121
89
  }
122
90
  } catch {
123
- return { ...DEFAULT_SETTINGS, continueFromWeb }
91
+ return DEFAULT_SETTINGS
124
92
  }
125
93
  }
126
94
 
127
95
  export async function saveSettings(settings: Settings): Promise<void> {
128
- const { continueFromWeb: _perFolder, ...shared } = settings
96
+ const { continueFromWeb: _perProject, ...shared } = settings
129
97
  await writeFile(SETTINGS_FILE(), `${JSON.stringify(shared, null, 2)}\n`, { mode: 0o600 }).catch(
130
98
  () => {}
131
99
  )
@@ -1 +0,0 @@
1
- {"version":3,"file":"computer.d.ts","sourceRoot":"","sources":["../../src/tui/computer.ts"],"names":[],"mappings":"AAeA,iFAAiF;AACjF,wBAAgB,cAAc,IAAI,OAAO,CAAC,MAAM,CAAC,CAUhD;AAED,gGAAgG;AAChG,wBAAsB,YAAY,IAAI,OAAO,CAAC;IAAE,QAAQ,CAAC,EAAE,EAAE,MAAM,CAAC;IAAC,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAA;CAAE,CAAC,CAG5F"}
@@ -1,75 +0,0 @@
1
- import { type GetAgentThreadResponses } from "@sixb/client";
2
- import type { ConversationAgentRunRecord } from "@sixb/core/storage";
3
- import type { Connection } from "./connection";
4
- /**
5
- * What the agent's commands never read on this computer, whatever the folder: the CLI's own
6
- * sign-in, and the credentials SSH and AWS keep.
7
- */
8
- export declare function deniedPaths(): readonly string[];
9
- /**
10
- * This computer as a runner: it claims its owner's turns from the project and runs them in the
11
- * folder `sixb` was opened in, one at a time per turn, each until it ends or is stopped. While its
12
- * session is open, the project knows `sixb` is open here, and the turns sent from elsewhere to the
13
- * conversations of this folder run here too.
14
- */
15
- export declare class LocalRunner {
16
- private readonly connection;
17
- /** The folder `sixb` was opened in: its real path, as the project keeps it. */
18
- readonly folder: string;
19
- private readonly onFailure;
20
- private readonly runner;
21
- private readonly running;
22
- private readonly elsewhereListeners;
23
- private session;
24
- /** The session's last call: its release follows a renewal, which would open it again. */
25
- private lastCall;
26
- constructor(connection: Connection,
27
- /** The folder `sixb` was opened in: its real path, as the project keeps it. */
28
- folder: string, onFailure: (error: unknown) => void);
29
- /** Hear each turn sent from elsewhere as it starts to run here. Returns the unsubscribe. */
30
- onElsewhere(listener: (run: ConversationAgentRunRecord) => void): () => void;
31
- /** Whether this computer runs `runId` now. */
32
- runs(runId: string): boolean;
33
- /**
34
- * Claim a queued turn and run it, unless this computer runs it already. Resolves once the turn
35
- * ended here: false when it was not this computer's to run, or could not be claimed.
36
- */
37
- claim(runId: string, onClaimed?: (run: ConversationAgentRunRecord) => void): Promise<boolean>;
38
- /**
39
- * Hold this `sixb`'s session while it is open: the conversations of this folder read as online,
40
- * and the turns waiting for them are claimed. Idempotent.
41
- */
42
- openSession(): void;
43
- /** Close the session: the conversations of this folder read as offline at once. */
44
- closeSession(): Promise<void>;
45
- /**
46
- * Claim a turn sent from elsewhere when this computer runs its conversation: its owner's, on this
47
- * computer and in this folder, and still queued, while the session is open. A running turn is
48
- * another sixb's, or one whose sixb closed, which the API ends interrupted: claiming it again
49
- * would run its commands twice.
50
- */
51
- claimIfHere(threadId: string, runId?: string): Promise<void>;
52
- /** Whether this `sixb` runs `thread`'s turns: its owner's, on this computer, in this folder. */
53
- runsHere(thread: GetAgentThreadResponses[200], computerId: string): boolean;
54
- /** After a stop was asked for: the turn hears it now, not at its next lease renewal. */
55
- hearStop(runId: string): void;
56
- /** Whether a turn runs here now. */
57
- get busy(): boolean;
58
- /**
59
- * Stop every turn this computer runs, each ending interrupted with its end recorded, and close
60
- * the session.
61
- */
62
- stop(): Promise<void>;
63
- /** A turn this computer already runs joins that run, and is no news. */
64
- private claimElsewhere;
65
- }
66
- /** Whether the person signed in owns `thread`: with sign-in off, the system owns what it starts. */
67
- export declare function owns(connection: Pick<Connection, "user">, thread: Pick<GetAgentThreadResponses[200], "ownerPrincipal">): boolean;
68
- /**
69
- * A closed terminal, or a kill, ends sixb as quitting does: the turns running here stop, each
70
- * ending interrupted with its end recorded, instead of renewing their lease from a process nobody
71
- * sees, and the session closes. Then `exit`, after a bounded wait. Returns the removal of the
72
- * handlers.
73
- */
74
- export declare function stopOnHangUp(runner: () => Pick<LocalRunner, "stop"> | null, exit: (signal: "SIGHUP" | "SIGTERM") => void): () => void;
75
- //# sourceMappingURL=runner.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"runner.d.ts","sourceRoot":"","sources":["../../src/tui/runner.ts"],"names":[],"mappings":"AAIA,OAAO,EACL,KAAK,uBAAuB,EAK7B,MAAM,cAAc,CAAA;AACrB,OAAO,KAAK,EAAE,0BAA0B,EAAE,MAAM,oBAAoB,CAAA;AAIpE,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,cAAc,CAAA;AAO9C;;;GAGG;AACH,wBAAgB,WAAW,IAAI,SAAS,MAAM,EAAE,CAE/C;AAED;;;;;GAKG;AACH,qBAAa,WAAW;IAapB,OAAO,CAAC,QAAQ,CAAC,UAAU;IAC3B,+EAA+E;IAC/E,QAAQ,CAAC,MAAM,EAAE,MAAM;IACvB,OAAO,CAAC,QAAQ,CAAC,SAAS;IAf5B,OAAO,CAAC,QAAQ,CAAC,MAAM,CAAgB;IACvC,OAAO,CAAC,QAAQ,CAAC,OAAO,CAGrB;IACH,OAAO,CAAC,QAAQ,CAAC,kBAAkB,CAAuD;IAC1F,OAAO,CAAC,OAAO,CACT;IACN,yFAAyF;IACzF,OAAO,CAAC,QAAQ,CAAmC;gBAGhC,UAAU,EAAE,UAAU;IACvC,+EAA+E;IACtE,MAAM,EAAE,MAAM,EACN,SAAS,EAAE,CAAC,KAAK,EAAE,OAAO,KAAK,IAAI;IAuBtD,4FAA4F;IAC5F,WAAW,CAAC,QAAQ,EAAE,CAAC,GAAG,EAAE,0BAA0B,KAAK,IAAI,GAAG,MAAM,IAAI;IAK5E,8CAA8C;IAC9C,IAAI,CAAC,KAAK,EAAE,MAAM,GAAG,OAAO;IAI5B;;;OAGG;IACH,KAAK,CAAC,KAAK,EAAE,MAAM,EAAE,SAAS,CAAC,EAAE,CAAC,GAAG,EAAE,0BAA0B,KAAK,IAAI,GAAG,OAAO,CAAC,OAAO,CAAC;IAe7F;;;OAGG;IACH,WAAW,IAAI,IAAI;IAwBnB,mFAAmF;IAC7E,YAAY,IAAI,OAAO,CAAC,IAAI,CAAC;IAqBnC;;;;;OAKG;IACG,WAAW,CAAC,QAAQ,EAAE,MAAM,EAAE,KAAK,CAAC,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;IAYlE,gGAAgG;IAChG,QAAQ,CAAC,MAAM,EAAE,uBAAuB,CAAC,GAAG,CAAC,EAAE,UAAU,EAAE,MAAM,GAAG,OAAO;IAS3E,wFAAwF;IACxF,QAAQ,CAAC,KAAK,EAAE,MAAM,GAAG,IAAI;IAI7B,oCAAoC;IACpC,IAAI,IAAI,IAAI,OAAO,CAElB;IAED;;;OAGG;IACG,IAAI,IAAI,OAAO,CAAC,IAAI,CAAC;IAO3B,wEAAwE;IACxE,OAAO,CAAC,cAAc;CAKvB;AAED,oGAAoG;AACpG,wBAAgB,IAAI,CAClB,UAAU,EAAE,IAAI,CAAC,UAAU,EAAE,MAAM,CAAC,EACpC,MAAM,EAAE,IAAI,CAAC,uBAAuB,CAAC,GAAG,CAAC,EAAE,gBAAgB,CAAC,GAC3D,OAAO,CAKT;AAED;;;;;GAKG;AACH,wBAAgB,YAAY,CAC1B,MAAM,EAAE,MAAM,IAAI,CAAC,WAAW,EAAE,MAAM,CAAC,GAAG,IAAI,EAC9C,IAAI,EAAE,CAAC,MAAM,EAAE,QAAQ,GAAG,SAAS,KAAK,IAAI,GAC3C,MAAM,IAAI,CAuBZ"}
package/src/tui/runner.ts DELETED
@@ -1,256 +0,0 @@
1
- import { randomUUID } from "node:crypto"
2
- import { homedir, tmpdir } from "node:os"
3
- import { dirname, join } from "node:path"
4
- import { ComputerRunner } from "@sixb/agent"
5
- import {
6
- type GetAgentThreadResponses,
7
- getAgentRun,
8
- getAgentThread,
9
- holdAgentComputerSession,
10
- releaseAgentComputerSession,
11
- } from "@sixb/client"
12
- import type { ConversationAgentRunRecord } from "@sixb/core/storage"
13
- import { LocalSandboxFactory } from "@sixb/sandboxes-local"
14
- import { resolveConfigPath } from "../lib/profiles"
15
- import { thisComputer, thisComputerId } from "./computer"
16
- import type { Connection } from "./connection"
17
-
18
- /** How long a closed terminal waits for a turn running here to record its end. */
19
- const HANG_UP_WAIT_MS = 10_000
20
- /** How often an open `sixb` renews its session, which lapses a minute after its last renewal. */
21
- const SESSION_RENEW_MS = 20_000
22
-
23
- /**
24
- * What the agent's commands never read on this computer, whatever the folder: the CLI's own
25
- * sign-in, and the credentials SSH and AWS keep.
26
- */
27
- export function deniedPaths(): readonly string[] {
28
- return [dirname(resolveConfigPath()), join(homedir(), ".ssh"), join(homedir(), ".aws")]
29
- }
30
-
31
- /**
32
- * This computer as a runner: it claims its owner's turns from the project and runs them in the
33
- * folder `sixb` was opened in, one at a time per turn, each until it ends or is stopped. While its
34
- * session is open, the project knows `sixb` is open here, and the turns sent from elsewhere to the
35
- * conversations of this folder run here too.
36
- */
37
- export class LocalRunner {
38
- private readonly runner: ComputerRunner
39
- private readonly running = new Map<
40
- string,
41
- { readonly stop: AbortController; readonly done: Promise<boolean> }
42
- >()
43
- private readonly elsewhereListeners = new Set<(run: ConversationAgentRunRecord) => void>()
44
- private session: { readonly id: string; readonly timer: ReturnType<typeof setInterval> } | null =
45
- null
46
- /** The session's last call: its release follows a renewal, which would open it again. */
47
- private lastCall: Promise<void> = Promise.resolve()
48
-
49
- constructor(
50
- private readonly connection: Connection,
51
- /** The folder `sixb` was opened in: its real path, as the project keeps it. */
52
- readonly folder: string,
53
- private readonly onFailure: (error: unknown) => void
54
- ) {
55
- this.runner = new ComputerRunner({
56
- apiUrl: connection.apiUrl,
57
- authorization: () => connection.authorization(),
58
- computer: thisComputer,
59
- folder,
60
- runFilesRoot: join(tmpdir(), "sixb-agent"),
61
- onFailure,
62
- openSandbox: ({ workingDirectory, runFiles, credential, signal }) =>
63
- new LocalSandboxFactory({
64
- readWritePaths: [runFiles],
65
- denyReadPaths: deniedPaths(),
66
- network: { mode: "all" },
67
- }).create({
68
- ...(workingDirectory === undefined ? {} : { workingDirectory }),
69
- network: { mode: "all" },
70
- requestCredentials: [credential],
71
- signal,
72
- }),
73
- })
74
- }
75
-
76
- /** Hear each turn sent from elsewhere as it starts to run here. Returns the unsubscribe. */
77
- onElsewhere(listener: (run: ConversationAgentRunRecord) => void): () => void {
78
- this.elsewhereListeners.add(listener)
79
- return () => this.elsewhereListeners.delete(listener)
80
- }
81
-
82
- /** Whether this computer runs `runId` now. */
83
- runs(runId: string): boolean {
84
- return this.running.has(runId)
85
- }
86
-
87
- /**
88
- * Claim a queued turn and run it, unless this computer runs it already. Resolves once the turn
89
- * ended here: false when it was not this computer's to run, or could not be claimed.
90
- */
91
- claim(runId: string, onClaimed?: (run: ConversationAgentRunRecord) => void): Promise<boolean> {
92
- const running = this.running.get(runId)
93
- if (running) return running.done
94
- const stop = new AbortController()
95
- const done = this.runner
96
- .runTurn(runId, stop.signal, onClaimed)
97
- .catch((error: unknown) => {
98
- this.onFailure(error)
99
- return false
100
- })
101
- .finally(() => this.running.delete(runId))
102
- this.running.set(runId, { stop, done })
103
- return done
104
- }
105
-
106
- /**
107
- * Hold this `sixb`'s session while it is open: the conversations of this folder read as online,
108
- * and the turns waiting for them are claimed. Idempotent.
109
- */
110
- openSession(): void {
111
- if (this.session) return
112
- const id = `cs_${randomUUID()}`
113
- const hold = async () => {
114
- const { data, error } = await holdAgentComputerSession({
115
- client: this.connection.client,
116
- path: { sessionId: id },
117
- body: { computer: { ...(await thisComputer()), folder: this.folder } },
118
- })
119
- if (error) throw error
120
- // Closed meanwhile, with the setting or by quitting: what waits keeps waiting.
121
- if (this.session?.id !== id) return
122
- for (const runId of data?.waiting ?? []) void this.claimElsewhere(runId)
123
- }
124
- // A missed renewal is retried at the next; the session lasts three of them.
125
- const renew = () => {
126
- this.lastCall = hold().catch((error: unknown) =>
127
- console.error("[SixbCLI] Session renewal failed.", error)
128
- )
129
- }
130
- this.session = { id, timer: setInterval(renew, SESSION_RENEW_MS) }
131
- renew()
132
- }
133
-
134
- /** Close the session: the conversations of this folder read as offline at once. */
135
- async closeSession(): Promise<void> {
136
- const session = this.session
137
- if (session) {
138
- this.session = null
139
- clearInterval(session.timer)
140
- // Whoever closes it next waits for this one, as quitting does after the screen let go.
141
- this.lastCall = this.lastCall
142
- .then(() =>
143
- releaseAgentComputerSession({
144
- client: this.connection.client,
145
- path: { sessionId: session.id },
146
- })
147
- )
148
- .then(
149
- () => {},
150
- () => {}
151
- )
152
- }
153
- await this.lastCall
154
- }
155
-
156
- /**
157
- * Claim a turn sent from elsewhere when this computer runs its conversation: its owner's, on this
158
- * computer and in this folder, and still queued, while the session is open. A running turn is
159
- * another sixb's, or one whose sixb closed, which the API ends interrupted: claiming it again
160
- * would run its commands twice.
161
- */
162
- async claimIfHere(threadId: string, runId?: string): Promise<void> {
163
- if (!this.session || (runId && this.running.has(runId))) return
164
- const { client } = this.connection
165
- const { data: thread } = await getAgentThread({ client, path: { threadId } })
166
- if (!thread || !this.runsHere(thread, await thisComputerId())) return
167
-
168
- const turn = runId ?? thread.activeRunId
169
- if (!turn) return
170
- const { data: run } = await getAgentRun({ client, path: { runId: turn } })
171
- if (run?.status === "queued" && this.session) void this.claimElsewhere(turn)
172
- }
173
-
174
- /** Whether this `sixb` runs `thread`'s turns: its owner's, on this computer, in this folder. */
175
- runsHere(thread: GetAgentThreadResponses[200], computerId: string): boolean {
176
- return (
177
- thread.runsOn === "computer" &&
178
- owns(this.connection, thread) &&
179
- thread.computer?.id === computerId &&
180
- thread.computer.folder === this.folder
181
- )
182
- }
183
-
184
- /** After a stop was asked for: the turn hears it now, not at its next lease renewal. */
185
- hearStop(runId: string): void {
186
- this.runner.renewNow(runId)
187
- }
188
-
189
- /** Whether a turn runs here now. */
190
- get busy(): boolean {
191
- return this.running.size > 0
192
- }
193
-
194
- /**
195
- * Stop every turn this computer runs, each ending interrupted with its end recorded, and close
196
- * the session.
197
- */
198
- async stop(): Promise<void> {
199
- const running = [...this.running.values()]
200
- for (const { stop } of running) stop.abort()
201
- await Promise.allSettled([...running.map(({ done }) => done), this.closeSession()])
202
- await this.runner.drain()
203
- }
204
-
205
- /** A turn this computer already runs joins that run, and is no news. */
206
- private claimElsewhere(runId: string): Promise<boolean> {
207
- return this.claim(runId, (run) => {
208
- for (const listener of this.elsewhereListeners) listener(run)
209
- })
210
- }
211
- }
212
-
213
- /** Whether the person signed in owns `thread`: with sign-in off, the system owns what it starts. */
214
- export function owns(
215
- connection: Pick<Connection, "user">,
216
- thread: Pick<GetAgentThreadResponses[200], "ownerPrincipal">
217
- ): boolean {
218
- const owner = thread.ownerPrincipal
219
- return connection.user
220
- ? owner.type === "user" && owner.id === connection.user.id
221
- : owner.type === "system"
222
- }
223
-
224
- /**
225
- * A closed terminal, or a kill, ends sixb as quitting does: the turns running here stop, each
226
- * ending interrupted with its end recorded, instead of renewing their lease from a process nobody
227
- * sees, and the session closes. Then `exit`, after a bounded wait. Returns the removal of the
228
- * handlers.
229
- */
230
- export function stopOnHangUp(
231
- runner: () => Pick<LocalRunner, "stop"> | null,
232
- exit: (signal: "SIGHUP" | "SIGTERM") => void
233
- ): () => void {
234
- const hangUp = (signal: "SIGHUP" | "SIGTERM") => {
235
- const running = runner()
236
- if (!running) return exit(signal)
237
-
238
- let timer: ReturnType<typeof setTimeout> | undefined
239
- const waited = new Promise<void>((resolve) => {
240
- timer = setTimeout(resolve, HANG_UP_WAIT_MS)
241
- })
242
- void Promise.race([running.stop(), waited]).finally(() => {
243
- clearTimeout(timer)
244
- exit(signal)
245
- })
246
- }
247
-
248
- const onHangUp = () => hangUp("SIGHUP")
249
- const onTerminate = () => hangUp("SIGTERM")
250
- process.on("SIGHUP", onHangUp)
251
- process.on("SIGTERM", onTerminate)
252
- return () => {
253
- process.off("SIGHUP", onHangUp)
254
- process.off("SIGTERM", onTerminate)
255
- }
256
- }
File without changes
File without changes