trantor 0.18.163 → 0.18.165

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.
@@ -6,14 +6,14 @@
6
6
  },
7
7
  "metadata": {
8
8
  "description": "Trantor — the hub-world for AI agent crews: live message bus, presence, project Kanban/flow board + context-handoff for independent AI coding agents (Claude, Codex, Gemini, …)",
9
- "version": "0.18.163"
9
+ "version": "0.18.165"
10
10
  },
11
11
  "plugins": [
12
12
  {
13
13
  "name": "trantor",
14
14
  "source": "./",
15
15
  "description": "The hub-world for AI agent crews. Say \"fire up the crew\" and Claude becomes the architect: a plan-aware Advisor routes the work (solo / cheap inline calls / live crew of Codex, GLM, Kimi & DeepSeek in their own terminal windows), a Kanban/flow command center with a testing gate tracks it, and an economics brain (Scrooge) keeps the receipts. Includes the relay MCP, a SessionStart auto-discovery hook, and a PreCompact context-handoff so a fresh session can take over a full window instead of compacting.",
16
- "version": "0.18.163",
16
+ "version": "0.18.165",
17
17
  "author": {
18
18
  "name": "Sasha Bogojevic"
19
19
  },
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "trantor",
3
- "version": "0.18.163",
3
+ "version": "0.18.165",
4
4
  "description": "Trantor — the hub-world for AI agent crews: live message bus, presence, project Kanban/flow board + crew orchestration for independent AI coding agents (Claude, Codex, Gemini, Kimi, DeepSeek)",
5
5
  "mcpServers": {
6
6
  "relay": {
package/kimi.plugin.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "trantor",
3
- "version": "0.18.163",
3
+ "version": "0.18.165",
4
4
  "description": "Trantor — the hub-world for AI agent crews: live message bus, presence, project Kanban/flow board + crew orchestration for independent AI coding agents (Claude, Codex, Gemini, Kimi, DeepSeek). This manifest makes Kimi Code CLI a first-class ORCHESTRATOR, mirroring .claude-plugin/plugin.json. Hooks are the CANONICAL hooks/** executed through the kimi dialect bridge (kimi/bridge.mjs) — docs/KIMI-BRIDGE-CONTRACT.md.",
5
5
  "interface": {
6
6
  "displayName": "Trantor",
package/lib/balances.mjs CHANGED
@@ -1,13 +1,105 @@
1
- // trantor provider credit — read-only "how much is left" per provider, keys from the environment.
1
+ // trantor provider credit — "how much is left" per provider, keys from the environment.
2
2
  // Two kinds of left: prepaid (a balance) and quota (a window that resets); docs/CONTRACT-lib.md §balances.
3
3
 
4
- import { readFileSync } from "node:fs";
5
- import { join } from "node:path";
4
+ import { chmodSync, readFileSync, renameSync, rmSync, statSync, writeFileSync } from "node:fs";
5
+ import { basename, dirname, join } from "node:path";
6
6
  import { homedir } from "node:os";
7
+ import { randomUUID } from "node:crypto";
7
8
 
8
9
  import { readProviderIdentity } from "./dispatcher/accounts.mjs";
9
10
 
10
11
  const TIMEOUT = 8000;
12
+ const KIMI_CLIENT_ID = "17e5f671-d194-4dfb-9706-5516cb48c098";
13
+ const KIMI_REGIONS = {
14
+ "mainland-cn": { oauthHost: "https://auth.kimi.com", baseUrl: "https://api.kimi.com/coding/v1" },
15
+ global: { oauthHost: "https://auth.kimi.ai", baseUrl: "https://api.kimi.ai/coding/v1" },
16
+ };
17
+
18
+ function kimiTokenRegion(token) {
19
+ const payload = String(token || "").split(".")[1];
20
+ if (!payload) return null;
21
+ try {
22
+ const issuer = JSON.parse(Buffer.from(payload, "base64url").toString("utf8")).iss;
23
+ const host = new URL(issuer).hostname;
24
+ if (host === "auth.kimi.ai") return "global";
25
+ if (host === "auth.kimi.com") return "mainland-cn";
26
+ } catch {}
27
+ return null;
28
+ }
29
+
30
+ export function kimiOAuthRegion(credentials, env = {}, home = homedir()) {
31
+ const fromToken = kimiTokenRegion(credentials?.access_token);
32
+ if (fromToken) return fromToken;
33
+ for (const value of [env.KIMI_CODE_OAUTH_HOST, env.KIMI_OAUTH_HOST, env.KIMI_CODE_BASE_URL]) {
34
+ try {
35
+ const host = new URL(value).hostname;
36
+ if (host === "auth.kimi.ai" || host === "api.kimi.ai") return "global";
37
+ if (host === "auth.kimi.com" || host === "api.kimi.com") return "mainland-cn";
38
+ } catch {}
39
+ }
40
+ try {
41
+ const marker = readFileSync(join(home, ".kimi-code", "region"), "utf8").trim();
42
+ if (marker === "global" || marker === "mainland-cn") return marker;
43
+ } catch {}
44
+ return "mainland-cn";
45
+ }
46
+
47
+ function writeKimiCredentials(credentialPath, credentials) {
48
+ const mode = statSync(credentialPath).mode & 0o7777;
49
+ const temporary = join(dirname(credentialPath), `.${basename(credentialPath)}.${process.pid}.${randomUUID()}.tmp`);
50
+ try {
51
+ writeFileSync(temporary, `${JSON.stringify(credentials, null, 2)}\n`, { mode });
52
+ chmodSync(temporary, mode);
53
+ renameSync(temporary, credentialPath);
54
+ } catch (error) {
55
+ rmSync(temporary, { force: true });
56
+ throw new Error(`Kimi Code token refreshed but credentials could not be saved: ${error.message}`);
57
+ }
58
+ }
59
+
60
+ async function refreshKimiCredentials(credentials, credentialPath, env, home) {
61
+ const region = kimiOAuthRegion(credentials, env, home);
62
+ const oauthHost = String(env.KIMI_CODE_OAUTH_HOST || env.KIMI_OAUTH_HOST || KIMI_REGIONS[region].oauthHost).replace(/\/+$/, "");
63
+ let response;
64
+ try {
65
+ response = await fetch(`${oauthHost}/api/oauth/token`, {
66
+ method: "POST",
67
+ headers: { "content-type": "application/x-www-form-urlencoded", Accept: "application/json" },
68
+ body: new URLSearchParams({
69
+ client_id: KIMI_CLIENT_ID,
70
+ grant_type: "refresh_token",
71
+ refresh_token: credentials.refresh_token,
72
+ }),
73
+ signal: AbortSignal.timeout(TIMEOUT),
74
+ });
75
+ } catch (error) {
76
+ throw new Error(`Kimi Code token refresh failed: ${error.message}`);
77
+ }
78
+ const text = await response.text();
79
+ let body; try { body = JSON.parse(text); } catch { body = null; }
80
+ if (!response.ok) {
81
+ const code = body?.error;
82
+ const rejected = response.status === 400 || response.status === 401 || response.status === 403 || code === "invalid_grant";
83
+ const reason = `HTTP ${response.status}${code ? ` ${code}` : ""}`;
84
+ if (rejected) throw new Error(`Kimi Code token refresh rejected (${reason}); log in to Kimi Code again`);
85
+ throw new Error(`Kimi Code token refresh failed (${reason})`);
86
+ }
87
+ const expiresIn = Number(body?.expires_in);
88
+ if (!body?.access_token || !body?.refresh_token || !Number.isFinite(expiresIn) || expiresIn <= 0) {
89
+ throw new Error("Kimi Code token refresh failed: malformed token response");
90
+ }
91
+ const refreshed = {
92
+ ...credentials,
93
+ access_token: body.access_token,
94
+ refresh_token: body.refresh_token,
95
+ expires_at: Math.floor(Date.now() / 1000) + expiresIn,
96
+ scope: body.scope || "",
97
+ token_type: body.token_type || "Bearer",
98
+ expires_in: expiresIn,
99
+ };
100
+ writeKimiCredentials(credentialPath, refreshed);
101
+ return refreshed;
102
+ }
11
103
 
12
104
  async function getJSON(url, key, extraHeaders = {}) {
13
105
  const r = await fetch(url, {
@@ -116,17 +208,20 @@ export const ADAPTERS = [
116
208
  {
117
209
  provider: "kimi", label: "Kimi Code", kind: "quota", match: ["kimi"], envKeys: ["KIMI_API_KEY"], keyless: true,
118
210
  async fetch(key, env = {}, options = {}) {
119
- // Prefer the explicit API key; OAuth is read-only and never refreshes Kimi's credentials.
211
+ // Prefer the explicit API key. OAuth credentials refresh through Kimi Code's own public-client grant.
120
212
  let oauthCredentials = null;
213
+ let oauthCredentialPath = null;
214
+ const home = options.home ?? homedir();
121
215
  if (!key) {
122
- try {
123
- for (const directory of [".kimi-code", ".kimi"]) {
124
- try { oauthCredentials = JSON.parse(readFileSync(join(options.home ?? homedir(), directory, "credentials", "kimi-code.json"), "utf8")); }
125
- catch { continue; }
126
- if (oauthCredentials?.access_token) break;
216
+ for (const directory of [".kimi-code", ".kimi"]) {
217
+ try { oauthCredentials = JSON.parse(readFileSync(join(home, directory, "credentials", "kimi-code.json"), "utf8")); }
218
+ catch { continue; }
219
+ if (oauthCredentials?.access_token) {
220
+ oauthCredentialPath = join(home, directory, "credentials", "kimi-code.json");
221
+ break;
127
222
  }
128
- key = oauthCredentials?.access_token;
129
- } catch { /* absent or unreadable login is handled as no token below */ }
223
+ }
224
+ key = oauthCredentials?.access_token;
130
225
  }
131
226
  if (!key) throw new Error("no Kimi Code OAuth token found");
132
227
  if (oauthCredentials?.expires_at != null) {
@@ -135,10 +230,13 @@ export const ADAPTERS = [
135
230
  let expiresAt = Number.isFinite(numericExpiry) ? numericExpiry : Date.parse(String(rawExpiry));
136
231
  if (expiresAt > 0 && expiresAt < 1e12) expiresAt *= 1000;
137
232
  if (Number.isFinite(expiresAt) && expiresAt <= Date.now()) {
138
- return { remainingPct: null, plan: "coding", resetTime: null, detail: "Kimi Code login token expired; open Kimi Code to refresh" };
233
+ if (!oauthCredentials.refresh_token) throw new Error("Kimi Code login token expired and no refresh_token exists; log in to Kimi Code again");
234
+ oauthCredentials = await refreshKimiCredentials(oauthCredentials, oauthCredentialPath, env, home);
235
+ key = oauthCredentials.access_token;
139
236
  }
140
237
  }
141
- const base = String(env.KIMI_CODE_BASE_URL || "https://api.kimi.com/coding/v1").replace(/\/+$/, "");
238
+ const region = kimiOAuthRegion(oauthCredentials || { access_token: key }, env, home);
239
+ const base = String(env.KIMI_CODE_BASE_URL || KIMI_REGIONS[region].baseUrl).replace(/\/+$/, "");
142
240
  const j = await getJSON(`${base}/usages`, key);
143
241
  const windowMinutes = (entry) => {
144
242
  const duration = Number(entry?.window?.duration);
package/lib/project.mjs CHANGED
@@ -2,7 +2,7 @@
2
2
  // in the checkout (.trantor/project.json) or, unmarked, by the git repo root basename; an explicit
3
3
  // RELAY_PROJECT always wins and the hub folds aliases on top.
4
4
  import { execSync, execFileSync } from "node:child_process";
5
- import { readFileSync, writeFileSync, appendFileSync, existsSync, mkdirSync, readdirSync, statSync, realpathSync } from "node:fs";
5
+ import { readFileSync, writeFileSync, appendFileSync, existsSync, mkdirSync, readdirSync, statSync, realpathSync, renameSync, chmodSync, rmSync } from "node:fs";
6
6
  import { basename, join, dirname, resolve, sep } from "node:path";
7
7
  import { homedir, hostname } from "node:os";
8
8
  import { asRecord, asString } from "./decode.mjs";
@@ -114,8 +114,9 @@ export function devRootFor(env = process.env) {
114
114
  if (env.TRANTOR_DEV_ROOT) return env.TRANTOR_DEV_ROOT;
115
115
  const home = env.HOME || homedir();
116
116
  try {
117
- const cfg = JSON.parse(readFileSync(join(env.AGENT_BUS_DIR || join(home, ".agent-bus"), "config.json"), "utf8"));
118
- if (typeof cfg?.projectsRoot === "string" && cfg.projectsRoot.startsWith("/")) return cfg.projectsRoot;
117
+ const cfg = asRecord(JSON.parse(readFileSync(join(env.AGENT_BUS_DIR || join(home, ".agent-bus"), "config.json"), "utf8")));
118
+ const root = asString(cfg?.projectsRoot) ?? "";
119
+ if (root.startsWith("/")) return root;
119
120
  } catch {}
120
121
  return join(home, "development");
121
122
  }
@@ -311,9 +312,23 @@ export function nonSeatReason(dir = process.cwd(), env = process.env) {
311
312
  // named export rather than exposing the internal one, so the file stays the single writer.
312
313
  export function writeConfigPublic(cfg) { writeConfig(cfg); }
313
314
 
315
+ // Write-then-rename (#14801): an in-place rewrite let the app read an empty or half-written file
316
+ // and fall back to the retired local hub. A rename on one filesystem is atomic, so a reader sees
317
+ // the old file or the new one, never a partial one. The existing mode (0600) is kept.
314
318
  function writeConfig(cfg) {
315
319
  mkdirSync(busDir(), { recursive: true });
316
- writeFileSync(configPath(), JSON.stringify(cfg, null, 2));
320
+ const target = configPath();
321
+ let mode = 0o644;
322
+ try { mode = statSync(target).mode & 0o777; } catch {}
323
+ const temp = `${target}.${process.pid}.${Date.now()}.${Math.random().toString(36).slice(2)}.tmp`;
324
+ try {
325
+ writeFileSync(temp, JSON.stringify(cfg, null, 2), { mode });
326
+ chmodSync(temp, mode);
327
+ renameSync(temp, target);
328
+ } catch (error) {
329
+ rmSync(temp, { force: true });
330
+ throw error;
331
+ }
317
332
  }
318
333
 
319
334
  // Pin a project to a hub. URL must be absolute http(s); trailing slash stripped so
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "trantor",
3
- "version": "0.18.163",
3
+ "version": "0.18.165",
4
4
  "type": "module",
5
5
  "bin": {
6
6
  "trantor": "bin/cli.mjs"