@runuai/host 0.9.99 → 0.9.100

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.
@@ -0,0 +1,7 @@
1
+ -- ADR-131 Decision 3: engine accounts carry a scope — 'host' (the owner's,
2
+ -- today's rows) or 'org:<orgId>' (a workspace's account on a shared host).
3
+ -- Tasks resolve accounts by their scope; org scopes never see the default
4
+ -- slot or the host's rows.
5
+ ALTER TABLE `host_engine_accounts` ADD `scope` text NOT NULL DEFAULT 'host';--> statement-breakpoint
6
+ CREATE INDEX `host_engine_accounts_scope_kind_idx` ON `host_engine_accounts` (`scope`,`kind`);--> statement-breakpoint
7
+ ALTER TABLE `uai_host_tasks` ADD `engine_account_scope` text;
@@ -120,6 +120,13 @@
120
120
  "when": 1786406402000,
121
121
  "tag": "0016_task_environment",
122
122
  "breakpoints": true
123
+ },
124
+ {
125
+ "idx": 17,
126
+ "version": "6",
127
+ "when": 1788820000000,
128
+ "tag": "0017_engine_account_scope",
129
+ "breakpoints": true
123
130
  }
124
131
  ]
125
132
  }
package/db/schema.ts CHANGED
@@ -37,6 +37,10 @@ export const hostTasks = sqliteTable(
37
37
  ownerEmail: text("owner_email"),
38
38
  ownerName: text("owner_name"),
39
39
  projectSlugs: text("project_slugs").notNull().default("[]"),
40
+ // ADR-131 D3: which engine-account scope this task resolves credentials
41
+ // from ("org:<orgId>" on a shared host; null = "host"). Persisted so a
42
+ // host restart re-provisions the same scope before the cloud re-sends it.
43
+ engineAccountScope: text("engine_account_scope"),
40
44
  lockedAt: integer("locked_at", { mode: "number" }),
41
45
  startedAt: integer("started_at", { mode: "number" }),
42
46
  endedAt: integer("ended_at", { mode: "number" }),
@@ -271,6 +275,9 @@ export const engineAccounts = sqliteTable("host_engine_accounts", {
271
275
  authKind: text("auth_kind").notNull(), // "env" | "config-dir"
272
276
  secretEnc: text("secret_enc"), // sealed JSON (env kind); null for config-dir
273
277
  configDir: text("config_dir"), // host dir (config-dir kind); null for env
278
+ // ADR-131 D3: "host" (owner-level, default) or "org:<orgId>" (a workspace's
279
+ // account on a shared host). Resolution is by exact scope.
280
+ scope: text("scope").notNull().default("host"),
274
281
  createdAt: integer("created_at", { mode: "number" }).notNull(),
275
282
  });
276
283
 
@@ -22,6 +22,10 @@
22
22
  * caps reset over time).
23
23
  */
24
24
 
25
+ import {
26
+ HOST_ACCOUNT_SCOPE,
27
+ isEngineAccountScope,
28
+ } from "../src/protocol";
25
29
  import { chmodSync, existsSync, mkdirSync, rmSync, writeFileSync } from "node:fs";
26
30
  import { homedir } from "node:os";
27
31
  import { join } from "node:path";
@@ -85,6 +89,8 @@ export interface EngineAccountInfo {
85
89
  label: string;
86
90
  authKind: AccountAuthKind;
87
91
  isDefault: boolean;
92
+ /** ADR-131 D3: "host" or "org:<orgId>". */
93
+ scope: string;
88
94
  }
89
95
 
90
96
  /** A fully-resolved account, ready to inject / provision (host-trusted; the
@@ -94,6 +100,8 @@ export interface ResolvedEngineAccount {
94
100
  kind: string;
95
101
  label: string;
96
102
  isDefault: boolean;
103
+ /** ADR-131 D3: "host" or "org:<orgId>". */
104
+ scope: string;
97
105
  authKind: AccountAuthKind;
98
106
  /** Env merged into the agent's docker exec. Empty for the default env
99
107
  * account (the ambient `.env.local` credential is account #1). */
@@ -141,6 +149,27 @@ function unpackSecret(enc: string): string {
141
149
  return openAesGcm(ct, nonce);
142
150
  }
143
151
 
152
+ // ---------------------------------------------------------------------------
153
+ // Scopes (ADR-131 Decision 3).
154
+ // ---------------------------------------------------------------------------
155
+
156
+ /**
157
+ * Every account has a scope. `host` is the owner's: the default slot plus
158
+ * every extra account connected before scopes existed (and every one an
159
+ * owner connects on a BYO/dedicated host). `org:<orgId>` is a workspace's
160
+ * account on a shared host: resolved ONLY for that workspace's tasks, and
161
+ * never joined by the default slot — a tenant sees exactly what it connected.
162
+ */
163
+ export { HOST_ACCOUNT_SCOPE, isEngineAccountScope };
164
+
165
+ /** A row's scope (legacy rows read as `host`) matches the requested one. */
166
+ export function accountInScope(
167
+ rowScope: string | null | undefined,
168
+ scope: string,
169
+ ): boolean {
170
+ return (rowScope ?? HOST_ACCOUNT_SCOPE) === scope;
171
+ }
172
+
144
173
  // ---------------------------------------------------------------------------
145
174
  // Resolution.
146
175
  // ---------------------------------------------------------------------------
@@ -177,6 +206,7 @@ function synthesizeDefault(
177
206
  label: "Default",
178
207
  isDefault: true,
179
208
  authKind: "env",
209
+ scope: HOST_ACCOUNT_SCOPE,
180
210
  execEnv: {},
181
211
  };
182
212
  }
@@ -187,6 +217,7 @@ function synthesizeDefault(
187
217
  label: "Default",
188
218
  isDefault: true,
189
219
  authKind: "config-dir",
220
+ scope: HOST_ACCOUNT_SCOPE,
190
221
  execEnv: d.selectVar ? { [d.selectVar]: containerDir } : {},
191
222
  configDir: {
192
223
  hostDir: (d.defaultHostDir as (o: string) => string)(s.ownerHome()),
@@ -196,14 +227,22 @@ function synthesizeDefault(
196
227
  }
197
228
 
198
229
  /** DB extras for a kind, resolved into injectable form. */
199
- function resolveExtras(kind: string, s: AccountSeams): ResolvedEngineAccount[] {
230
+ function resolveExtras(
231
+ kind: string,
232
+ s: AccountSeams,
233
+ scope: string,
234
+ ): ResolvedEngineAccount[] {
200
235
  const d = KINDS[kind];
201
236
  if (!d) return [];
202
237
  const rows = getDb()
203
238
  .select()
204
239
  .from(schema.engineAccounts)
205
240
  .all()
206
- .filter((r) => r.kind === kind);
241
+ .filter(
242
+ (r) =>
243
+ r.kind === kind &&
244
+ accountInScope((r as { scope?: string | null }).scope, scope),
245
+ );
207
246
  const out: ResolvedEngineAccount[] = [];
208
247
  for (const row of rows) {
209
248
  if (row.authKind === "env") {
@@ -226,6 +265,7 @@ function resolveExtras(kind: string, s: AccountSeams): ResolvedEngineAccount[] {
226
265
  label: row.label,
227
266
  isDefault: false,
228
267
  authKind: "env",
268
+ scope,
229
269
  execEnv,
230
270
  });
231
271
  } else if (row.authKind === "config-dir" && row.configDir && d.selectVar) {
@@ -236,6 +276,7 @@ function resolveExtras(kind: string, s: AccountSeams): ResolvedEngineAccount[] {
236
276
  label: row.label,
237
277
  isDefault: false,
238
278
  authKind: "config-dir",
279
+ scope,
239
280
  execEnv: { [d.selectVar]: containerDir },
240
281
  configDir: { hostDir: row.configDir, containerDir },
241
282
  });
@@ -248,12 +289,16 @@ function resolveExtras(kind: string, s: AccountSeams): ResolvedEngineAccount[] {
248
289
  export function resolveEngineAccounts(
249
290
  kind: string,
250
291
  seams: Partial<AccountSeams> = {},
292
+ scope: string = HOST_ACCOUNT_SCOPE,
251
293
  ): ResolvedEngineAccount[] {
252
294
  const s = withDefaults(seams);
253
295
  const accounts: ResolvedEngineAccount[] = [];
254
- const def = synthesizeDefault(kind, s);
255
- if (def) accounts.push(def);
256
- accounts.push(...resolveExtras(kind, s));
296
+ // The default slot is the OWNER's credential: it joins the host scope only.
297
+ if (scope === HOST_ACCOUNT_SCOPE) {
298
+ const def = synthesizeDefault(kind, s);
299
+ if (def) accounts.push(def);
300
+ }
301
+ accounts.push(...resolveExtras(kind, s, scope));
257
302
  return accounts;
258
303
  }
259
304
 
@@ -261,22 +306,47 @@ export function resolveEngineAccounts(
261
306
  export function listEngineAccounts(
262
307
  kind: string,
263
308
  seams: Partial<AccountSeams> = {},
309
+ scope: string = HOST_ACCOUNT_SCOPE,
264
310
  ): EngineAccountInfo[] {
265
- return resolveEngineAccounts(kind, seams).map((a) => ({
311
+ return resolveEngineAccounts(kind, seams, scope).map((a) => ({
266
312
  id: a.id,
267
313
  kind: a.kind,
268
314
  label: a.label,
269
315
  authKind: a.authKind,
270
316
  isDefault: a.isDefault,
317
+ scope: a.scope,
271
318
  }));
272
319
  }
273
320
 
321
+ /** Every scope holding at least one stored account for the kind, plus
322
+ * `host` (which may consist of the default slot alone). */
323
+ export function engineAccountScopes(kind: string): string[] {
324
+ const scopes = new Set<string>([HOST_ACCOUNT_SCOPE]);
325
+ for (const row of getDb().select().from(schema.engineAccounts).all()) {
326
+ if (row.kind !== kind) continue;
327
+ scopes.add((row as { scope?: string | null }).scope ?? HOST_ACCOUNT_SCOPE);
328
+ }
329
+ return [...scopes];
330
+ }
331
+
332
+ /** Account list across ALL scopes — the capabilities advertisement. The
333
+ * cloud filters per caller; labels only, never credentials. */
334
+ export function listEngineAccountsAllScopes(
335
+ kind: string,
336
+ seams: Partial<AccountSeams> = {},
337
+ ): EngineAccountInfo[] {
338
+ return engineAccountScopes(kind).flatMap((scope) =>
339
+ listEngineAccounts(kind, seams, scope),
340
+ );
341
+ }
342
+
274
343
  /** How many accounts a kind has right now (default + extras). */
275
344
  export function engineAccountCount(
276
345
  kind: string,
277
346
  seams: Partial<AccountSeams> = {},
347
+ scope: string = HOST_ACCOUNT_SCOPE,
278
348
  ): number {
279
- return resolveEngineAccounts(kind, seams).length;
349
+ return resolveEngineAccounts(kind, seams, scope).length;
280
350
  }
281
351
 
282
352
  // ---------------------------------------------------------------------------
@@ -339,9 +409,19 @@ export function selectAccount(
339
409
  /** Pick an account for a kind (default + extras), applying rotation state. */
340
410
  export function pickEngineAccount(
341
411
  kind: string,
342
- opts: { exclude?: Set<string>; seams?: Partial<AccountSeams>; now?: number } = {},
412
+ opts: {
413
+ exclude?: Set<string>;
414
+ seams?: Partial<AccountSeams>;
415
+ now?: number;
416
+ /** ADR-131 D3: the task's scope; default = the host's own accounts. */
417
+ scope?: string;
418
+ } = {},
343
419
  ): ResolvedEngineAccount | null {
344
- const accounts = resolveEngineAccounts(kind, opts.seams ?? {});
420
+ const accounts = resolveEngineAccounts(
421
+ kind,
422
+ opts.seams ?? {},
423
+ opts.scope ?? HOST_ACCOUNT_SCOPE,
424
+ );
345
425
  return selectAccount(accounts, { exclude: opts.exclude, now: opts.now });
346
426
  }
347
427
 
@@ -495,6 +575,7 @@ export async function provisionEngineAccounts(
495
575
  kinds: Iterable<string>,
496
576
  seams: Partial<AccountSeams> = {},
497
577
  environment?: Pick<TaskEnvironmentHandle, "exec" | "copy">,
578
+ scope: string = HOST_ACCOUNT_SCOPE,
498
579
  ): Promise<ProvisionEngineAccountsResult> {
499
580
  const s = withDefaults(seams);
500
581
  const seen = new Set<string>();
@@ -504,7 +585,7 @@ export async function provisionEngineAccounts(
504
585
  for (const kind of kinds) {
505
586
  if (seen.has(kind)) continue;
506
587
  seen.add(kind);
507
- for (const account of resolveEngineAccounts(kind, s)) {
588
+ for (const account of resolveEngineAccounts(kind, s, scope)) {
508
589
  if (account.isDefault || !account.configDir) continue;
509
590
  if (!s.fileExists(account.configDir.hostDir)) {
510
591
  failed += 1;
@@ -554,8 +635,12 @@ export function addEngineAccount(
554
635
  label: string,
555
636
  creds: { apiKey?: string; token?: string },
556
637
  seams: Partial<AccountSeams> = {},
638
+ scope: string = HOST_ACCOUNT_SCOPE,
557
639
  ): AddAccountResult {
558
640
  const s = withDefaults(seams);
641
+ if (!isEngineAccountScope(scope)) {
642
+ return { ok: false, message: "The account scope is invalid." };
643
+ }
559
644
  const trimmedLabel = label.trim();
560
645
  if (!trimmedLabel) return { ok: false, message: "Give the account a label." };
561
646
  const secret = (creds.token ?? creds.apiKey ?? "").trim();
@@ -581,6 +666,7 @@ export function addEngineAccount(
581
666
  secretEnc: packSecret(JSON.stringify({ [envVar]: secret })),
582
667
  configDir: null,
583
668
  createdAt: now,
669
+ scope,
584
670
  })
585
671
  .run();
586
672
  return { ok: true, message: `Added Claude account "${trimmedLabel}".`, id };
@@ -621,6 +707,7 @@ export function addEngineAccount(
621
707
  secretEnc: null,
622
708
  configDir: hostDir,
623
709
  createdAt: now,
710
+ scope,
624
711
  })
625
712
  .run();
626
713
  return { ok: true, message: `Added Codex account "${trimmedLabel}".`, id };
@@ -642,7 +729,11 @@ export function addCodexAccountFromAuthJson(
642
729
  label: string,
643
730
  authJson: string,
644
731
  seams: Partial<AccountSeams> = {},
732
+ scope: string = HOST_ACCOUNT_SCOPE,
645
733
  ): AddAccountResult {
734
+ if (!isEngineAccountScope(scope)) {
735
+ return { ok: false, message: "The account scope is invalid." };
736
+ }
646
737
  const s = withDefaults(seams);
647
738
  const trimmedLabel = label.trim();
648
739
  if (!trimmedLabel) return { ok: false, message: "Give the account a label." };
@@ -690,6 +781,7 @@ export function addCodexAccountFromAuthJson(
690
781
  secretEnc: null,
691
782
  configDir: hostDir,
692
783
  createdAt: Date.now(),
784
+ scope,
693
785
  })
694
786
  .run();
695
787
  return { ok: true, message: `Added Codex account "${trimmedLabel}".`, id };
@@ -698,7 +790,19 @@ export function addCodexAccountFromAuthJson(
698
790
  /** Remove an EXTRA account (idempotent). The synthesized default can't be
699
791
  * removed here (use the engine disconnect flow for the legacy slot). The
700
792
  * isolated host config dir of a config-dir account is deleted too. */
701
- export function removeEngineAccount(id: string): { ok: boolean; message: string } {
793
+ /** Whether a caller acting in `scope` may remove `row`. `undefined` is the
794
+ * host's own local UI, which may remove anything. */
795
+ export function accountRemovableInScope(
796
+ row: { scope?: string | null },
797
+ scope: string | undefined,
798
+ ): boolean {
799
+ return scope === undefined || accountInScope(row.scope, scope);
800
+ }
801
+
802
+ export function removeEngineAccount(
803
+ id: string,
804
+ scope?: string,
805
+ ): { ok: boolean; message: string } {
702
806
  if (id.startsWith("default:")) {
703
807
  return {
704
808
  ok: false,
@@ -711,6 +815,11 @@ export function removeEngineAccount(id: string): { ok: boolean; message: string
711
815
  .where(eq(schema.engineAccounts.id, id))
712
816
  .get();
713
817
  if (!row) return { ok: true, message: "Account already removed." };
818
+ // ADR-131 D3: a workspace removes only its own accounts — never the host's
819
+ // and never another workspace's, whatever id it names.
820
+ if (!accountRemovableInScope(row, scope)) {
821
+ return { ok: false, message: "That account belongs to a different scope." };
822
+ }
714
823
  getDb().delete(schema.engineAccounts).where(eq(schema.engineAccounts.id, id)).run();
715
824
  if (row.authKind === "config-dir" && row.configDir) {
716
825
  try {
@@ -10,7 +10,9 @@
10
10
  */
11
11
 
12
12
  import {
13
+ HOST_ACCOUNT_SCOPE,
13
14
  isEngineAccountLabel,
15
+ isEngineAccountScope,
14
16
  isHostOpId,
15
17
  MAX_ENGINE_CONNECT_LINE_CHARS,
16
18
  MAX_ENGINE_CONNECT_SECRET_CHARS,
@@ -57,8 +59,10 @@ export class EngineConnectManager {
57
59
  secret: string | undefined,
58
60
  label: string | undefined,
59
61
  emit: EmitEngineConnectEvent,
62
+ scope: string | undefined = undefined,
60
63
  ): boolean {
61
64
  if (!isHostOpId(opId) || this.operations.has(opId)) return false;
65
+ if (scope !== undefined && !isEngineAccountScope(scope)) return false;
62
66
  if (
63
67
  secret !== undefined &&
64
68
  (secret.length < 1 || secret.length > MAX_ENGINE_CONNECT_SECRET_CHARS)
@@ -93,7 +97,7 @@ export class EngineConnectManager {
93
97
  this.finish(operation, false, "Engine connect timed out.");
94
98
  }, CONNECT_TIMEOUT_MS);
95
99
  operation.timer.unref?.();
96
- void this.run(operation, secret, label).catch((error: unknown) => {
100
+ void this.run(operation, secret, label, scope).catch((error: unknown) => {
97
101
  this.finish(
98
102
  operation,
99
103
  false,
@@ -118,6 +122,7 @@ export class EngineConnectManager {
118
122
  operation: ConnectOperation,
119
123
  secret: string | undefined,
120
124
  label: string | undefined,
125
+ scope: string | undefined,
121
126
  ): Promise<void> {
122
127
  const { engine } = operation;
123
128
  const emitLine = (line: string): void => {
@@ -153,11 +158,28 @@ export class EngineConnectManager {
153
158
 
154
159
  // ADR-116 labeled extra account — the sink validates kind support.
155
160
  if (label !== undefined && secret !== undefined) {
156
- const added = addEngineAccount(engine, label, { token: secret });
161
+ const added = addEngineAccount(
162
+ engine,
163
+ label,
164
+ { token: secret },
165
+ {},
166
+ scope ?? HOST_ACCOUNT_SCOPE,
167
+ );
157
168
  if (added.ok) this.afterMutation(engine, false);
158
169
  this.finish(operation, added.ok, added.message);
159
170
  return;
160
171
  }
172
+ // ADR-131 D3: everything below writes the host's DEFAULT slot or re-detects
173
+ // a host-side login — the owner's credential, never a workspace's. A
174
+ // tenant scope must not reach it.
175
+ if (scope !== undefined && scope !== HOST_ACCOUNT_SCOPE) {
176
+ this.finish(
177
+ operation,
178
+ false,
179
+ "Workspace accounts need a label and a pasted secret; the host's own sign-in is not available to workspaces.",
180
+ );
181
+ return;
182
+ }
161
183
 
162
184
  const result = await connectEngine(
163
185
  engine as EngineKind,
@@ -27,7 +27,9 @@ import { homedir, tmpdir } from "node:os";
27
27
  import { basename, dirname, join, resolve } from "node:path";
28
28
 
29
29
  import {
30
+ HOST_ACCOUNT_SCOPE,
30
31
  isEngineAccountLabel,
32
+ isEngineAccountScope,
31
33
  isHostOpId,
32
34
  MAX_ENGINE_LOGIN_QUERY_CHARS,
33
35
  MAX_ENGINE_LOGIN_TEXT_CHARS,
@@ -145,8 +147,16 @@ export interface EngineLoginSeams {
145
147
  persistClaudeToken(token: string): Promise<void>;
146
148
  persistCodexAuth(sourceFile: string): Promise<void>;
147
149
  /** ADR-116: labeled extra-account captures (never the default slots). */
148
- addClaudeAccount(label: string, token: string): { ok: boolean; message: string };
149
- addCodexAccount(label: string, authJson: string): { ok: boolean; message: string };
150
+ addClaudeAccount(
151
+ label: string,
152
+ token: string,
153
+ scope: string,
154
+ ): { ok: boolean; message: string };
155
+ addCodexAccount(
156
+ label: string,
157
+ authJson: string,
158
+ scope: string,
159
+ ): { ok: boolean; message: string };
150
160
  refreshEngineAccountAgents(engine: "claude"): Promise<void>;
151
161
  reinjectCodexRunningTasks(): Promise<void>;
152
162
  ownerHome(): string;
@@ -209,6 +219,8 @@ interface LoginOperation {
209
219
  /** ADR-116: when set, the captured credential lands in a labeled extra
210
220
  * account instead of the default slot. */
211
221
  accountLabel: string | null;
222
+ /** ADR-131 D3: the scope a labeled capture is stored under. */
223
+ accountScope: string;
212
224
  /** Diagnosis breadcrumb: has ANY output arrived after the one-time code
213
225
  * was written? Distinguishes "stdin never delivered" from "CLI answered
214
226
  * and we ignored it" without reading the PTY transcript. */
@@ -299,10 +311,10 @@ function defaultSeams(options: EngineLoginManagerOptions): EngineLoginSeams {
299
311
  },
300
312
  persistClaudeToken: (token) => persistClaudeTokenAtomic(token),
301
313
  persistCodexAuth: (sourceFile) => persistCodexAuthAtomic(sourceFile),
302
- addClaudeAccount: (label, token) =>
303
- addEngineAccount("claude", label, { token }),
304
- addCodexAccount: (label, authJson) =>
305
- addCodexAccountFromAuthJson(label, authJson),
314
+ addClaudeAccount: (label, token, scope) =>
315
+ addEngineAccount("claude", label, { token }, {}, scope),
316
+ addCodexAccount: (label, authJson, scope) =>
317
+ addCodexAccountFromAuthJson(label, authJson, {}, scope),
306
318
  refreshEngineAccountAgents: options.refreshEngineAccountAgents,
307
319
  reinjectCodexRunningTasks: () => reinjectCodexRunningTasks(),
308
320
  ownerHome,
@@ -370,8 +382,25 @@ export class EngineLoginManager {
370
382
  engine: EngineLoginKind,
371
383
  emit: EmitEngineLoginEvent,
372
384
  label?: string,
385
+ scope?: string,
373
386
  ): boolean {
374
387
  if (!isHostOpId(opId)) return false;
388
+ if (scope !== undefined && !isEngineAccountScope(scope)) {
389
+ safeEmit(
390
+ emit,
391
+ failedEvent(opId, engine, "start_failed", "The account scope is invalid."),
392
+ );
393
+ return false;
394
+ }
395
+ // A workspace's sign-in is always a labeled account: the default slot is
396
+ // the host owner's and must never be written on a tenant's behalf.
397
+ if (scope !== undefined && scope !== HOST_ACCOUNT_SCOPE && label === undefined) {
398
+ safeEmit(
399
+ emit,
400
+ failedEvent(opId, engine, "start_failed", "A workspace account needs a label."),
401
+ );
402
+ return false;
403
+ }
375
404
  if (label !== undefined && !isEngineAccountLabel(label)) {
376
405
  safeEmit(
377
406
  emit,
@@ -426,6 +455,7 @@ export class EngineLoginManager {
426
455
  pendingInput: null,
427
456
  callbackTarget: null,
428
457
  accountLabel: label ?? null,
458
+ accountScope: scope ?? HOST_ACCOUNT_SCOPE,
429
459
  postInputOutputSeen: false,
430
460
  };
431
461
  this.operations.set(opId, operation);
@@ -941,7 +971,11 @@ export class EngineLoginManager {
941
971
  // ADR-116: labeled capture — an extra account, not the default slot.
942
972
  // Extras are picked up at the next agent spawn / rotation, so no
943
973
  // running-agent refresh is needed (mirrors the local accounts API).
944
- const added = this.seams.addClaudeAccount(operation.accountLabel, token);
974
+ const added = this.seams.addClaudeAccount(
975
+ operation.accountLabel,
976
+ token,
977
+ operation.accountScope,
978
+ );
945
979
  terminal = added.ok
946
980
  ? {
947
981
  kind: "engine.login.event",
@@ -1011,7 +1045,11 @@ export class EngineLoginManager {
1011
1045
  join(tempDir, "codex", "auth.json"),
1012
1046
  "utf8",
1013
1047
  );
1014
- added = this.seams.addCodexAccount(operation.accountLabel, contents);
1048
+ added = this.seams.addCodexAccount(
1049
+ operation.accountLabel,
1050
+ contents,
1051
+ operation.accountScope,
1052
+ );
1015
1053
  } catch {
1016
1054
  added = {
1017
1055
  ok: false,
@@ -106,14 +106,14 @@ import {
106
106
  } from "./browser-testing";
107
107
  import { injectCodexIntoContainer } from "./codex-auth";
108
108
  import {
109
+ codexHomeIsolatable,
110
+ codexHomeSeedCommand,
111
+ codexPerAgentHome,
109
112
  cooldownEngineAccount,
110
113
  noteEngineAccountUsed,
111
114
  pickEngineAccount,
112
115
  provisionEngineAccounts,
113
116
  resolveEngineAccounts,
114
- codexHomeIsolatable,
115
- codexPerAgentHome,
116
- codexHomeSeedCommand,
117
117
  type ResolvedEngineAccount,
118
118
  } from "./engine-accounts";
119
119
  import { clearTaskGatewayAcl, setupMcpTaskConfig } from "./mcp-gateway";
@@ -133,6 +133,7 @@ import type {
133
133
  HostEvent,
134
134
  } from "../src/protocol";
135
135
  import {
136
+ HOST_ACCOUNT_SCOPE,
136
137
  MAX_AGENT_ID_CHARS,
137
138
  MAX_SECRETARY_DISPATCH_ID_CHARS,
138
139
  SECRETARY_TYPED_DISPATCH_PROTOCOL_FEATURE,
@@ -155,6 +156,9 @@ const RESTRICTED_SECRETARY_SESSION_ATTACH_KEY =
155
156
  interface Channel {
156
157
  taskId: string;
157
158
  roster: Roster;
159
+ /** ADR-131 D3: the engine-account scope this task's agents resolve
160
+ * credentials from. `host` unless the cloud scoped the task to a workspace. */
161
+ engineAccountScope: string;
158
162
  /** ADR-083: host-derived role assignment for execution-profile enforcement. */
159
163
  mode: "open" | "secretary";
160
164
  secretaryAgentId?: string;
@@ -527,6 +531,7 @@ export class Orchestrator {
527
531
  channel.browserTesting = spec.browserTesting === true;
528
532
  channel.sharedFiles = spec.sharedFiles ?? "ro";
529
533
  channel.mcpConnections = spec.mcpConnections ?? [];
534
+ if (spec.engineAccountScope) channel.engineAccountScope = spec.engineAccountScope;
530
535
  const nextMcpShape = JSON.stringify({
531
536
  connections: channel.mcpConnections,
532
537
  kinds: [...new Set(channel.roster.map((agent) => agent.kind))].sort(),
@@ -640,6 +645,10 @@ export class Orchestrator {
640
645
  const channel: Channel = {
641
646
  taskId,
642
647
  roster,
648
+ engineAccountScope:
649
+ spec.engineAccountScope ??
650
+ getHostTask(taskId)?.engineAccountScope ??
651
+ HOST_ACCOUNT_SCOPE,
643
652
  mode: spec.mode === "secretary" ? "secretary" : "open",
644
653
  secretaryAgentId: spec.secretaryAgentId,
645
654
  sessions: new Map(),
@@ -797,9 +806,9 @@ export class Orchestrator {
797
806
  * copies use this gate: a false→true toggle queues migration after the older
798
807
  * copy, so that copy cannot land last and erase the managed browser block.
799
808
  */
800
- private codexHomes(hasCodex: boolean): string[] {
809
+ private codexHomes(hasCodex: boolean, scope: string): string[] {
801
810
  if (!hasCodex) return [];
802
- const homes = resolveEngineAccounts("codex")
811
+ const homes = resolveEngineAccounts("codex", {}, scope)
803
812
  .map((account) => account.configDir?.containerDir)
804
813
  .filter((home): home is string => Boolean(home));
805
814
  return [...new Set([DEFAULT_CODEX_HOME, ...homes])];
@@ -825,9 +834,9 @@ export class Orchestrator {
825
834
  if (this.isActiveChannel(channel)) channel.configGeneration += 1;
826
835
  }
827
836
 
828
- private provisionFingerprint(kinds: readonly string[]): string {
837
+ private provisionFingerprint(kinds: readonly string[], scope: string): string {
829
838
  const accounts = kinds.flatMap((kind) =>
830
- resolveEngineAccounts(kind)
839
+ resolveEngineAccounts(kind, {}, scope)
831
840
  .filter((account) => !account.isDefault && account.configDir)
832
841
  .map((account) => ({
833
842
  kind,
@@ -864,15 +873,15 @@ export class Orchestrator {
864
873
  const requestedHasCodex =
865
874
  hasCodex || channel.roster.some((agent) => agent.kind === "codex");
866
875
  const requestedHomes = requestedBrowser
867
- ? this.codexHomes(requestedHasCodex)
876
+ ? this.codexHomes(requestedHasCodex, channel.engineAccountScope)
868
877
  : [];
869
878
  const requestedKinds = [
870
879
  ...new Set(channel.roster.map((agent) => agent.kind)),
871
880
  ];
872
881
  const requestedProvisionFingerprint =
873
- this.provisionFingerprint(requestedKinds);
882
+ this.provisionFingerprint(requestedKinds, channel.engineAccountScope);
874
883
  const mayProvisionConfig = requestedKinds.some((kind) =>
875
- resolveEngineAccounts(kind).some(
884
+ resolveEngineAccounts(kind, {}, channel.engineAccountScope).some(
876
885
  (account) => !account.isDefault && Boolean(account.configDir),
877
886
  ),
878
887
  );
@@ -891,13 +900,13 @@ export class Orchestrator {
891
900
  requestedHasCodex ||
892
901
  channel.roster.some((agent) => agent.kind === "codex");
893
902
  const latestHomes = latestBrowser
894
- ? this.codexHomes(latestHasCodex)
903
+ ? this.codexHomes(latestHasCodex, channel.engineAccountScope)
895
904
  : [];
896
905
  const latestKinds = [
897
906
  ...new Set(channel.roster.map((agent) => agent.kind)),
898
907
  ];
899
908
  const latestProvisionFingerprint =
900
- this.provisionFingerprint(latestKinds);
909
+ this.provisionFingerprint(latestKinds, channel.engineAccountScope);
901
910
  if (
902
911
  (latestBrowser &&
903
912
  coverage?.browserAttempted !== true &&
@@ -949,10 +958,14 @@ export class Orchestrator {
949
958
  requestedKinds,
950
959
  {},
951
960
  channel.agentHandle,
961
+ channel.engineAccountScope,
952
962
  )
953
963
  : await provisionEngineAccounts(
954
964
  channel.containerName,
955
965
  requestedKinds,
966
+ {},
967
+ undefined,
968
+ channel.engineAccountScope,
956
969
  );
957
970
  copiedOrUnknown =
958
971
  provisioned.copied > 0 || provisioned.mayHaveMutated;
@@ -1075,12 +1088,15 @@ export class Orchestrator {
1075
1088
  requestedHasCodex ||
1076
1089
  channel.roster.some((agent) => agent.kind === "codex");
1077
1090
  const latestHomes = latestBrowser
1078
- ? this.codexHomes(latestHasCodex)
1091
+ ? this.codexHomes(latestHasCodex, channel.engineAccountScope)
1079
1092
  : [];
1080
1093
  const latestKinds = [
1081
1094
  ...new Set(channel.roster.map((agent) => agent.kind)),
1082
1095
  ];
1083
- const latestProvisionFingerprint = this.provisionFingerprint(latestKinds);
1096
+ const latestProvisionFingerprint = this.provisionFingerprint(
1097
+ latestKinds,
1098
+ channel.engineAccountScope,
1099
+ );
1084
1100
  if (
1085
1101
  (latestBrowser &&
1086
1102
  !coverage.browserAttempted &&
@@ -1169,7 +1185,7 @@ export class Orchestrator {
1169
1185
  ...new Set(channel.roster.map((agent) => agent.kind)),
1170
1186
  ].sort();
1171
1187
  const codexHomes = engineKinds.includes("codex")
1172
- ? this.codexHomes(true)
1188
+ ? this.codexHomes(true, channel.engineAccountScope)
1173
1189
  : [];
1174
1190
  const fingerprint = JSON.stringify({
1175
1191
  connections,
@@ -1529,7 +1545,9 @@ export class Orchestrator {
1529
1545
  agent: RosterAgent,
1530
1546
  base: Record<string, string>,
1531
1547
  ): Record<string, string> {
1532
- const account = pickEngineAccount(agent.kind);
1548
+ const account = pickEngineAccount(agent.kind, {
1549
+ scope: channel.engineAccountScope,
1550
+ });
1533
1551
  if (!account) {
1534
1552
  channel.accountByAgent.delete(agent.id);
1535
1553
  return base;
@@ -2598,7 +2616,7 @@ export class Orchestrator {
2598
2616
  );
2599
2617
  const boundAccountId = channel.accountByAgent.get(agentId);
2600
2618
  const boundAccount = boundAccountId
2601
- ? resolveEngineAccounts(agent.kind).find(
2619
+ ? resolveEngineAccounts(agent.kind, {}, channel.engineAccountScope).find(
2602
2620
  (account) => account.id === boundAccountId,
2603
2621
  )
2604
2622
  : undefined;
@@ -2667,7 +2685,9 @@ export class Orchestrator {
2667
2685
  // A concurrent terminal event for the same session is already being
2668
2686
  // handled by the path that owns this spawn slot.
2669
2687
  if (channel.spawning.has(agentId)) return true;
2670
- if (resolveEngineAccounts(agent.kind).length < 2) return false;
2688
+ if (resolveEngineAccounts(agent.kind, {}, channel.engineAccountScope).length < 2) {
2689
+ return false;
2690
+ }
2671
2691
 
2672
2692
  const budget = (channel.rotations.get(agentId) ?? 0) + 1;
2673
2693
  channel.rotations.set(agentId, budget);
@@ -2676,6 +2696,7 @@ export class Orchestrator {
2676
2696
  const current = channel.accountByAgent.get(agentId);
2677
2697
  if (current) cooldownEngineAccount(current);
2678
2698
  const next = pickEngineAccount(agent.kind, {
2699
+ scope: channel.engineAccountScope,
2679
2700
  exclude: current ? new Set([current]) : undefined,
2680
2701
  });
2681
2702
  if (!next) return false;
@@ -2918,7 +2939,7 @@ export class Orchestrator {
2918
2939
  return;
2919
2940
  }
2920
2941
 
2921
- const accounts = resolveEngineAccounts(agent.kind);
2942
+ const accounts = resolveEngineAccounts(agent.kind, {}, channel.engineAccountScope);
2922
2943
  const account =
2923
2944
  accounts.find((a) => a.id === channel.accountByAgent.get(agentId)) ??
2924
2945
  accounts[0];
@@ -231,12 +231,14 @@ export function recordTaskOwner(
231
231
  ownerEmail: string | null,
232
232
  ownerName: string | null,
233
233
  projectSlugs: string[],
234
+ engineAccountScope: string | null = null,
234
235
  ): void {
235
236
  upsertHostTask(taskId, {
236
237
  ownerUserId,
237
238
  ownerEmail,
238
239
  ownerName,
239
240
  projectSlugs: JSON.stringify(projectSlugs),
241
+ engineAccountScope,
240
242
  });
241
243
  }
242
244
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@runuai/host",
3
- "version": "0.9.99",
3
+ "version": "0.9.100",
4
4
  "description": "Uai host — runs ephemeral AI tasks in containers on a machine you control.",
5
5
  "license": "MIT",
6
6
  "author": "Uai Tech <team@runuai.com>",
package/src/index.ts CHANGED
@@ -768,6 +768,8 @@ export const hostCommands: HostCommands = {
768
768
  input.ownerEmail ?? null,
769
769
  input.ownerName ?? null,
770
770
  input.projects.map((p) => p.slug),
771
+ // ADR-131 D3: persisted so recovery re-provisions the same scope.
772
+ input.task.engineAccountScope ?? null,
771
773
  );
772
774
  // ADR-048: persist the cloud-issued per-task cli secret (host-private) so the
773
775
  // `uai` CLI's per-agent tokens can be minted now + after a host restart.
@@ -1227,7 +1229,7 @@ export const hostCommands: HostCommands = {
1227
1229
  async engineAccountRemove(ctx, input) {
1228
1230
  logCommand(ctx, "engineAccountRemove", input.id);
1229
1231
  try {
1230
- const result = removeEngineAccount(input.id);
1232
+ const result = removeEngineAccount(input.id, input.scope);
1231
1233
  if (!result.ok) {
1232
1234
  return ok({ removed: false, message: result.message });
1233
1235
  }
package/src/main.ts CHANGED
@@ -150,7 +150,7 @@ import {
150
150
  patchHostConfig,
151
151
  type HostConfigResult,
152
152
  } from "../lib/host-config";
153
- import { listEngineAccounts } from "../lib/engine-accounts";
153
+ import { listEngineAccountsAllScopes } from "../lib/engine-accounts";
154
154
  import { createEngineConnectManager } from "../lib/engine-connect";
155
155
  import { createEngineLoginManager } from "../lib/engine-login";
156
156
  import {
@@ -182,7 +182,9 @@ import {
182
182
  HOST_TASK_STOP_PROTOCOL_FEATURE,
183
183
  HOST_ENGINE_ACCOUNTS_PROTOCOL_FEATURE,
184
184
  HOST_ENGINE_CONNECT_PROTOCOL_FEATURE,
185
+ HOST_ENGINE_ACCOUNT_SCOPES_PROTOCOL_FEATURE,
185
186
  HOST_ENGINE_LOGIN_PROTOCOL_FEATURE,
187
+ isEngineAccountScope,
186
188
  HOST_LOGS_PROTOCOL_FEATURE,
187
189
  HOST_TASK_INVENTORY_PROTOCOL_FEATURE,
188
190
  MAX_ENGINE_ACCOUNT_LABEL_CHARS,
@@ -601,6 +603,7 @@ function buildCapabilities(): HostCapabilities {
601
603
  HOST_TASK_STOP_PROTOCOL_FEATURE,
602
604
  HOST_ENGINE_ACCOUNTS_PROTOCOL_FEATURE,
603
605
  HOST_ENGINE_CONNECT_PROTOCOL_FEATURE,
606
+ HOST_ENGINE_ACCOUNT_SCOPES_PROTOCOL_FEATURE,
604
607
  // The echo adapter cannot execute the in-task CLI. Advertising typed
605
608
  // dispatch in mock mode would let the composer create a Secretary that
606
609
  // has no way to wake crew.
@@ -696,13 +699,15 @@ function engineAccountSummaries(): EngineAccountSummary[] {
696
699
  const summaries: EngineAccountSummary[] = [];
697
700
  for (const kind of ["claude", "codex", "opencode"] as const) {
698
701
  try {
699
- for (const account of listEngineAccounts(kind)) {
702
+ // ADR-131 D3: every scope — the cloud filters per caller.
703
+ for (const account of listEngineAccountsAllScopes(kind)) {
700
704
  summaries.push({
701
705
  id: account.id,
702
706
  kind,
703
707
  label: account.label.slice(0, MAX_ENGINE_ACCOUNT_LABEL_CHARS),
704
708
  authKind: account.authKind,
705
709
  isDefault: account.isDefault,
710
+ scope: account.scope,
706
711
  });
707
712
  }
708
713
  } catch (error) {
@@ -1227,6 +1232,7 @@ async function connect(): Promise<void> {
1227
1232
  frame.engine,
1228
1233
  emitEngineLoginEvent,
1229
1234
  frame.label,
1235
+ frame.scope,
1230
1236
  );
1231
1237
  break;
1232
1238
  case "engine.login.input":
@@ -1247,6 +1253,7 @@ async function connect(): Promise<void> {
1247
1253
  frame.secret,
1248
1254
  frame.label,
1249
1255
  (event) => sendRemoteOperationFrame(event),
1256
+ frame.scope,
1250
1257
  );
1251
1258
  break;
1252
1259
  case "engine.connect.stop":
@@ -2434,7 +2441,7 @@ async function dispatchCommand(
2434
2441
  function expectEngineAccountRemoveInput(
2435
2442
  args: unknown[],
2436
2443
  index: number,
2437
- ): { id: string } {
2444
+ ): { id: string; scope?: string } {
2438
2445
  const value = args[index];
2439
2446
  if (
2440
2447
  !value ||
@@ -2445,7 +2452,14 @@ function expectEngineAccountRemoveInput(
2445
2452
  ) {
2446
2453
  throw new Error(`invalid command args: expected account id at ${index}`);
2447
2454
  }
2448
- return { id: (value as { id: string }).id };
2455
+ const scope = (value as { scope?: unknown }).scope;
2456
+ if (scope !== undefined && !isEngineAccountScope(scope)) {
2457
+ throw new Error(`invalid command args: bad account scope at ${index}`);
2458
+ }
2459
+ return {
2460
+ id: (value as { id: string }).id,
2461
+ ...(scope !== undefined ? { scope } : {}),
2462
+ };
2449
2463
  }
2450
2464
 
2451
2465
  function expectNumberArg(args: unknown[], index: number): number {
package/src/protocol.ts CHANGED
@@ -102,6 +102,25 @@ export const MAX_ENGINE_ACCOUNTS_ADVERTISED = 48;
102
102
  /** ADR-117: one-shot engine credentials over the bridge + the full engine
103
103
  * catalog in capabilities, so every engine renders on the cloud pane. */
104
104
  export const HOST_ENGINE_CONNECT_PROTOCOL_FEATURE = "host-engine-connect-v1";
105
+ /** ADR-131 Decision 3: engine accounts carry a scope — `host` (the owner's)
106
+ * or `org:<orgId>` (a workspace's account on a shared host). A host that
107
+ * advertises this accepts `scope` on engine.login.start / engine.connect.start
108
+ * / engineAccountRemove, `engineAccountScope` on channelEnsure and task-up,
109
+ * and stamps `scope` on every EngineAccountSummary it advertises. The cloud
110
+ * sends none of those to a host without the feature (the v1 exact-shape
111
+ * guards would reject the frames). */
112
+ export const HOST_ENGINE_ACCOUNT_SCOPES_PROTOCOL_FEATURE =
113
+ "host-engine-account-scopes-v1";
114
+ /** The owner-level account scope; every pre-scope account lives here. */
115
+ export const HOST_ACCOUNT_SCOPE = "host";
116
+ const ORG_ACCOUNT_SCOPE_RE = /^org:[A-Za-z0-9_-]{1,128}$/;
117
+ /** `host` or `org:<orgId>` — bounded, single-token, safe in every surface. */
118
+ export function isEngineAccountScope(value: unknown): value is string {
119
+ return (
120
+ value === HOST_ACCOUNT_SCOPE ||
121
+ (typeof value === "string" && ORG_ACCOUNT_SCOPE_RE.test(value))
122
+ );
123
+ }
105
124
  export const MAX_ENGINE_CONNECT_SECRET_CHARS = 8_192;
106
125
  export const MAX_ENGINE_CONNECT_LINE_CHARS = 512;
107
126
  export const MAX_ENGINE_CATALOG_ENTRIES = 8;
@@ -307,6 +326,10 @@ export interface EngineLoginStartFrame {
307
326
  * slot. Only sent to hosts advertising `host-engine-accounts-v1`; the v1
308
327
  * exact-shape guard on older hosts rejects frames carrying it. */
309
328
  label?: string;
329
+ /** ADR-131 D3: capture into this account scope (`org:<orgId>` on a shared
330
+ * host). Only sent to hosts advertising `host-engine-account-scopes-v1`;
331
+ * absent = the host scope. An org scope requires a label. */
332
+ scope?: string;
310
333
  }
311
334
 
312
335
  /** The only generic one-time response channel. Long-lived tokens must never
@@ -379,6 +402,9 @@ export interface EngineAccountSummary {
379
402
  label: string;
380
403
  authKind: "env" | "config-dir";
381
404
  isDefault: boolean;
405
+ /** ADR-131 D3: `host` or `org:<orgId>`. Absent from hosts that predate
406
+ * scopes — read as `host`. */
407
+ scope?: string;
382
408
  }
383
409
 
384
410
  /** ADR-117 engine kinds — every engine the host's descriptor table knows. */
@@ -416,6 +442,8 @@ export interface EngineConnectStartFrame {
416
442
  engine: EngineConnectKind;
417
443
  secret?: string;
418
444
  label?: string;
445
+ /** ADR-131 D3: see EngineLoginStartFrame.scope. */
446
+ scope?: string;
419
447
  }
420
448
 
421
449
  export interface EngineConnectStopFrame {
@@ -454,13 +482,14 @@ export function isEngineConnectStartFrame(
454
482
  const frame = exactWireObject(
455
483
  value,
456
484
  ["kind", "opId", "engine"],
457
- ["secret", "label"],
485
+ ["secret", "label", "scope"],
458
486
  );
459
487
  if (
460
488
  !frame ||
461
489
  frame.kind !== "engine.connect.start" ||
462
490
  !isHostOpId(frame.opId) ||
463
- !isEngineConnectKind(frame.engine)
491
+ !isEngineConnectKind(frame.engine) ||
492
+ (frame.scope !== undefined && !isEngineAccountScope(frame.scope))
464
493
  ) {
465
494
  return false;
466
495
  }
@@ -705,13 +734,18 @@ export function isHostLogsEndFrame(value: unknown): value is HostLogsEndFrame {
705
734
  export function isEngineLoginStartFrame(
706
735
  value: unknown,
707
736
  ): value is EngineLoginStartFrame {
708
- const frame = exactWireObject(value, ["kind", "opId", "engine"], ["label"]);
737
+ const frame = exactWireObject(
738
+ value,
739
+ ["kind", "opId", "engine"],
740
+ ["label", "scope"],
741
+ );
709
742
  return Boolean(
710
743
  frame &&
711
744
  frame.kind === "engine.login.start" &&
712
745
  isHostOpId(frame.opId) &&
713
746
  isEngineLoginKind(frame.engine) &&
714
- (frame.label === undefined || isEngineAccountLabel(frame.label)),
747
+ (frame.label === undefined || isEngineAccountLabel(frame.label)) &&
748
+ (frame.scope === undefined || isEngineAccountScope(frame.scope)),
715
749
  );
716
750
  }
717
751
 
@@ -1087,6 +1121,9 @@ export interface TaskCommandTask {
1087
1121
  previewEnv?: Record<string, string>;
1088
1122
  /** ADR-062: owning org — locates the org shared-files root on the host. */
1089
1123
  ownerOrgId?: string;
1124
+ /** ADR-131 D3: the engine-account scope the task's agents resolve
1125
+ * credentials from (`org:<orgId>` on a shared host). Absent = `host`. */
1126
+ engineAccountScope?: string;
1090
1127
  /** ADR-062: shared-files mount mode ("off" | "ro" | "rw"; default "ro"). */
1091
1128
  sharedFiles?: string;
1092
1129
  }
@@ -1188,6 +1225,10 @@ export interface ChannelEnsureInput {
1188
1225
  /** ADR-053: any joined project opted into browser testing — the host wires
1189
1226
  * the Playwright MCP browser at session start. */
1190
1227
  browserTesting?: boolean;
1228
+ /** ADR-131 D3: see TaskCommandTask.engineAccountScope — the channel's
1229
+ * agents pick accounts from this scope. Absent = the task's persisted
1230
+ * scope, else `host`. */
1231
+ engineAccountScope?: string;
1191
1232
  /** ADR-057: the owner's usable MCP connections (policy "on", connected,
1192
1233
  * remote). The host writes gateway-URL MCP configs at session start. */
1193
1234
  mcpConnections?: Array<{ id: string; slug: string }>;
@@ -1358,7 +1399,7 @@ export interface HostCommands {
1358
1399
  * exactly like the local API; re-advertises capabilities on success. */
1359
1400
  engineAccountRemove(
1360
1401
  ctx: CommandContext,
1361
- input: { id: string },
1402
+ input: { id: string; scope?: string },
1362
1403
  ): Promise<HostCommandResult<{ removed: boolean; message?: string }>>;
1363
1404
  cloneRepo(
1364
1405
  ctx: CommandContext,