@sixb/cli 0.2.1 → 0.2.3

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 (121) hide show
  1. package/README.md +25 -22
  2. package/dist/commands/access-token-utils.d.ts.map +1 -1
  3. package/dist/commands/agent.d.ts +4 -1
  4. package/dist/commands/agent.d.ts.map +1 -1
  5. package/dist/commands/api.d.ts.map +1 -1
  6. package/dist/commands/check.d.ts.map +1 -1
  7. package/dist/commands/connect.d.ts +13 -0
  8. package/dist/commands/connect.d.ts.map +1 -0
  9. package/dist/commands/db-migrate.d.ts.map +1 -1
  10. package/dist/commands/db-prepare.d.ts.map +1 -1
  11. package/dist/commands/deploy.d.ts.map +1 -1
  12. package/dist/commands/desktop.d.ts.map +1 -1
  13. package/dist/commands/dev-runner.d.ts.map +1 -1
  14. package/dist/commands/env.d.ts +6 -1
  15. package/dist/commands/env.d.ts.map +1 -1
  16. package/dist/commands/lake-cleanup.d.ts +2 -12
  17. package/dist/commands/lake-cleanup.d.ts.map +1 -1
  18. package/dist/commands/lake-rejected.d.ts +10 -0
  19. package/dist/commands/lake-rejected.d.ts.map +1 -0
  20. package/dist/commands/orchestrator.d.ts.map +1 -1
  21. package/dist/commands/scheduler.d.ts +2 -5
  22. package/dist/commands/scheduler.d.ts.map +1 -1
  23. package/dist/commands/worker-group.d.ts.map +1 -1
  24. package/dist/lib/command-line.d.ts +22 -7
  25. package/dist/lib/command-line.d.ts.map +1 -1
  26. package/dist/{tui → lib}/connection.d.ts +11 -1
  27. package/dist/{tui → lib}/connection.d.ts.map +1 -1
  28. package/dist/lib/deploy-release.d.ts +7 -1
  29. package/dist/lib/deploy-release.d.ts.map +1 -1
  30. package/dist/lib/desktop.d.ts +4 -0
  31. package/dist/lib/desktop.d.ts.map +1 -1
  32. package/dist/lib/dev-supervisor.d.ts.map +1 -1
  33. package/dist/lib/duration.d.ts +3 -0
  34. package/dist/lib/duration.d.ts.map +1 -0
  35. package/dist/lib/loadSixb.d.ts.map +1 -1
  36. package/dist/lib/production-roles.d.ts +0 -4
  37. package/dist/lib/production-roles.d.ts.map +1 -1
  38. package/dist/lib/profiles.d.ts +5 -0
  39. package/dist/lib/profiles.d.ts.map +1 -1
  40. package/dist/lib/runtime.d.ts +7 -9
  41. package/dist/lib/runtime.d.ts.map +1 -1
  42. package/dist/lib/worker-concurrency.d.ts.map +1 -1
  43. package/dist/lib/worker-registry.d.ts +4 -1
  44. package/dist/lib/worker-registry.d.ts.map +1 -1
  45. package/dist/runner/allowed-folders.d.ts +17 -0
  46. package/dist/runner/allowed-folders.d.ts.map +1 -0
  47. package/dist/runner/computer-connection.d.ts +70 -0
  48. package/dist/runner/computer-connection.d.ts.map +1 -0
  49. package/dist/runner/computer.d.ts.map +1 -0
  50. package/dist/runner/desktop-runner-main.d.ts +2 -0
  51. package/dist/runner/desktop-runner-main.d.ts.map +1 -0
  52. package/dist/runner/desktop-runner.d.ts +43 -0
  53. package/dist/runner/desktop-runner.d.ts.map +1 -0
  54. package/dist/runner/keep-awake.d.ts +11 -0
  55. package/dist/runner/keep-awake.d.ts.map +1 -0
  56. package/dist/runner/local-runner.d.ts +131 -0
  57. package/dist/runner/local-runner.d.ts.map +1 -0
  58. package/dist/tui/app.d.ts +2 -2
  59. package/dist/tui/app.d.ts.map +1 -1
  60. package/dist/tui/format.d.ts +29 -0
  61. package/dist/tui/format.d.ts.map +1 -1
  62. package/dist/tui/index.d.ts.map +1 -1
  63. package/dist/tui/settings.d.ts +5 -8
  64. package/dist/tui/settings.d.ts.map +1 -1
  65. package/dist/ui/deploy-screens.d.ts +4 -2
  66. package/dist/ui/deploy-screens.d.ts.map +1 -1
  67. package/dist/ui/env-screens.d.ts +14 -1
  68. package/dist/ui/env-screens.d.ts.map +1 -1
  69. package/dist/ui/screens.d.ts +5 -11
  70. package/dist/ui/screens.d.ts.map +1 -1
  71. package/package.json +21 -17
  72. package/src/commands/access-token-utils.ts +2 -20
  73. package/src/commands/agent.ts +122 -39
  74. package/src/commands/api.ts +7 -0
  75. package/src/commands/check.ts +75 -1
  76. package/src/commands/connect.ts +197 -0
  77. package/src/commands/db-migrate.ts +1 -0
  78. package/src/commands/db-prepare.ts +1 -0
  79. package/src/commands/deploy.ts +15 -3
  80. package/src/commands/desktop.ts +2 -1
  81. package/src/commands/dev-runner.ts +5 -0
  82. package/src/commands/env.ts +99 -20
  83. package/src/commands/lake-cleanup.ts +25 -48
  84. package/src/commands/lake-rejected.ts +36 -0
  85. package/src/commands/orchestrator.ts +2 -7
  86. package/src/commands/scheduler.ts +11 -61
  87. package/src/commands/worker-group.ts +6 -3
  88. package/src/index.tsx +23 -4
  89. package/src/lib/command-line.ts +47 -15
  90. package/src/{tui → lib}/connection.ts +64 -17
  91. package/src/lib/deploy-release.ts +42 -2
  92. package/src/lib/desktop.ts +8 -1
  93. package/src/lib/dev-supervisor.ts +7 -2
  94. package/src/lib/duration.ts +11 -0
  95. package/src/lib/loadSixb.ts +3 -4
  96. package/src/lib/production-roles.ts +0 -1
  97. package/src/lib/profiles.ts +15 -1
  98. package/src/lib/runtime.ts +63 -43
  99. package/src/lib/shareable-providers.ts +2 -2
  100. package/src/lib/storage-migration.ts +1 -0
  101. package/src/lib/worker-concurrency.ts +1 -0
  102. package/src/lib/worker-registry.ts +36 -1
  103. package/src/runner/allowed-folders.ts +126 -0
  104. package/src/runner/computer-connection.ts +184 -0
  105. package/src/runner/desktop-runner-main.ts +9 -0
  106. package/src/runner/desktop-runner.ts +217 -0
  107. package/src/runner/keep-awake.ts +50 -0
  108. package/src/runner/local-runner.ts +427 -0
  109. package/src/tui/app.tsx +168 -12
  110. package/src/tui/format.ts +213 -7
  111. package/src/tui/index.tsx +14 -13
  112. package/src/tui/settings.ts +12 -44
  113. package/src/ui/deploy-screens.ts +8 -1
  114. package/src/ui/env-screens.ts +39 -5
  115. package/src/ui/screens.ts +21 -20
  116. package/dist/tui/computer.d.ts.map +0 -1
  117. package/dist/tui/runner.d.ts +0 -75
  118. package/dist/tui/runner.d.ts.map +0 -1
  119. package/src/tui/runner.ts +0 -256
  120. /package/dist/{tui → runner}/computer.d.ts +0 -0
  121. /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
  )
@@ -20,15 +20,18 @@ import {
20
20
  section,
21
21
  stack,
22
22
  table,
23
+ warnings as warningLines,
23
24
  } from "./layout"
24
25
  import { glyph, tone } from "./theme"
25
26
 
26
27
  export function deployReleaseView({
27
28
  release,
28
29
  configPath,
30
+ warnings = [],
29
31
  }: {
30
32
  release: DeployRelease
31
33
  configPath: string
34
+ warnings?: readonly string[]
32
35
  }): string {
33
36
  const steps = [
34
37
  ...(release.steps.env ? [{ label: "env", commands: [release.steps.env] }] : []),
@@ -93,6 +96,7 @@ export function deployReleaseView({
93
96
  origins.size > 0 ? tone.muted("plus the public origins above") : null
94
97
  )
95
98
  ),
99
+ warningLines(warnings),
96
100
  headline("idle", "Nothing was deployed", "--json prints the full release")
97
101
  )
98
102
  }
@@ -107,11 +111,13 @@ export function deployCompleteView({
107
111
  release,
108
112
  seconds,
109
113
  keptEnv = false,
114
+ warnings = [],
110
115
  }: {
111
116
  release: DeployRelease
112
117
  seconds?: number
113
118
  /** The deploy couldn't update the server's `.env`, so this release runs on its current values. */
114
119
  keptEnv?: boolean
120
+ warnings?: readonly string[]
115
121
  }): string {
116
122
  const urls = release.services.flatMap((service) =>
117
123
  service.http ? [{ label: service.name, value: service.http.publicOrigin }] : []
@@ -129,7 +135,8 @@ export function deployCompleteView({
129
135
  "This release runs on the server's current .env, not on the latest values. Deploy again to update them.",
130
136
  tone.muted
131
137
  )
132
- : null
138
+ : null,
139
+ warningLines(warnings)
133
140
  )
134
141
  }
135
142
 
@@ -27,15 +27,49 @@ export function envSetView(input: {
27
27
  )
28
28
  }
29
29
 
30
+ /** What `init` did with `sixb.env.ts`: wrote names into it, left it to the author, or had none to add. */
31
+ export type EnvInitConfig =
32
+ | { readonly kind: "written"; readonly names: number }
33
+ | { readonly kind: "paste"; readonly names: number; readonly lines: readonly string[] }
34
+ | { readonly kind: "unchanged" }
35
+
30
36
  export function envInitView(input: {
31
- readonly uploaded: readonly { readonly env: EnvName; readonly count: number }[]
32
- readonly names: number
37
+ /** Per environment: how many values were sent, and how many it had already. */
38
+ readonly uploaded: readonly {
39
+ readonly env: EnvName
40
+ readonly count: number
41
+ readonly already: number
42
+ }[]
43
+ readonly config: EnvInitConfig
33
44
  }): string {
34
- const uploaded = input.uploaded.map(({ env, count }) => `${plural(count, "variable")} to ${env}`)
45
+ const sent = input.uploaded.filter(({ count }) => count > 0)
46
+ const had = input.uploaded.filter(({ already }) => already > 0)
47
+ const { config } = input
35
48
  return screen(
36
49
  stack(
37
- headline("ok", `Uploaded ${uploaded.join(" and ")}`),
38
- headline("ok", `Wrote sixb.env.ts with ${plural(input.names, "name")}`)
50
+ sent.length > 0
51
+ ? headline(
52
+ "ok",
53
+ `Uploaded ${sent.map(({ env, count }) => `${plural(count, "variable")} to ${env}`).join(" and ")}`
54
+ )
55
+ : headline("ok", "Nothing to upload"),
56
+ had.length > 0
57
+ ? tone.muted(
58
+ `Already there: ${had.map(({ env, already }) => `${already} in ${env}`).join(", ")}`
59
+ )
60
+ : null,
61
+ config.kind === "written"
62
+ ? headline("ok", `Wrote sixb.env.ts with ${plural(config.names, "name")}`)
63
+ : null,
64
+ config.kind === "paste"
65
+ ? stack(
66
+ headline("warn", `Add ${plural(config.names, "name")} to \`vars\` in sixb.env.ts`),
67
+ tone.muted(
68
+ "It isn't an empty `vars: {}`, so it was left alone. A first guess at each:"
69
+ ),
70
+ config.lines.join("\n")
71
+ )
72
+ : null
39
73
  )
40
74
  )
41
75
  }
package/src/ui/screens.ts CHANGED
@@ -1,3 +1,4 @@
1
+ import type { LakeRetentionReport } from "@sixb/core/lake-storage"
1
2
  import {
2
3
  CLI_EXAMPLES,
3
4
  type CliHelp,
@@ -430,39 +431,39 @@ export function lakeCheckView({
430
431
  return screen(headline("ok", "Lake definitions compatible", projectId), warningLines(warnings))
431
432
  }
432
433
 
433
- export interface LakeCleanupReport {
434
- readonly dryRun: boolean
435
- readonly expireOlderThan: string
436
- readonly deleteOlderThan: string
437
- readonly snapshots: number
438
- readonly keptSnapshots?: number
439
- readonly oldFiles: number
440
- readonly orphanedFiles: number
441
- }
442
-
443
434
  export function lakeCleanupView({
444
435
  projectId,
436
+ keepVersionsFor,
437
+ deleteFilesAfter,
445
438
  report,
446
439
  }: {
447
440
  projectId: string
448
- report: LakeCleanupReport
441
+ keepVersionsFor: string
442
+ deleteFilesAfter: string
443
+ report: LakeRetentionReport
449
444
  }): string {
445
+ // A dry run measures one pass: when more remain, what the run would clean is more than it counts.
446
+ const measuredOnePass = report.dryRun && report.hasMore
447
+ const atLeast = (count: number) => (measuredOnePass ? `${count}+` : String(count))
448
+
450
449
  return screen(
451
450
  header(report.dryRun ? "lake cleanup --dry-run" : "lake cleanup", projectId),
452
451
  rows([
453
- { label: "Expire older than", value: report.expireOlderThan },
454
- { label: "Delete older than", value: report.deleteOlderThan },
455
- { label: "Snapshots", value: String(report.snapshots) },
456
- ...(report.keptSnapshots === undefined
457
- ? []
458
- : [{ label: "Kept snapshots", value: String(report.keptSnapshots) }]),
459
- { label: "Old files", value: String(report.oldFiles) },
460
- { label: "Orphaned files", value: String(report.orphanedFiles) },
452
+ { label: "Keep versions for", value: keepVersionsFor },
453
+ { label: "Delete files after", value: deleteFilesAfter },
454
+ { label: "Expired versions", value: atLeast(report.expiredVersions) },
455
+ { label: "Kept versions", value: String(report.keptVersions) },
456
+ { label: "Deleted files", value: atLeast(report.deletedFiles) },
457
+ { label: "Orphaned files", value: atLeast(report.orphanedFiles) },
461
458
  ]),
462
459
  headline(
463
460
  "ok",
464
461
  report.dryRun ? "Lake cleanup dry run complete" : "Lake cleanup complete",
465
- report.dryRun ? "nothing was deleted" : undefined
462
+ report.dryRun
463
+ ? measuredOnePass
464
+ ? "nothing was deleted; one pass measured, more remain"
465
+ : "nothing was deleted"
466
+ : undefined
466
467
  )
467
468
  )
468
469
  }
@@ -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