shadok-ai 0.17.50 → 0.17.51

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/README.md CHANGED
@@ -570,12 +570,16 @@ in to Claude, which happens after boot; the banner stays up until then and the
570
570
  migration **finishes on its own the moment you sign in** (no restart needed).
571
571
  **One-time provisioning:** isolated-group agents authenticate with a
572
572
  subscription token injected into their environment, not a shared credential
573
- file. Until it is set, group spawns are refused with a message naming this step,
574
- and the cockpit shows a red "no subscription token" banner. Provide it from the
575
- cockpit itself — **no shell needed**: as an admin, click **Provide token** on
576
- that banner (or **Replace subscription token…** in the version menu to rotate
577
- it), authorise on your Claude subscription in the browser, and paste the code
578
- back; the server mints and stores it. From Telegram, `/mttoken` then
573
+ file. A fresh instance asks for it through the **Connect Claude** card that opens
574
+ after the welcome tour — **no shell needed**: as an admin, pick **1 month** (an
575
+ interactive login, the agents get your claude.ai connectors, one connection per
576
+ isolated space) or **1 year** (this long-lived token, model access only), click
577
+ **Open claude.ai**, authorise, and paste the code back; the server mints and
578
+ stores it. **I already have a token** takes one minted elsewhere with
579
+ `claude setup-token`. Rotate it later with **Replace subscription token…** in the
580
+ version menu. Until a space is connected, its spawns are refused (`code:
581
+ "space-not-connected"`): an admin gets the card for that space, a member is told
582
+ to ask an admin. From Telegram, `/mttoken` then
579
583
  `/mtcode <code>` do the same. The token is captured and vaulted server-side and
580
584
  is never shown. It is valid for about a year; re-run the card (or `/mttoken`)
581
585
  before it expires. The shell path still works as a fallback: `claude setup-token`
@@ -916,8 +920,8 @@ are **never held by the quota guard** (they don't spend your subscription).
916
920
 
917
921
  Three ways to do it:
918
922
 
919
- - **From the cockpit — the easy one.** The sign-in card a fresh instance opens
920
- has a second side, **Another model**: pick a provider (Ollama, a llama.cpp
923
+ - **From the cockpit — the easy one.** The Connect Claude card a fresh instance
924
+ opens has a **Use another model** link: pick a provider (Ollama, a llama.cpp
921
925
  server, DeepSeek, Z.ai/GLM, Moonshot/Kimi, or any Anthropic-compatible
922
926
  server), the address and model are pre-filled, the models a local server
923
927
  serves are listed for you, and **Test** sends one real request before
@@ -0,0 +1,47 @@
1
+ /**
2
+ * Can THIS agent authenticate to Claude? — the one question every spawn gate
3
+ * asks, answered from facts the caller gathers (pure, tested).
4
+ *
5
+ * It used to be two unrelated gates: every spawn required the instance's own
6
+ * (root) `claude auth login`, and a privilege-dropped agent additionally
7
+ * required the long-lived token. On a multi-tenant instance the dropped agent
8
+ * uses neither the root login nor, in "login" auth mode, the token — so a fresh
9
+ * hosted instance demanded TWO OAuth round-trips before its first agent, and a
10
+ * login-mode agent was refused for a token it would never use. The gate now
11
+ * checks only the credential the agent will actually run on:
12
+ *
13
+ * - custom model backend → nothing to check;
14
+ * - the server's own user (mono-tenant, or a commons not yet migrated) → the
15
+ * root sign-in;
16
+ * - a dropped user in "token" mode → the token;
17
+ * - a dropped user in "login" mode → that user's own login.
18
+ *
19
+ * Only an OBSERVED absence refuses (invariant 27): an unknown root state or an
20
+ * unread login lets the spawn through. Messages never carry a credential.
21
+ */
22
+ export type Connected = "yes" | "no" | "unknown";
23
+ export interface ConnectFacts {
24
+ multiTenant: boolean;
25
+ customBackend: boolean;
26
+ /** The OS user the agent will run as; null = the server's own user. */
27
+ dropUser: string | null;
28
+ agentAuth: "token" | "login";
29
+ /** MT_CLAUDE_OAUTH_TOKEN present in Main. */
30
+ hasToken: boolean;
31
+ rootAuth: "signed-in" | "signed-out" | "unknown";
32
+ /** `agentLoginInfo(home).loggedIn` for `dropUser`; null = not looked up. */
33
+ userLoggedIn: boolean | null;
34
+ }
35
+ export type ConnectVerdict = {
36
+ ok: true;
37
+ } | {
38
+ ok: false;
39
+ code: "logged-out" | "space-not-connected";
40
+ user: string | null;
41
+ message: string;
42
+ };
43
+ export declare const LOGGED_OUT_MESSAGE = "this shadok-ai instance is not signed in to Claude \u2014 sign in from the cockpit";
44
+ export declare const SPACE_NOT_CONNECTED_MESSAGE = "This space isn't connected to Claude yet \u2014 an admin can connect it from the cockpit.";
45
+ export declare function connectVerdict(f: ConnectFacts): ConnectVerdict;
46
+ /** The verdict as a three-valued state: "unknown" when the deciding fact was not observed. */
47
+ export declare function connectedState(f: ConnectFacts): Connected;
@@ -0,0 +1,49 @@
1
+ /**
2
+ * Can THIS agent authenticate to Claude? — the one question every spawn gate
3
+ * asks, answered from facts the caller gathers (pure, tested).
4
+ *
5
+ * It used to be two unrelated gates: every spawn required the instance's own
6
+ * (root) `claude auth login`, and a privilege-dropped agent additionally
7
+ * required the long-lived token. On a multi-tenant instance the dropped agent
8
+ * uses neither the root login nor, in "login" auth mode, the token — so a fresh
9
+ * hosted instance demanded TWO OAuth round-trips before its first agent, and a
10
+ * login-mode agent was refused for a token it would never use. The gate now
11
+ * checks only the credential the agent will actually run on:
12
+ *
13
+ * - custom model backend → nothing to check;
14
+ * - the server's own user (mono-tenant, or a commons not yet migrated) → the
15
+ * root sign-in;
16
+ * - a dropped user in "token" mode → the token;
17
+ * - a dropped user in "login" mode → that user's own login.
18
+ *
19
+ * Only an OBSERVED absence refuses (invariant 27): an unknown root state or an
20
+ * unread login lets the spawn through. Messages never carry a credential.
21
+ */
22
+ export const LOGGED_OUT_MESSAGE = "this shadok-ai instance is not signed in to Claude — sign in from the cockpit";
23
+ export const SPACE_NOT_CONNECTED_MESSAGE = "This space isn't connected to Claude yet — an admin can connect it from the cockpit.";
24
+ export function connectVerdict(f) {
25
+ if (f.customBackend)
26
+ return { ok: true };
27
+ if (f.dropUser === null) {
28
+ return f.rootAuth === "signed-out"
29
+ ? { ok: false, code: "logged-out", user: null, message: LOGGED_OUT_MESSAGE }
30
+ : { ok: true };
31
+ }
32
+ const missing = f.agentAuth === "token" ? !f.hasToken : f.userLoggedIn === false;
33
+ return missing
34
+ ? { ok: false, code: "space-not-connected", user: f.dropUser, message: SPACE_NOT_CONNECTED_MESSAGE }
35
+ : { ok: true };
36
+ }
37
+ /** The verdict as a three-valued state: "unknown" when the deciding fact was not observed. */
38
+ export function connectedState(f) {
39
+ if (!connectVerdict(f).ok)
40
+ return "no";
41
+ if (f.customBackend)
42
+ return "yes";
43
+ if (f.dropUser === null)
44
+ return f.rootAuth === "unknown" ? "unknown" : "yes";
45
+ if (f.agentAuth === "login" && f.userLoggedIn === null)
46
+ return "unknown";
47
+ return "yes";
48
+ }
49
+ //# sourceMappingURL=connect-gate.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"connect-gate.js","sourceRoot":"","sources":["../src/connect-gate.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;GAoBG;AAqBH,MAAM,CAAC,MAAM,kBAAkB,GAC7B,+EAA+E,CAAC;AAClF,MAAM,CAAC,MAAM,2BAA2B,GACtC,sFAAsF,CAAC;AAEzF,MAAM,UAAU,cAAc,CAAC,CAAe;IAC5C,IAAI,CAAC,CAAC,aAAa;QAAE,OAAO,EAAE,EAAE,EAAE,IAAI,EAAE,CAAC;IACzC,IAAI,CAAC,CAAC,QAAQ,KAAK,IAAI,EAAE,CAAC;QACxB,OAAO,CAAC,CAAC,QAAQ,KAAK,YAAY;YAChC,CAAC,CAAC,EAAE,EAAE,EAAE,KAAK,EAAE,IAAI,EAAE,YAAY,EAAE,IAAI,EAAE,IAAI,EAAE,OAAO,EAAE,kBAAkB,EAAE;YAC5E,CAAC,CAAC,EAAE,EAAE,EAAE,IAAI,EAAE,CAAC;IACnB,CAAC;IACD,MAAM,OAAO,GAAG,CAAC,CAAC,SAAS,KAAK,OAAO,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,QAAQ,CAAC,CAAC,CAAC,CAAC,CAAC,YAAY,KAAK,KAAK,CAAC;IACjF,OAAO,OAAO;QACZ,CAAC,CAAC,EAAE,EAAE,EAAE,KAAK,EAAE,IAAI,EAAE,qBAAqB,EAAE,IAAI,EAAE,CAAC,CAAC,QAAQ,EAAE,OAAO,EAAE,2BAA2B,EAAE;QACpG,CAAC,CAAC,EAAE,EAAE,EAAE,IAAI,EAAE,CAAC;AACnB,CAAC;AAED,8FAA8F;AAC9F,MAAM,UAAU,cAAc,CAAC,CAAe;IAC5C,IAAI,CAAC,cAAc,CAAC,CAAC,CAAC,CAAC,EAAE;QAAE,OAAO,IAAI,CAAC;IACvC,IAAI,CAAC,CAAC,aAAa;QAAE,OAAO,KAAK,CAAC;IAClC,IAAI,CAAC,CAAC,QAAQ,KAAK,IAAI;QAAE,OAAO,CAAC,CAAC,QAAQ,KAAK,SAAS,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,KAAK,CAAC;IAC7E,IAAI,CAAC,CAAC,SAAS,KAAK,OAAO,IAAI,CAAC,CAAC,YAAY,KAAK,IAAI;QAAE,OAAO,SAAS,CAAC;IACzE,OAAO,KAAK,CAAC;AACf,CAAC"}
@@ -1,4 +1,4 @@
1
- import { type AuthState } from "./claude-auth.js";
1
+ import type { Connected } from "./connect-gate.js";
2
2
  /**
3
3
  * The lead agent an instance starts life with.
4
4
  *
@@ -18,6 +18,21 @@ export declare function countMainChannels(channels: ReadonlyArray<{
18
18
  group?: string | null;
19
19
  }>): number;
20
20
  export declare const FIRST_AGENT_NAME = "general";
21
+ /**
22
+ * Pure: the `start` the lead agent is spawned with. The launch directory and no
23
+ * worktree — this is the main channel, not one of the isolated agents it will go
24
+ * on to spawn. And an EXPLICIT `group: Main`: the spawn is made over the
25
+ * loopback as the bootstrap admin, and on a multi-tenant instance a spawn with no
26
+ * group lands in its creator's private group — the lead agent then lived in the
27
+ * admin's Personal, where nobody else could see it. Mono-tenant ignores the field.
28
+ */
29
+ export declare function firstAgentStartMessage(cwd: string, profile: string | undefined): {
30
+ type: "start";
31
+ cwd: string;
32
+ profile: string | undefined;
33
+ origin: string;
34
+ group: string;
35
+ };
21
36
  export interface FirstAgentPlan {
22
37
  spawn: boolean;
23
38
  reason: "first-boot" | "channels-exist" | "not-signed-in";
@@ -36,7 +51,8 @@ export declare function firstAgentPlan(input: {
36
51
  * the user launches its first agent on demand, so a brand-new private group
37
52
  * must never read as "no channel, spawn a lead". */
38
53
  mainChannelCount: number;
39
- authState: AuthState;
54
+ /** Can the agent this spawns authenticate (src/connect-gate.ts)? */
55
+ connected: Connected;
40
56
  /** The whole instance runs on a custom model backend (src/backend.ts): its
41
57
  * agents carry their own token, so the Claude sign-in is irrelevant. */
42
58
  customBackend?: boolean;
@@ -95,6 +111,9 @@ export declare function ensureFirstAgent(deps: {
95
111
  /** The instance runs on a custom model backend (src/backend.ts) — decided by
96
112
  * the server, which owns both the env and the saved choice. */
97
113
  customBackend?: boolean;
114
+ /** Whether the commons' first agent could authenticate (src/connect-gate.ts),
115
+ * computed by the server, which owns the facts (auth mode, token, logins). */
116
+ connected: () => Promise<Connected>;
98
117
  /** Called with the new session id once the server reports it ready. */
99
118
  onReady: (sessionId: string, name: string) => void;
100
119
  }): Promise<FirstAgentPlan["reason"]>;
@@ -1,7 +1,6 @@
1
1
  import { MAIN_GROUP_ID } from "./groups.js";
2
2
  import WebSocket from "ws";
3
3
  import { loadChannels } from "./channels.js";
4
- import { authStatus } from "./claude-auth.js";
5
4
  import { BOSS_PROFILE_NAME } from "./profiles.js";
6
5
  /**
7
6
  * The lead agent an instance starts life with.
@@ -22,6 +21,17 @@ export function countMainChannels(channels) {
22
21
  return channels.filter((c) => c.group == null || c.group === MAIN_GROUP_ID).length;
23
22
  }
24
23
  export const FIRST_AGENT_NAME = "general";
24
+ /**
25
+ * Pure: the `start` the lead agent is spawned with. The launch directory and no
26
+ * worktree — this is the main channel, not one of the isolated agents it will go
27
+ * on to spawn. And an EXPLICIT `group: Main`: the spawn is made over the
28
+ * loopback as the bootstrap admin, and on a multi-tenant instance a spawn with no
29
+ * group lands in its creator's private group — the lead agent then lived in the
30
+ * admin's Personal, where nobody else could see it. Mono-tenant ignores the field.
31
+ */
32
+ export function firstAgentStartMessage(cwd, profile) {
33
+ return { type: "start", cwd, profile, origin: "boot", group: MAIN_GROUP_ID };
34
+ }
25
35
  /**
26
36
  * Pure: should this instance start its lead agent?
27
37
  *
@@ -36,7 +46,7 @@ export function firstAgentPlan(input) {
36
46
  return { spawn: true, reason: "first-boot", name: FIRST_AGENT_NAME, profile: BOSS_PROFILE_NAME };
37
47
  // "unknown" is not "signed in": the probe failed. Waiting costs one boot,
38
48
  // guessing costs an agent with no credentials — the zombie shape (invariant 27).
39
- if (input.authState !== "signed-in")
49
+ if (input.connected !== "yes")
40
50
  return { spawn: false, reason: "not-signed-in" };
41
51
  return { spawn: true, reason: "first-boot", name: FIRST_AGENT_NAME, profile: BOSS_PROFILE_NAME };
42
52
  }
@@ -85,7 +95,7 @@ export async function ensureFirstAgent(deps) {
85
95
  const plan = firstAgentPlan({
86
96
  mainChannelCount: countMainChannels(loadChannels()),
87
97
  // No probe when it cannot change the answer (~850ms, and a process spawn).
88
- authState: customBackend ? "unknown" : (await authStatus()).state,
98
+ connected: customBackend ? "unknown" : await deps.connected(),
89
99
  customBackend,
90
100
  });
91
101
  if (!plan.spawn) {
@@ -117,14 +127,7 @@ export async function ensureFirstAgent(deps) {
117
127
  };
118
128
  const guard = setTimeout(finish, 60_000);
119
129
  guard.unref?.();
120
- ws.on("open", () => ws.send(JSON.stringify({
121
- type: "start",
122
- // The launch directory, and no worktree: this is the main channel,
123
- // not one of the isolated agents it will go on to spawn.
124
- cwd: deps.cwd,
125
- profile: plan.profile,
126
- origin: "boot",
127
- })));
130
+ ws.on("open", () => ws.send(JSON.stringify(firstAgentStartMessage(deps.cwd, plan.profile))));
128
131
  ws.on("message", (raw) => {
129
132
  let m;
130
133
  try {
@@ -1 +1 @@
1
- {"version":3,"file":"first-agent.js","sourceRoot":"","sources":["../src/first-agent.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AAC5C,OAAO,SAAS,MAAM,IAAI,CAAC;AAC3B,OAAO,EAAE,YAAY,EAAE,MAAM,eAAe,CAAC;AAC7C,OAAO,EAAE,UAAU,EAAkB,MAAM,kBAAkB,CAAC;AAC9D,OAAO,EAAE,iBAAiB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AC,CAAC;YACvB,EAAE,CAAC,EAAE,CAAC,OAAO,EAAE,MAAM,CAAC,CAAC;QACzB,CAAC,CAAC,CAAC;IACL,CAAC;YAAS,CAAC;QACT,QAAQ,GAAG,KAAK,CAAC;QACjB,0EAA0E;QAC1E,0EAA0E;QAC1E,4EAA4E;QAC5E,4EAA4E;QAC5E,gBAAgB,CAAC,YAAY,CAAC,CAAC;IACjC,CAAC;IACD,OAAO,YAAY,CAAC;AACtB,CAAC"}
package/dist/server.js CHANGED
@@ -26,6 +26,8 @@ import { PtyPilot } from "./session.js";
26
26
  import { ensureClaudeHome, ensureProjectTrusted, getDefaultModel, setDefaultModel, parseClaudeVersion, seedPlanForCwds, settingsPlan, } from "./claude-home.js";
27
27
  import { mergeAppendedPrompts } from "./prompt-args.js";
28
28
  import { authStatus, cancelLogin, invalidateAuthStatus, startLogin, submitLoginCode } from "./claude-auth.js";
29
+ import { connectVerdict, connectedState } from "./connect-gate.js";
30
+ import { normalizePastedToken } from "./token-paste.js";
29
31
  import { startSetupToken, submitSetupTokenCode, cancelSetupToken } from "./setup-token.js";
30
32
  import { startAgentLogin, submitAgentLoginCode, cancelAgentLogin, agentLoginPending, agentLoginInfo, } from "./agent-login.js";
31
33
  import { readTokenExpiry } from "./claude-creds.js";
@@ -92,7 +94,7 @@ import { pctFromUsage, windowForModel } from "./context.js";
92
94
  import { BACKEND_PRESETS, backendEnv, backendFor, backendSaveVerdict, instanceEnv, joinUrl, looksLikeMessage, parseModelList, testFailure, testRequestBody, } from "./backend.js";
93
95
  import { availableModels, MODEL_FAMILIES } from "./claude-models.js";
94
96
  import { startHeartbeat } from "./heartbeat.js";
95
- import { ensureClaude, claudeInstallInProgress, claudeCommand, classifyBin, findClaudeBinWithRetry, startWithBusyRetry, liveClaudeDeps, rememberClaudeBin, resolveBin, sampleBin, mtCredentialMessage, mtTokenNeeded, } from "./claude-bin.js";
97
+ import { ensureClaude, claudeInstallInProgress, claudeCommand, classifyBin, findClaudeBinWithRetry, startWithBusyRetry, liveClaudeDeps, rememberClaudeBin, resolveBin, sampleBin, } from "./claude-bin.js";
96
98
  import { ensureTmux, tmuxInstallCommand } from "./tmux-install.js";
97
99
  import { cspHeader, injectNonce, NONCE_PLACEHOLDER, injectAssetVersion, injectInstanceKey } from "./csp.js";
98
100
  const __dirname = path.dirname(fileURLToPath(import.meta.url));
@@ -318,6 +320,7 @@ async function startFirstAgent() {
318
320
  cookie: tgCookie(),
319
321
  cwd: process.cwd(),
320
322
  customBackend: instanceBackend().kind === "custom",
323
+ connected: async () => connectedState(await commonsConnectFacts()),
321
324
  // `start` carries no name, so the channel is named once the server has
322
325
  // told us its session id.
323
326
  onReady: (sessionId, name) => {
@@ -1936,13 +1939,17 @@ app.get("/version", (_req, res) => res.json(versionState()));
1936
1939
  // (src/backend.ts): the page then never opens the sign-in card, since no agent
1937
1940
  // here needs the subscription. The probe still runs — a mixed setup's
1938
1941
  // subscription agents still need to know.
1939
- app.get("/auth", async (_req, res) => res.json({
1940
- ...(await authStatus()),
1941
- ...readTokenExpiry(),
1942
- ...longLivedTokenInfo(loadVault(), DEPLOYMENT_MODE),
1943
- ...customBackendFields(),
1944
- ...mtTokenFields(),
1945
- }));
1942
+ app.get("/auth", async (_req, res) => {
1943
+ const expiry = readTokenExpiry();
1944
+ res.json({
1945
+ ...(await authStatus()),
1946
+ ...expiry,
1947
+ ...longLivedTokenInfo(loadVault(), DEPLOYMENT_MODE),
1948
+ ...customBackendFields(),
1949
+ ...mtTokenFields(),
1950
+ ...(await connectFields(expiry)),
1951
+ });
1952
+ });
1946
1953
  /**
1947
1954
  * Whether this is a multi-tenant instance and, if so, whether its group agents'
1948
1955
  * subscription token is still missing — the signal the cockpit uses to offer the
@@ -1954,6 +1961,43 @@ function mtTokenFields() {
1954
1961
  const present = !!secretsFor([MT_CLAUDE_OAUTH_TOKEN_NAME], MAIN_GROUP_ID)[MT_CLAUDE_OAUTH_TOKEN_NAME];
1955
1962
  return { multiTenant, mtTokenMissing: multiTenant && !present };
1956
1963
  }
1964
+ /**
1965
+ * The connect facts for the COMMONS' agents — where the first agent is born —
1966
+ * read by the first-agent plan and by `/auth` (the cockpit's "Connect Claude"
1967
+ * card). Same inputs as the spawn gate's `connectRefusal`, for the commons user.
1968
+ */
1969
+ async function commonsConnectFacts() {
1970
+ const user = commonsOsUser({ migrated: groupsMigrated, mode: DEPLOYMENT_MODE }) ?? null;
1971
+ const agentAuth = agentAuthForCwd(loadConfig(), process.cwd());
1972
+ const customBackend = instanceBackend().kind === "custom";
1973
+ return {
1974
+ multiTenant: DEPLOYMENT_MODE === "multi-tenant",
1975
+ customBackend,
1976
+ dropUser: user,
1977
+ agentAuth,
1978
+ hasToken: !!secretsFor([MT_CLAUDE_OAUTH_TOKEN_NAME], MAIN_GROUP_ID)[MT_CLAUDE_OAUTH_TOKEN_NAME],
1979
+ rootAuth: user === null && !customBackend ? (await authStatus()).state : "unknown",
1980
+ userLoggedIn: user !== null && agentAuth === "login" ? agentLoginInfo(agentStateHome(user)).loggedIn : null,
1981
+ };
1982
+ }
1983
+ /**
1984
+ * What the cockpit's "Connect Claude" card reads (`/auth` → `connect`): is the
1985
+ * commons connected, which mode, which OS user a "1 month" login targets, and
1986
+ * until when the credential in use lasts (null when unknown).
1987
+ */
1988
+ async function connectFields(auth) {
1989
+ const f = await commonsConnectFacts();
1990
+ let expiresAt = null;
1991
+ if (f.dropUser === null)
1992
+ expiresAt = auth.tokenExpiresAt;
1993
+ else if (f.agentAuth === "login")
1994
+ expiresAt = agentLoginInfo(agentStateHome(f.dropUser)).expiresAt;
1995
+ else
1996
+ expiresAt = longLivedTokenInfo(loadVault(), DEPLOYMENT_MODE).longLivedExpiresAt;
1997
+ return {
1998
+ connect: { state: connectedState(f), multiTenant: f.multiTenant, agentAuth: f.agentAuth, user: f.dropUser, expiresAt },
1999
+ };
2000
+ }
1957
2001
  function customBackendFields() {
1958
2002
  const b = instanceBackend();
1959
2003
  return b.kind === "custom" ? { backend: "custom", backendModel: b.model } : {};
@@ -2063,7 +2107,39 @@ app.post("/mt-token/code", async (req, res) => {
2063
2107
  invalidateAuthStatus(); // so /auth re-reports longLived immediately
2064
2108
  }
2065
2109
  res.status(r.ok ? 200 : 400).json(r); // {ok} — never the token
2110
+ if (r.ok)
2111
+ afterConnected();
2066
2112
  });
2113
+ // "I already have a token": a long-lived token minted elsewhere with
2114
+ // `claude setup-token`, pasted on the Connect Claude card. Same gate and same
2115
+ // vault slot as the in-cockpit mint; choosing it also means "1 year", so the
2116
+ // auth mode follows (agents restart only if it actually changed).
2117
+ app.post("/mt-token/paste", (req, res) => {
2118
+ if (!mtTokenGate(req, res))
2119
+ return;
2120
+ const r = normalizePastedToken(req.body?.token);
2121
+ if (!r.ok)
2122
+ return res.status(400).json({ ok: false, error: r.error });
2123
+ setSecret(MT_CLAUDE_OAUTH_TOKEN_NAME, r.token, MAIN_GROUP_ID, "operator:paste");
2124
+ mtTokenWarned = false;
2125
+ invalidateAuthStatus();
2126
+ const cfg = loadConfig();
2127
+ if (agentAuthForCwd(cfg, process.cwd()) !== "token") {
2128
+ setAgentAuthForCwd(cfg, process.cwd(), "token");
2129
+ restartAllSessions();
2130
+ }
2131
+ res.json({ ok: true }); // never the token
2132
+ afterConnected();
2133
+ });
2134
+ /**
2135
+ * A connection just landed (token minted or pasted, commons login): this is
2136
+ * where a fresh multi-tenant instance's lead agent is really born, exactly as
2137
+ * `/auth/code` does for the root sign-in. Called AFTER answering the browser.
2138
+ */
2139
+ function afterConnected() {
2140
+ void startFirstAgent();
2141
+ void maybeRunGroupsMigration("post-sign-in");
2142
+ }
2067
2143
  app.delete("/mt-token", (req, res) => {
2068
2144
  // Same gate as start/code: a cancel is still a write on a credential flow, so
2069
2145
  // a non-admin/non-browser caller must not be able to kill an admin's live
@@ -2140,6 +2216,9 @@ app.post("/agent-login/code", async (req, res) => {
2140
2216
  return res.status(400).json({ error: "unknown user" });
2141
2217
  const r = await submitAgentLoginCode(user, code);
2142
2218
  res.status(r.ok ? 200 : 400).json(r); // {ok} — never the credential
2219
+ // Connecting the commons is how a "1 month" instance gets its lead agent.
2220
+ if (r.ok && user === commonsOsUser({ migrated: groupsMigrated, mode: DEPLOYMENT_MODE }))
2221
+ afterConnected();
2143
2222
  });
2144
2223
  app.delete("/agent-login", (req, res) => {
2145
2224
  if (!mtTokenGate(req, res))
@@ -7599,7 +7678,7 @@ wss.on("connection", (ws, req) => {
7599
7678
  // `code` is optional and purely additive: it lets a machine client (the cron
7600
7679
  // driver) tell "the session is busy" — a transient miss worth replaying —
7601
7680
  // apart from any other refusal, without matching on the message text.
7602
- const fail = (message, code) => send({ type: "error", message, ...(code ? { code } : {}) });
7681
+ const fail = (message, code, user) => send({ type: "error", message, ...(code ? { code } : {}), ...(user ? { user } : {}) });
7603
7682
  // ACL backstop on every per-turn DRIVE action (prompt, dialog answers, keys,
7604
7683
  // restart, set-*, stop): may THIS caller see/drive the session's group? The
7605
7684
  // spawn/resume path already gates with `canResumeAs`, but a socket attached to
@@ -7690,21 +7769,10 @@ wss.on("connection", (ws, req) => {
7690
7769
  // never touches the subscription, so the instance's sign-in is not
7691
7770
  // its business. The profile is resolved early (and cheaply) for this
7692
7771
  // alone; a resume we cannot match falls back to the probe as before.
7693
- if (sessionBackend(gateProfile(msg)).kind === "custom") {
7694
- console.log(`auth: custom model backend, sign-in not required`);
7695
- }
7696
- else {
7697
- const auth = await authStatus();
7698
- if (auth.state === "unknown")
7699
- console.log(`auth: could not verify sign-in state, allowing the spawn anyway`);
7700
- if (auth.state === "signed-out") {
7701
- // Telling the user is the whole point: a cron refused at 4am must
7702
- // not be discovered a day later. Deduplicated inside, so a
7703
- // five-minute cron does not turn one sign-out into a flood.
7704
- announceLoggedOut();
7705
- return fail("this shadok-ai instance is not signed in to Claude — sign in from the cockpit", "logged-out");
7706
- }
7707
- }
7772
+ // WHICH credential this agent needs is only known once its OS user is
7773
+ // resolved below, so the refusal itself lives in `connectRefusal`
7774
+ // (src/connect-gate.ts): a dropped multi-tenant agent no longer needs the
7775
+ // instance's root sign-in, only the token or its own space's login.
7708
7776
  origin = connectionOrigin({
7709
7777
  systemDrive: isSystemDrive,
7710
7778
  telegramBridge: isTelegramBridge,
@@ -7784,13 +7852,36 @@ wss.on("connection", (ws, req) => {
7784
7852
  // worktree/branch behind (a token-less retry loop would otherwise pile up
7785
7853
  // empty checkouts). Keyed on the same `dropUser` the spawn will use; the
7786
7854
  // late call below re-checks the (resume / live-attach) paths unchanged.
7787
- const mtRefusal = (dropUser) => {
7788
- const m = mtCredentialMessage(mtTokenNeeded(!!dropUser, sessionBackend(gateProfile(msg)).kind === "custom"), !!secretsFor([MT_CLAUDE_OAUTH_TOKEN_NAME], MAIN_GROUP_ID)[MT_CLAUDE_OAUTH_TOKEN_NAME]);
7789
- if (m && !mtTokenWarned) {
7855
+ const connectRefusal = async (dropUser) => {
7856
+ const customBackend = sessionBackend(gateProfile(msg)).kind === "custom";
7857
+ const user = dropUser ?? null;
7858
+ const agentAuth = agentAuthForCwd(loadConfig(), process.cwd());
7859
+ // Probe only what decides: the root sign-in is a ~850ms process spawn,
7860
+ // and a dropped agent never runs on it.
7861
+ const rootAuth = !customBackend && user === null ? (await authStatus()).state : "unknown";
7862
+ if (rootAuth === "unknown" && user === null && !customBackend)
7863
+ console.log(`auth: could not verify sign-in state, allowing the spawn anyway`);
7864
+ const v = connectVerdict({
7865
+ multiTenant: DEPLOYMENT_MODE === "multi-tenant",
7866
+ customBackend,
7867
+ dropUser: user,
7868
+ agentAuth,
7869
+ hasToken: !!secretsFor([MT_CLAUDE_OAUTH_TOKEN_NAME], MAIN_GROUP_ID)[MT_CLAUDE_OAUTH_TOKEN_NAME],
7870
+ rootAuth,
7871
+ userLoggedIn: user !== null && agentAuth === "login" ? agentLoginInfo(agentStateHome(user)).loggedIn : null,
7872
+ });
7873
+ if (v.ok)
7874
+ return null;
7875
+ if (v.code === "logged-out") {
7876
+ // Telling the user is the whole point: a cron refused at 4am must
7877
+ // not be discovered a day later. Deduplicated inside.
7878
+ announceLoggedOut();
7879
+ }
7880
+ else if (!mtTokenWarned) {
7790
7881
  mtTokenWarned = true;
7791
- console.error(`mt: ${m}`);
7882
+ console.error(`connect: ${v.user} — ${v.message}`);
7792
7883
  }
7793
- return m ?? null;
7884
+ return { message: v.message, code: v.code, user: v.user };
7794
7885
  };
7795
7886
  // The drop user a NEW spawn will run as — same inputs as the isolation
7796
7887
  // resolution further down. Hoisted out of the MT-token guard because the
@@ -7819,9 +7910,9 @@ wss.on("connection", (ws, req) => {
7819
7910
  parentGroupId,
7820
7911
  });
7821
7912
  earlyUser = earlyIso.user ?? commonsOsUser({ migrated: groupsMigrated, mode: DEPLOYMENT_MODE });
7822
- const earlyMsg = mtRefusal(earlyUser);
7823
- if (earlyMsg)
7824
- return fail(earlyMsg);
7913
+ const early = await connectRefusal(earlyUser);
7914
+ if (early)
7915
+ return fail(early.message, early.code, early.user);
7825
7916
  }
7826
7917
  if (msg.worktree && !resumed && isGitRepo(cwd)) {
7827
7918
  try {
@@ -8026,9 +8117,9 @@ wss.on("connection", (ws, req) => {
8026
8117
  // handed to makePilot — and skipped for a custom backend, which uses its
8027
8118
  // own key and never the subscription. Without the token, say so plainly
8028
8119
  // instead of letting the spawn die on a bare auth error.
8029
- const mtMsg = mtRefusal(dropUser);
8030
- if (mtMsg)
8031
- return fail(mtMsg);
8120
+ const refused = await connectRefusal(dropUser);
8121
+ if (refused)
8122
+ return fail(refused.message, refused.code, refused.user);
8032
8123
  // Who this new agent belongs to, for factory skill scopes: the person
8033
8124
  // spawning it (an agent's spawn inherits its parent's creator, so a
8034
8125
  // lead's ticket agents stay "yours"), and the cockpit group the client