@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.
- package/dist/commands/agent.d.ts +4 -1
- package/dist/commands/agent.d.ts.map +1 -1
- package/dist/commands/connect.d.ts +13 -0
- package/dist/commands/connect.d.ts.map +1 -0
- package/dist/commands/db-migrate.d.ts.map +1 -1
- package/dist/commands/db-prepare.d.ts.map +1 -1
- package/dist/commands/desktop.d.ts.map +1 -1
- package/dist/lib/command-line.d.ts +11 -1
- package/dist/lib/command-line.d.ts.map +1 -1
- package/dist/{tui → lib}/connection.d.ts +11 -1
- package/dist/{tui → lib}/connection.d.ts.map +1 -1
- package/dist/lib/desktop.d.ts +4 -0
- package/dist/lib/desktop.d.ts.map +1 -1
- package/dist/lib/dev-supervisor.d.ts.map +1 -1
- package/dist/lib/profiles.d.ts +5 -0
- package/dist/lib/profiles.d.ts.map +1 -1
- package/dist/lib/runtime.d.ts.map +1 -1
- package/dist/runner/allowed-folders.d.ts +17 -0
- package/dist/runner/allowed-folders.d.ts.map +1 -0
- package/dist/runner/computer-connection.d.ts +70 -0
- package/dist/runner/computer-connection.d.ts.map +1 -0
- package/dist/runner/computer.d.ts.map +1 -0
- package/dist/runner/desktop-runner-main.d.ts +2 -0
- package/dist/runner/desktop-runner-main.d.ts.map +1 -0
- package/dist/runner/desktop-runner.d.ts +43 -0
- package/dist/runner/desktop-runner.d.ts.map +1 -0
- package/dist/runner/keep-awake.d.ts +11 -0
- package/dist/runner/keep-awake.d.ts.map +1 -0
- package/dist/runner/local-runner.d.ts +131 -0
- package/dist/runner/local-runner.d.ts.map +1 -0
- package/dist/tui/app.d.ts +2 -2
- package/dist/tui/app.d.ts.map +1 -1
- package/dist/tui/format.d.ts +29 -0
- package/dist/tui/format.d.ts.map +1 -1
- package/dist/tui/index.d.ts.map +1 -1
- package/dist/tui/settings.d.ts +5 -8
- package/dist/tui/settings.d.ts.map +1 -1
- package/package.json +17 -17
- package/src/commands/agent.ts +122 -39
- package/src/commands/connect.ts +197 -0
- package/src/commands/db-migrate.ts +1 -0
- package/src/commands/db-prepare.ts +1 -0
- package/src/commands/desktop.ts +2 -1
- package/src/index.tsx +13 -0
- package/src/lib/command-line.ts +22 -3
- package/src/{tui → lib}/connection.ts +64 -17
- package/src/lib/desktop.ts +8 -1
- package/src/lib/dev-supervisor.ts +7 -2
- package/src/lib/profiles.ts +15 -1
- package/src/lib/runtime.ts +1 -0
- package/src/lib/storage-migration.ts +1 -0
- package/src/runner/allowed-folders.ts +126 -0
- package/src/runner/computer-connection.ts +184 -0
- package/src/runner/desktop-runner-main.ts +9 -0
- package/src/runner/desktop-runner.ts +217 -0
- package/src/runner/keep-awake.ts +50 -0
- package/src/runner/local-runner.ts +427 -0
- package/src/tui/app.tsx +168 -12
- package/src/tui/format.ts +203 -6
- package/src/tui/index.tsx +14 -13
- package/src/tui/settings.ts +12 -44
- package/dist/tui/computer.d.ts.map +0 -1
- package/dist/tui/runner.d.ts +0 -75
- package/dist/tui/runner.d.ts.map +0 -1
- package/src/tui/runner.ts +0 -256
- /package/dist/{tui → runner}/computer.d.ts +0 -0
- /package/src/{tui → runner}/computer.ts +0 -0
package/src/lib/command-line.ts
CHANGED
|
@@ -119,6 +119,16 @@ export const CLI_OPTION_DEFINITIONS = {
|
|
|
119
119
|
summary: "What this turn may do without asking (default: your mode in the conversation)",
|
|
120
120
|
kind: "string",
|
|
121
121
|
},
|
|
122
|
+
detach: {
|
|
123
|
+
syntax: "--detach",
|
|
124
|
+
summary: "Send the message and exit, without following the turn",
|
|
125
|
+
kind: "boolean",
|
|
126
|
+
},
|
|
127
|
+
yes: {
|
|
128
|
+
syntax: "--yes",
|
|
129
|
+
summary: "Allow the folders named without asking",
|
|
130
|
+
kind: "boolean",
|
|
131
|
+
},
|
|
122
132
|
outdir: { syntax: "--outdir <path>", summary: "Build output directory", kind: "string" },
|
|
123
133
|
ref: {
|
|
124
134
|
syntax: "--ref <ref>",
|
|
@@ -191,6 +201,7 @@ export const CLI_OPTION_DEFINITIONS = {
|
|
|
191
201
|
export type CliOptionName = keyof typeof CLI_OPTION_DEFINITIONS
|
|
192
202
|
export type LocalCommandId =
|
|
193
203
|
| "agent"
|
|
204
|
+
| "connect"
|
|
194
205
|
| "dev"
|
|
195
206
|
| "api"
|
|
196
207
|
| "app"
|
|
@@ -352,14 +363,21 @@ const commandTree: readonly CommandNode[] = [
|
|
|
352
363
|
options: [...CONNECTION_OPTIONS, "json"],
|
|
353
364
|
}),
|
|
354
365
|
command("agent", "Ask the agent; it works in this folder", {
|
|
355
|
-
usage:
|
|
366
|
+
usage:
|
|
367
|
+
'sixb agent "<message>" [--thread <id>] [--cloud] [--approval-mode <mode>] [--detach] [--json]',
|
|
356
368
|
// No --token: a command the agent runs could read it from this one's arguments. A token comes
|
|
357
369
|
// from a profile or SIXB_API_TOKEN.
|
|
358
|
-
options: ["api-url", "profile", "thread", "cloud", "approval-mode", "json"],
|
|
370
|
+
options: ["api-url", "profile", "thread", "cloud", "approval-mode", "detach", "json"],
|
|
359
371
|
// The message, quoted or not; standard input when there is none.
|
|
360
372
|
maximumPositionals: Number.POSITIVE_INFINITY,
|
|
361
373
|
rootHelpLabel: 'agent "<message>"',
|
|
362
374
|
}),
|
|
375
|
+
command("connect", "Run messages from the web in folders on this computer", {
|
|
376
|
+
usage: "sixb connect [folder...] [--yes] [--json]",
|
|
377
|
+
options: ["api-url", "profile", "yes", "json"],
|
|
378
|
+
maximumPositionals: Number.POSITIVE_INFINITY,
|
|
379
|
+
rootHelpLabel: "connect [folder...]",
|
|
380
|
+
}),
|
|
363
381
|
{
|
|
364
382
|
name: "profile",
|
|
365
383
|
summary: "List, show, or switch saved profiles",
|
|
@@ -720,7 +738,7 @@ const ROOT_HELP_GROUP_COMMANDS: readonly {
|
|
|
720
738
|
/** Listed by name only: each has its own help. */
|
|
721
739
|
readonly compact?: boolean
|
|
722
740
|
}[] = [
|
|
723
|
-
{ title: "Agent", names: ["agent"] },
|
|
741
|
+
{ title: "Agent", names: ["agent", "connect"] },
|
|
724
742
|
{ title: "Develop", names: ["init", "dev", "env", "check", "typegen", "build"] },
|
|
725
743
|
{ title: "Deploy", names: ["deploy", "desktop"] },
|
|
726
744
|
{
|
|
@@ -813,6 +831,7 @@ export function wantsManagementJson(args: readonly string[]): boolean {
|
|
|
813
831
|
"service-account",
|
|
814
832
|
"deploy",
|
|
815
833
|
"agent",
|
|
834
|
+
"connect",
|
|
816
835
|
].includes(args[0] ?? "") &&
|
|
817
836
|
args.some((argument) => argument === "--json" || argument.startsWith("--json="))
|
|
818
837
|
)
|
|
@@ -8,13 +8,17 @@ import {
|
|
|
8
8
|
type SixbSessionTokens,
|
|
9
9
|
startSixbDeviceLogin,
|
|
10
10
|
} from "@sixb/client"
|
|
11
|
-
import { normalizeApiUrl } from "
|
|
11
|
+
import { normalizeApiUrl } from "./api-client"
|
|
12
|
+
import { errorMessage } from "./errors"
|
|
12
13
|
import {
|
|
14
|
+
ProfileUnansweredError,
|
|
13
15
|
profileSessionStore,
|
|
14
16
|
type ResolvedProfile,
|
|
17
|
+
readConfig,
|
|
15
18
|
resolveProfile,
|
|
19
|
+
type SixbConfigFile,
|
|
16
20
|
updateConfig,
|
|
17
|
-
} from "
|
|
21
|
+
} from "./profiles"
|
|
18
22
|
|
|
19
23
|
/** A project the app talks to, as the person signed in to it. */
|
|
20
24
|
export interface Connection {
|
|
@@ -45,7 +49,10 @@ export async function connect(input: {
|
|
|
45
49
|
try {
|
|
46
50
|
resolved = await resolveProfile(input)
|
|
47
51
|
} catch (error) {
|
|
48
|
-
|
|
52
|
+
if (error instanceof ProfileUnansweredError) {
|
|
53
|
+
return { apiUrl: error.apiUrl, reason: "unreachable", message: error.message }
|
|
54
|
+
}
|
|
55
|
+
return { apiUrl: input.apiUrl ?? "", reason: "session-ended", message: errorMessage(error) }
|
|
49
56
|
}
|
|
50
57
|
const profile = resolved.profile
|
|
51
58
|
const viaSession = resolved.tokenSource === "session" && profile !== undefined
|
|
@@ -101,11 +108,24 @@ export async function connect(input: {
|
|
|
101
108
|
apiUrl: resolved.apiUrl,
|
|
102
109
|
...(profile === undefined ? {} : { profile }),
|
|
103
110
|
reason: status === 401 || status === 403 ? "signed-out" : "unreachable",
|
|
104
|
-
message:
|
|
111
|
+
message: errorMessage(error),
|
|
105
112
|
}
|
|
106
113
|
}
|
|
107
114
|
}
|
|
108
115
|
|
|
116
|
+
/**
|
|
117
|
+
* The profiles signed in to `apiUrl`: the CLI's own sign-in there serves a program beside it. The one
|
|
118
|
+
* `sixb` is using comes first.
|
|
119
|
+
*/
|
|
120
|
+
export async function profilesSignedInTo(apiUrl: string): Promise<readonly string[]> {
|
|
121
|
+
const baseUrl = normalizeApiUrl(apiUrl)
|
|
122
|
+
const { profiles, currentProfile } = await readConfig()
|
|
123
|
+
return Object.entries(profiles)
|
|
124
|
+
.filter(([, profile]) => profile.apiUrl === baseUrl && (profile.session || profile.token))
|
|
125
|
+
.map(([name]) => name)
|
|
126
|
+
.sort((a, b) => Number(b === currentProfile) - Number(a === currentProfile))
|
|
127
|
+
}
|
|
128
|
+
|
|
109
129
|
/** A sign-in in progress: show the code, open the page, then wait for the person to approve it. */
|
|
110
130
|
export interface PendingSignIn {
|
|
111
131
|
readonly apiUrl: string
|
|
@@ -116,11 +136,49 @@ export interface PendingSignIn {
|
|
|
116
136
|
|
|
117
137
|
/**
|
|
118
138
|
* Sign this computer in to `apiUrl` with the device flow, as `sixb login` does, and keep the
|
|
119
|
-
* session on a profile named after the project.
|
|
139
|
+
* session on a profile named after the project, which `sixb` then uses.
|
|
120
140
|
*/
|
|
121
141
|
export async function startSignIn(apiUrl: string): Promise<PendingSignIn> {
|
|
122
142
|
const baseUrl = normalizeApiUrl(apiUrl)
|
|
123
143
|
const login = await startSixbDeviceLogin({ baseUrl, clientName: `sixb on ${hostname()}` })
|
|
144
|
+
return pendingSignIn(baseUrl, login, (config, project, session) => ({
|
|
145
|
+
version: 1,
|
|
146
|
+
currentProfile: project,
|
|
147
|
+
profiles: {
|
|
148
|
+
...config.profiles,
|
|
149
|
+
[project]: { apiUrl: baseUrl, projectId: project, session },
|
|
150
|
+
},
|
|
151
|
+
}))
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
/**
|
|
155
|
+
* As `startSignIn`, for a program beside `sixb` rather than `sixb` itself: what `sixb` is using stays
|
|
156
|
+
* as it was, and so does a profile of the same name for another address.
|
|
157
|
+
*/
|
|
158
|
+
export async function startSignInBeside(
|
|
159
|
+
apiUrl: string,
|
|
160
|
+
clientName: string
|
|
161
|
+
): Promise<PendingSignIn> {
|
|
162
|
+
const baseUrl = normalizeApiUrl(apiUrl)
|
|
163
|
+
const login = await startSixbDeviceLogin({ baseUrl, clientName })
|
|
164
|
+
return pendingSignIn(baseUrl, login, (config, project, session) => {
|
|
165
|
+
const taken = config.profiles[project]
|
|
166
|
+
const name =
|
|
167
|
+
taken && taken.apiUrl !== baseUrl
|
|
168
|
+
? `${project}-${new URL(baseUrl).host.replace(":", "-")}`
|
|
169
|
+
: project
|
|
170
|
+
return {
|
|
171
|
+
...config,
|
|
172
|
+
profiles: { ...config.profiles, [name]: { apiUrl: baseUrl, projectId: project, session } },
|
|
173
|
+
}
|
|
174
|
+
})
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
function pendingSignIn(
|
|
178
|
+
baseUrl: string,
|
|
179
|
+
login: Awaited<ReturnType<typeof startSixbDeviceLogin>>,
|
|
180
|
+
keep: (config: SixbConfigFile, project: string, session: SixbSessionTokens) => SixbConfigFile
|
|
181
|
+
): PendingSignIn {
|
|
124
182
|
return {
|
|
125
183
|
apiUrl: baseUrl,
|
|
126
184
|
userCode: login.userCode,
|
|
@@ -132,18 +190,7 @@ export async function startSignIn(apiUrl: string): Promise<PendingSignIn> {
|
|
|
132
190
|
auth: { kind: "bearer", token: session.accessToken },
|
|
133
191
|
})
|
|
134
192
|
const { data: project } = await getProjectInfo({ client, throwOnError: true })
|
|
135
|
-
await updateConfig((config) => (
|
|
136
|
-
version: 1,
|
|
137
|
-
currentProfile: project.id,
|
|
138
|
-
profiles: {
|
|
139
|
-
...config.profiles,
|
|
140
|
-
[project.id]: { apiUrl: baseUrl, projectId: project.id, session },
|
|
141
|
-
},
|
|
142
|
-
}))
|
|
193
|
+
await updateConfig((config) => keep(config, project.id, session))
|
|
143
194
|
},
|
|
144
195
|
}
|
|
145
196
|
}
|
|
146
|
-
|
|
147
|
-
function errorText(error: unknown): string {
|
|
148
|
-
return error instanceof Error ? error.message : String(error)
|
|
149
|
-
}
|
package/src/lib/desktop.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { pathToFileURL } from "node:url"
|
|
1
|
+
import { fileURLToPath, pathToFileURL } from "node:url"
|
|
2
2
|
import { SixbCliError } from "./errors"
|
|
3
3
|
|
|
4
4
|
export interface DesktopAppOptions {
|
|
@@ -6,8 +6,15 @@ export interface DesktopAppOptions {
|
|
|
6
6
|
/** Where the app is served. The desktop app opens it and takes its name and icon from it. */
|
|
7
7
|
readonly appUrl: string
|
|
8
8
|
readonly apiOrigin: string
|
|
9
|
+
/** What the app compiles to run the agent on this computer. */
|
|
10
|
+
readonly runnerEntry: string
|
|
9
11
|
}
|
|
10
12
|
|
|
13
|
+
/** From the CLI's `src`, which ships: `@sixb/desktop` compiles it into the app. */
|
|
14
|
+
export const DESKTOP_RUNNER_ENTRY = fileURLToPath(
|
|
15
|
+
new URL("../runner/desktop-runner-main.ts", import.meta.url)
|
|
16
|
+
)
|
|
17
|
+
|
|
11
18
|
/**
|
|
12
19
|
* What the CLI calls on `@sixb/desktop`. Declared here, not imported: the CLI does not depend on
|
|
13
20
|
* the package, and `desktop.test.ts` holds the two together.
|
|
@@ -2,7 +2,7 @@ import { spawn } from "node:child_process"
|
|
|
2
2
|
import { dirname, resolve } from "node:path"
|
|
3
3
|
import type { DevOptions } from "../commands/dev-runner"
|
|
4
4
|
import { canRunLive } from "../ui/live/can-run-live"
|
|
5
|
-
import { loadDesktop } from "./desktop"
|
|
5
|
+
import { DESKTOP_RUNNER_ENTRY, loadDesktop } from "./desktop"
|
|
6
6
|
import { DEV_UI_ENV, type DevChildMessage } from "./dev-messages"
|
|
7
7
|
import { watchDevSource } from "./dev-watch"
|
|
8
8
|
import { errorMessage } from "./errors"
|
|
@@ -175,7 +175,12 @@ export async function runDevSupervisor(options: DevOptions): Promise<void> {
|
|
|
175
175
|
const app = servedApp(message)
|
|
176
176
|
if (desktop && app && !desktopWindow) {
|
|
177
177
|
desktopWindow = desktop
|
|
178
|
-
.openDesktopApp({
|
|
178
|
+
.openDesktopApp({
|
|
179
|
+
projectRoot: root,
|
|
180
|
+
runnerEntry: DESKTOP_RUNNER_ENTRY,
|
|
181
|
+
appUrl: app.url,
|
|
182
|
+
apiOrigin: app.apiOrigin,
|
|
183
|
+
})
|
|
179
184
|
.catch((error: unknown) => {
|
|
180
185
|
reporter.error(`Could not open the desktop window: ${errorMessage(error)}`)
|
|
181
186
|
// The next generation to come up tries again.
|
package/src/lib/profiles.ts
CHANGED
|
@@ -9,6 +9,7 @@ import {
|
|
|
9
9
|
type SixbSessionTokens,
|
|
10
10
|
} from "@sixb/client"
|
|
11
11
|
import { normalizeApiUrl } from "./api-client"
|
|
12
|
+
import { errorMessage } from "./errors"
|
|
12
13
|
|
|
13
14
|
const CONFIG_DIRECTORY_MODE = 0o700
|
|
14
15
|
const CONFIG_FILE_MODE = 0o600
|
|
@@ -188,6 +189,17 @@ export function assertProfileName(name: string): void {
|
|
|
188
189
|
}
|
|
189
190
|
}
|
|
190
191
|
|
|
192
|
+
/** Its sign-in couldn't be refreshed for want of an answer, which says nothing about the sign-in. */
|
|
193
|
+
export class ProfileUnansweredError extends Error {
|
|
194
|
+
constructor(
|
|
195
|
+
readonly apiUrl: string,
|
|
196
|
+
cause: unknown
|
|
197
|
+
) {
|
|
198
|
+
super(errorMessage(cause), { cause })
|
|
199
|
+
this.name = "ProfileUnansweredError"
|
|
200
|
+
}
|
|
201
|
+
}
|
|
202
|
+
|
|
191
203
|
async function resolvedStoredProfile(
|
|
192
204
|
stored: SixbProfile,
|
|
193
205
|
profile: string,
|
|
@@ -203,7 +215,9 @@ async function resolvedStoredProfile(
|
|
|
203
215
|
baseUrl: stored.apiUrl,
|
|
204
216
|
store: profileSessionStore(profile, options),
|
|
205
217
|
}).catch((error: unknown) => {
|
|
206
|
-
if (!(error instanceof SixbSessionEndedError))
|
|
218
|
+
if (!(error instanceof SixbSessionEndedError)) {
|
|
219
|
+
throw new ProfileUnansweredError(stored.apiUrl, error)
|
|
220
|
+
}
|
|
207
221
|
return null
|
|
208
222
|
})
|
|
209
223
|
if (!token) {
|
package/src/lib/runtime.ts
CHANGED
|
@@ -97,6 +97,7 @@ async function runMigration(sixb: LoadedSixbHost, role: StorageSchemaRole) {
|
|
|
97
97
|
return await migrateStorage(sixb.storage, {
|
|
98
98
|
projectId: sixb.id,
|
|
99
99
|
ontology: sixb.definitions.ontology,
|
|
100
|
+
security: sixb.definitions.security,
|
|
100
101
|
})
|
|
101
102
|
} catch (error) {
|
|
102
103
|
throw isBusyDatabaseError(error) ? concurrentMigrationError(error, role) : error
|
|
@@ -0,0 +1,126 @@
|
|
|
1
|
+
import { randomUUID } from "node:crypto"
|
|
2
|
+
import { watch } from "node:fs"
|
|
3
|
+
import { mkdir, readFile, rename, writeFile } from "node:fs/promises"
|
|
4
|
+
import { basename, dirname, join } from "node:path"
|
|
5
|
+
import type { Connection } from "../lib/connection"
|
|
6
|
+
import { resolveConfigPath } from "../lib/profiles"
|
|
7
|
+
|
|
8
|
+
// The folders chosen on this computer, for each project. A conversation's folder is only text on
|
|
9
|
+
// the server, so a stolen web sign-in could name any folder: nothing sent from elsewhere runs in one
|
|
10
|
+
// that isn't listed here for that project, and choosing a folder for one project says nothing about
|
|
11
|
+
// another. Kept beside the CLI's sign-in, where the agent's own commands can't reach it.
|
|
12
|
+
|
|
13
|
+
const ALLOWED_FOLDERS_FILE = () => join(dirname(resolveConfigPath()), "allowed-folders.json")
|
|
14
|
+
|
|
15
|
+
/** The project a list is for: `connect` names it. */
|
|
16
|
+
export type AllowedFor = Pick<Connection, "apiUrl" | "project">
|
|
17
|
+
|
|
18
|
+
/** Its address as well as its id: a project reports its own id, and two can share one. */
|
|
19
|
+
function keyOf({ apiUrl, project }: AllowedFor): string {
|
|
20
|
+
return `${project.id} at ${apiUrl}`
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
type StoredFolders = Readonly<Record<string, readonly string[]>>
|
|
24
|
+
|
|
25
|
+
async function readStored(): Promise<StoredFolders> {
|
|
26
|
+
const text = await readFile(ALLOWED_FOLDERS_FILE(), "utf8").catch((error: unknown) => {
|
|
27
|
+
if ((error as NodeJS.ErrnoException).code === "ENOENT") return "{}"
|
|
28
|
+
throw error
|
|
29
|
+
})
|
|
30
|
+
const stored: unknown = JSON.parse(text)
|
|
31
|
+
if (typeof stored !== "object" || stored === null || Array.isArray(stored)) {
|
|
32
|
+
throw new Error("[SixbCLI] allowed-folders.json doesn't list folders by project.")
|
|
33
|
+
}
|
|
34
|
+
return Object.fromEntries(
|
|
35
|
+
Object.entries(stored).map(([key, folders]) => [
|
|
36
|
+
key,
|
|
37
|
+
Array.isArray(folders)
|
|
38
|
+
? folders.filter((folder): folder is string => typeof folder === "string")
|
|
39
|
+
: [],
|
|
40
|
+
])
|
|
41
|
+
)
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/** The folders chosen on this computer for `project`. Throws when the list can't be read. */
|
|
45
|
+
export async function readAllowedFolders(project: AllowedFor): Promise<readonly string[]> {
|
|
46
|
+
return (await readStored())[keyOf(project)] ?? []
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/** Whether `folder` was chosen here for `project`. A list that can't be read allows nothing. */
|
|
50
|
+
export async function isFolderAllowed(project: AllowedFor, folder: string): Promise<boolean> {
|
|
51
|
+
return readAllowedFolders(project).then(
|
|
52
|
+
(folders) => folders.includes(folder),
|
|
53
|
+
() => false
|
|
54
|
+
)
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
let lastChange: Promise<unknown> = Promise.resolve()
|
|
58
|
+
|
|
59
|
+
/** One at a time here, so that a quick off and on can't undo each other. */
|
|
60
|
+
function oneAtATime(write: () => Promise<void>): Promise<void> {
|
|
61
|
+
const change = lastChange.then(write)
|
|
62
|
+
lastChange = change.catch(() => {})
|
|
63
|
+
return change
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/** Allow or forget folders for `project`. A folder forgotten stays forgotten. */
|
|
67
|
+
export function setFoldersAllowed(
|
|
68
|
+
project: AllowedFor,
|
|
69
|
+
changed: readonly string[],
|
|
70
|
+
allowed: boolean
|
|
71
|
+
): Promise<void> {
|
|
72
|
+
return oneAtATime(() => writeChange(project, changed, allowed))
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/**
|
|
76
|
+
* Reads the file first, as another `sixb` may have written it, and refuses one it can't read rather
|
|
77
|
+
* than lose the choices in it. Written whole, so no reader finds half.
|
|
78
|
+
*/
|
|
79
|
+
async function writeChange(
|
|
80
|
+
project: AllowedFor,
|
|
81
|
+
changed: readonly string[],
|
|
82
|
+
allowed: boolean
|
|
83
|
+
): Promise<void> {
|
|
84
|
+
const stored = await readStored()
|
|
85
|
+
const key = keyOf(project)
|
|
86
|
+
const others = (stored[key] ?? []).filter((folder) => !changed.includes(folder))
|
|
87
|
+
await writeStored({ ...stored, [key]: allowed ? [...others, ...changed] : others })
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
async function writeStored(stored: StoredFolders): Promise<void> {
|
|
91
|
+
const path = ALLOWED_FOLDERS_FILE()
|
|
92
|
+
const written = `${path}.${randomUUID()}`
|
|
93
|
+
await mkdir(dirname(path), { recursive: true, mode: 0o700 })
|
|
94
|
+
await writeFile(written, `${JSON.stringify(stored, null, 2)}\n`, { mode: 0o600 })
|
|
95
|
+
await rename(written, path)
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
/**
|
|
99
|
+
* Forget `folder` for every project at `apiUrl`. Needs no sign-in, as a list on this computer doesn't:
|
|
100
|
+
* someone signed out can still take a folder back, and it stays taken back.
|
|
101
|
+
*/
|
|
102
|
+
export function forgetFolderAt(apiUrl: string, folder: string): Promise<void> {
|
|
103
|
+
return oneAtATime(async () => {
|
|
104
|
+
const stored = await readStored()
|
|
105
|
+
const suffix = ` at ${apiUrl}`
|
|
106
|
+
await writeStored(
|
|
107
|
+
Object.fromEntries(
|
|
108
|
+
Object.entries(stored).map(([key, folders]) => [
|
|
109
|
+
key,
|
|
110
|
+
key.endsWith(suffix) ? folders.filter((known) => known !== folder) : folders,
|
|
111
|
+
])
|
|
112
|
+
)
|
|
113
|
+
)
|
|
114
|
+
})
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
/** Call `changed` whenever the list may have changed. Returns the way to stop. */
|
|
118
|
+
export async function watchAllowedFolders(changed: () => void): Promise<() => void> {
|
|
119
|
+
const path = ALLOWED_FOLDERS_FILE()
|
|
120
|
+
await mkdir(dirname(path), { recursive: true, mode: 0o700 })
|
|
121
|
+
// The directory: a write replaces the file, which a watch on the file itself would lose.
|
|
122
|
+
const watcher = watch(dirname(path), (_event, name) => {
|
|
123
|
+
if (name === basename(path)) changed()
|
|
124
|
+
})
|
|
125
|
+
return () => watcher.close()
|
|
126
|
+
}
|
|
@@ -0,0 +1,184 @@
|
|
|
1
|
+
import { stat } from "node:fs/promises"
|
|
2
|
+
import { createAgentActivitySocket, getAgentThread, isSixbApiError } from "@sixb/client"
|
|
3
|
+
import type { Connection } from "../lib/connection"
|
|
4
|
+
import { errorMessage } from "../lib/errors"
|
|
5
|
+
import { readAllowedFolders, watchAllowedFolders } from "./allowed-folders"
|
|
6
|
+
import { LocalRunner } from "./local-runner"
|
|
7
|
+
|
|
8
|
+
/** How often the allowed folders are checked for being there still. */
|
|
9
|
+
const FOLDER_RECHECK_MS = 20_000
|
|
10
|
+
/** Exit status when the person's sign-in ended: whatever restarts this should know. */
|
|
11
|
+
export const EXIT_SIGNED_OUT = 3
|
|
12
|
+
|
|
13
|
+
/** What a connected computer reports, one line each with `sixb connect --json`. */
|
|
14
|
+
export type ComputerEvent =
|
|
15
|
+
| { readonly type: "folders"; readonly folders: readonly string[] }
|
|
16
|
+
| {
|
|
17
|
+
readonly type: "turn.started"
|
|
18
|
+
readonly folder: string
|
|
19
|
+
readonly threadId: string
|
|
20
|
+
readonly runId: string
|
|
21
|
+
}
|
|
22
|
+
| {
|
|
23
|
+
readonly type: "turn.ended"
|
|
24
|
+
readonly folder: string
|
|
25
|
+
readonly threadId: string
|
|
26
|
+
readonly runId: string
|
|
27
|
+
/** False when it could not be claimed or failed before it ended on its own. */
|
|
28
|
+
readonly ran: boolean
|
|
29
|
+
}
|
|
30
|
+
| { readonly type: "session.lost"; readonly folder: string; readonly message: string }
|
|
31
|
+
| { readonly type: "session.back"; readonly folder: string }
|
|
32
|
+
| { readonly type: "signed-out" }
|
|
33
|
+
| { readonly type: "error"; readonly message: string }
|
|
34
|
+
|
|
35
|
+
/**
|
|
36
|
+
* This computer, connected to a project: one session per folder allowed for it, and the turns sent
|
|
37
|
+
* to their conversations run in their folders. The list of folders is read again whenever it changes, so
|
|
38
|
+
* choosing one needs no restart.
|
|
39
|
+
*/
|
|
40
|
+
export class ComputerConnection {
|
|
41
|
+
private readonly runners = new Map<string, LocalRunner>()
|
|
42
|
+
private socket: { close(): void } | null = null
|
|
43
|
+
private unwatch: (() => void) | null = null
|
|
44
|
+
private recheck: ReturnType<typeof setInterval> | null = null
|
|
45
|
+
private reconciled: Promise<void> = Promise.resolve()
|
|
46
|
+
private shown: readonly string[] | null = null
|
|
47
|
+
private stopped = false
|
|
48
|
+
private signedOut = false
|
|
49
|
+
|
|
50
|
+
constructor(
|
|
51
|
+
private readonly connection: Connection,
|
|
52
|
+
private readonly onEvent: (event: ComputerEvent) => void,
|
|
53
|
+
private readonly keepsAwake: boolean,
|
|
54
|
+
/** What the agent's commands also never read, beyond what `sixb` keeps from them. */
|
|
55
|
+
private readonly alsoDenied: readonly string[] = []
|
|
56
|
+
) {}
|
|
57
|
+
|
|
58
|
+
async start(): Promise<void> {
|
|
59
|
+
this.unwatch = await watchAllowedFolders(() => void this.reconcile())
|
|
60
|
+
await this.reconcile()
|
|
61
|
+
// A folder can go or come back with no change to the list: a deleted one, an unmounted volume.
|
|
62
|
+
this.recheck = setInterval(() => void this.reconcile(), FOLDER_RECHECK_MS)
|
|
63
|
+
this.socket = createAgentActivitySocket({
|
|
64
|
+
client: this.connection.client,
|
|
65
|
+
onActivity: (event) => {
|
|
66
|
+
if (event.runsOn !== "computer") return
|
|
67
|
+
if (event.cancelRequested) {
|
|
68
|
+
for (const runner of this.runners.values()) runner.hearStop(event.runId)
|
|
69
|
+
return
|
|
70
|
+
}
|
|
71
|
+
// Queued turns only reach here by this event for speed: each renewal lists them too.
|
|
72
|
+
if (event.status !== "queued") return
|
|
73
|
+
void this.route(event.threadId, event.runId).catch((error: unknown) =>
|
|
74
|
+
this.onEvent({ type: "error", message: errorMessage(error) })
|
|
75
|
+
)
|
|
76
|
+
},
|
|
77
|
+
})
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/** Stop every turn running here, each ending interrupted, and close every session. */
|
|
81
|
+
async stop(): Promise<void> {
|
|
82
|
+
this.stopped = true
|
|
83
|
+
this.socket?.close()
|
|
84
|
+
this.unwatch?.()
|
|
85
|
+
if (this.recheck) clearInterval(this.recheck)
|
|
86
|
+
// Not after `reconciled`: a stalled call there mustn't keep a turn from hearing its stop.
|
|
87
|
+
await Promise.allSettled([...this.runners.values()].map((runner) => runner.stop()))
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/** One at a time, so two quick changes can't leave the older read in charge. */
|
|
91
|
+
private reconcile(): Promise<void> {
|
|
92
|
+
this.reconciled = this.reconciled.then(() => this.applyAllowedFolders())
|
|
93
|
+
return this.reconciled
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
private async applyAllowedFolders(): Promise<void> {
|
|
97
|
+
if (this.stopped) return
|
|
98
|
+
const allowed = await this.readAllowed()
|
|
99
|
+
const folders = await this.existing(allowed)
|
|
100
|
+
if (this.stopped) return
|
|
101
|
+
|
|
102
|
+
for (const folder of folders) this.runnerFor(folder).openSession()
|
|
103
|
+
for (const [folder, runner] of this.runners) {
|
|
104
|
+
if (folders.includes(folder)) continue
|
|
105
|
+
// Not awaited: a stalled call there mustn't keep the next change from being applied. Taken back,
|
|
106
|
+
// nothing more runs there. Only gone for now, a volume coming back mustn't cost a turn.
|
|
107
|
+
void (allowed.includes(folder) ? runner.closeSession() : runner.stop())
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
if (folders.join("\n") !== this.shown?.join("\n")) {
|
|
111
|
+
this.shown = folders
|
|
112
|
+
this.onEvent({ type: "folders", folders })
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
/** A list that can't be read allows nothing, and says so. */
|
|
117
|
+
private async readAllowed(): Promise<readonly string[]> {
|
|
118
|
+
try {
|
|
119
|
+
return await readAllowedFolders(this.connection)
|
|
120
|
+
} catch (error) {
|
|
121
|
+
this.onEvent({ type: "error", message: errorMessage(error) })
|
|
122
|
+
return []
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
/** A folder that's gone reads as offline, rather than as one whose turns all fail. */
|
|
127
|
+
private async existing(folders: readonly string[]): Promise<readonly string[]> {
|
|
128
|
+
const found = await Promise.all(
|
|
129
|
+
folders.map((folder) =>
|
|
130
|
+
stat(folder).then(
|
|
131
|
+
(entry) => entry.isDirectory(),
|
|
132
|
+
() => false
|
|
133
|
+
)
|
|
134
|
+
)
|
|
135
|
+
)
|
|
136
|
+
return folders.filter((_folder, index) => found[index])
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
private runnerFor(folder: string): LocalRunner {
|
|
140
|
+
const known = this.runners.get(folder)
|
|
141
|
+
if (known) return known
|
|
142
|
+
|
|
143
|
+
const runner = new LocalRunner(
|
|
144
|
+
this.connection,
|
|
145
|
+
folder,
|
|
146
|
+
(error) => this.onEvent({ type: "error", message: errorMessage(error) }),
|
|
147
|
+
{
|
|
148
|
+
onSessionChange: (failure) => this.onSessionChange(folder, failure),
|
|
149
|
+
alsoDenied: this.alsoDenied,
|
|
150
|
+
}
|
|
151
|
+
)
|
|
152
|
+
runner.keepsAwake = this.keepsAwake
|
|
153
|
+
runner.onElsewhere((run, ended) => {
|
|
154
|
+
const turn = { folder, threadId: run.threadId, runId: run.id }
|
|
155
|
+
this.onEvent({ type: "turn.started", ...turn })
|
|
156
|
+
void ended.then((ran) => this.onEvent({ type: "turn.ended", ...turn, ran }))
|
|
157
|
+
})
|
|
158
|
+
this.runners.set(folder, runner)
|
|
159
|
+
return runner
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
private onSessionChange(folder: string, failure: unknown | null): void {
|
|
163
|
+
if (failure === null) {
|
|
164
|
+
this.onEvent({ type: "session.back", folder })
|
|
165
|
+
} else if (isSixbApiError(failure) && failure.status === 401) {
|
|
166
|
+
// Every folder's session ends with the sign-in: once is enough to say so.
|
|
167
|
+
if (this.signedOut) return
|
|
168
|
+
this.signedOut = true
|
|
169
|
+
this.onEvent({ type: "signed-out" })
|
|
170
|
+
} else {
|
|
171
|
+
this.onEvent({ type: "session.lost", folder, message: errorMessage(failure) })
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
/** Each folder's runner would read the thread to learn it isn't theirs: read it once. */
|
|
176
|
+
private async route(threadId: string, runId: string): Promise<void> {
|
|
177
|
+
const { data: thread } = await getAgentThread({
|
|
178
|
+
client: this.connection.client,
|
|
179
|
+
path: { threadId },
|
|
180
|
+
})
|
|
181
|
+
const folder = thread?.computer?.folder
|
|
182
|
+
if (thread && folder) await this.runners.get(folder)?.offer(thread, runId)
|
|
183
|
+
}
|
|
184
|
+
}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
// What `@sixb/desktop` compiles into a desktop app: `<binary> <api-url> <client-name> [window-data]`.
|
|
2
|
+
import { runDesktopRunner } from "./desktop-runner"
|
|
3
|
+
|
|
4
|
+
const [apiUrl, clientName, windowData] = process.argv.slice(2)
|
|
5
|
+
if (!apiUrl || !clientName) {
|
|
6
|
+
console.error("[SixbCLI] Usage: <binary> <api-url> <client-name> [window-data]")
|
|
7
|
+
process.exit(2)
|
|
8
|
+
}
|
|
9
|
+
await runDesktopRunner({ apiUrl, clientName, ...(windowData ? { windowData } : {}) })
|