@phren/cli 0.3.48 → 0.3.49

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.
@@ -286,10 +286,10 @@ export const gitboy = {
286
286
  return { ok: false, reason: result.reason ?? "failed", message: result.message ?? "gitboy refused the merge." };
287
287
  }
288
288
  },
289
- async whoami(root, host, token) {
289
+ async whoami(root, host, token, checkedApi) {
290
290
  if (!host.domain)
291
291
  throw new HostApiError("failed", "This repository has no gitboy remote.");
292
- const api = await apiRoot(root, host.domain, `https://${host.domain}/api/v1`);
292
+ const api = checkedApi ?? await apiRoot(root, host.domain, `https://${host.domain}/api/v1`);
293
293
  const { json } = await hostJson(`${api}/user`, { token, scheme: "bearer" });
294
294
  return { user: String(obj(json).username ?? "") };
295
295
  },
@@ -219,10 +219,10 @@ export const gitlab = {
219
219
  return { ok: false, reason: result.reason ?? "failed", message: result.message ?? "GitLab refused the merge." };
220
220
  }
221
221
  },
222
- async whoami(root, host, token) {
222
+ async whoami(root, host, token, checkedApi) {
223
223
  if (!host.domain)
224
224
  throw new HostApiError("failed", "This repository has no GitLab remote.");
225
- const base = await apiRoot(root, host.domain, `https://${host.domain}/api/v4`);
225
+ const base = checkedApi ?? await apiRoot(root, host.domain, `https://${host.domain}/api/v4`);
226
226
  const { json } = await hostJson(`${base}/user`, { token, scheme: "private-token" });
227
227
  return { user: String(obj(json).username ?? "") };
228
228
  },
@@ -16,6 +16,15 @@ export declare class HostApiError extends Error {
16
16
  * writable by whatever runs in the checkout, and must never be able to send
17
17
  * a stored token to another server. */
18
18
  export declare function apiRoot(root: string, domain: string, fallback: string): Promise<string>;
19
+ /** Resolve the exact endpoint once, so Connect can check and use the same URL.
20
+ * Only the hostname/port is exposed to clients, never API URL credentials. */
21
+ export declare function tokenDestination(root: string, host: {
22
+ kind: string | null;
23
+ domain: string | null;
24
+ }): Promise<{
25
+ api: string | null;
26
+ apiHost: string | null;
27
+ }>;
19
28
  export interface HostRequest {
20
29
  token?: string;
21
30
  /** How the token is sent: GitLab's PRIVATE-TOKEN header or a bearer token. */
@@ -20,6 +20,17 @@ export async function apiRoot(root, domain, fallback) {
20
20
  const configured = (await git(root, "config", "--global", "--get", `phren.${domain}.api`).catch(() => "")).trim();
21
21
  return (configured || fallback).replace(/\/+$/, "");
22
22
  }
23
+ /** Resolve the exact endpoint once, so Connect can check and use the same URL.
24
+ * Only the hostname/port is exposed to clients, never API URL credentials. */
25
+ export async function tokenDestination(root, host) {
26
+ if (!host.domain || (host.kind !== "gitlab" && host.kind !== "gitboy"))
27
+ return { api: null, apiHost: host.domain };
28
+ const api = await apiRoot(root, host.domain, `https://${host.domain}/api/${host.kind === "gitlab" ? "v4" : "v1"}`);
29
+ const url = new URL(api);
30
+ if (!["https:", "http:"].includes(url.protocol) || !url.host)
31
+ throw new HostApiError("failed", "Invalid git host API address.");
32
+ return { api, apiHost: url.host.toLowerCase() };
33
+ }
23
34
  export async function hostJson(url, request) {
24
35
  const headers = { accept: "application/json", "user-agent": "phren-hook" };
25
36
  if (request.token) {
@@ -22,6 +22,8 @@ export interface GitHost {
22
22
  name: string;
23
23
  /** The remote's domain and the repository's web address, when known. */
24
24
  domain: string | null;
25
+ /** Actual token destination (including a configured API port), when resolved. */
26
+ apiHost?: string | null;
25
27
  webUrl: string | null;
26
28
  remote: string | null;
27
29
  /** How the kind was found: from the URL, from an override, or not at all. */
@@ -56,7 +58,7 @@ export interface GitHostProvider {
56
58
  * comes back as `{ ok: false, reason: "blocked", message }`. */
57
59
  merge(root: string, request: MergeRequest, host: GitHost): Promise<Json>;
58
60
  /** Who a token signs in as, for Connect; HTTP hosts only. */
59
- whoami?(root: string, host: GitHost, token: string): Promise<{
61
+ whoami?(root: string, host: GitHost, token: string, api?: string): Promise<{
60
62
  user: string;
61
63
  }>;
62
64
  }
@@ -7,7 +7,7 @@ import { defaultBranch, invalidatePulls, invalidateTree } from "./git.js";
7
7
  import { z } from "zod";
8
8
  import { detectHost, providerFor, unknownHost } from "./git-hosts.js";
9
9
  import { writeHostToken } from "./git-host-auth.js";
10
- import { HostApiError } from "./git-host-http.js";
10
+ import { HostApiError, tokenDestination } from "./git-host-http.js";
11
11
  /** Finishing a session from the phone: commit what is staged, push the
12
12
  * current branch, open a pull request. Each acts on the repository the
13
13
  * existing /v1/git/* routes resolve (the pane's, a child's worktree, or a
@@ -231,16 +231,22 @@ export async function gitMergeRequest(cwd, data) {
231
231
  * gitboy host: the token is checked against the host first and stored in the
232
232
  * Hook's git-hosts.json with the account it signs in as. GitHub keeps gh's. */
233
233
  export async function gitHostToken(cwd, data) {
234
- const { token } = z.object({ token: z.string().max(4096) }).parse(data);
234
+ const { token, expectedHost } = z.object({ token: z.string().max(4096), expectedHost: z.string().trim().min(1).max(253).optional() }).parse(data);
235
235
  const root = await repository(cwd);
236
236
  const branch = (await git(root, "branch", "--show-current").catch(() => "")).trim();
237
237
  const host = await detectHost(root, branch);
238
+ const { api, apiHost } = await tokenDestination(root, host);
239
+ host.apiHost = apiHost;
240
+ // Pin the resolved endpoint through validation, even if config changes now.
241
+ if (expectedHost !== undefined && apiHost !== expectedHost.toLowerCase()) {
242
+ throw new BridgeError(409, "The project's remote changed. Reopen to review the new host.", { code: "host-changed" });
243
+ }
238
244
  const provider = providerFor(host);
239
245
  if (!provider || !host.domain || !host.kind) {
240
246
  const { reason, message } = unknownHost(host);
241
247
  return { ok: false, reason, message, host };
242
248
  }
243
- if (host.kind === "github" || !provider.whoami)
249
+ if (host.kind === "github" || !provider.whoami || !api)
244
250
  return { ok: false, reason: "unsupported", message: "GitHub uses the GitHub CLI's sign-in: run gh auth login on this computer.", host };
245
251
  const kind = host.kind;
246
252
  if (!token.trim()) {
@@ -248,13 +254,14 @@ export async function gitHostToken(cwd, data) {
248
254
  return { ok: true, disconnected: true, domain: host.domain, host };
249
255
  }
250
256
  try {
251
- const { user } = await provider.whoami(root, host, token.trim());
257
+ const identity = await provider.whoami(root, host, token.trim(), api);
258
+ const user = identity.user.replaceAll(token.trim(), "[redacted]");
252
259
  await writeHostToken(host.domain, kind, token.trim(), user || undefined);
253
260
  return { ok: true, domain: host.domain, kind, ...(user ? { user } : {}), host };
254
261
  }
255
262
  catch (error) {
256
263
  if (error instanceof HostApiError)
257
- return { ok: false, reason: error.reason, message: error.reason === "auth" ? `${host.name} refused that token.` : error.message, host };
264
+ return { ok: false, reason: error.reason, message: error.reason === "auth" ? `${host.name} refused that token.` : `${host.name} could not validate that token.`, host };
258
265
  throw error;
259
266
  }
260
267
  }
@@ -1,4 +1,5 @@
1
1
  import { type Json } from "./protocol.js";
2
+ import { detectHost } from "./git-hosts.js";
2
3
  export { checkRollup, checkRuns } from "./git-hosts.js";
3
4
  interface Counts {
4
5
  additions: number;
@@ -40,6 +41,7 @@ export interface GitStatus {
40
41
  files: GitStatusFile[];
41
42
  /** The branch a push guards: the upstream remote's `HEAD`, else `main`/`master`. */
42
43
  defaultBranch: string | null;
44
+ host: Awaited<ReturnType<typeof detectHost>>;
43
45
  }
44
46
  /** Working-tree status, one record per section: a file edited in both the index
45
47
  * and the working tree appears once with `staged: true` and once with `false`. */
@@ -4,6 +4,7 @@ import { lstat, open, readdir, realpath } from "node:fs/promises";
4
4
  import path from "node:path";
5
5
  import { BridgeError } from "./protocol.js";
6
6
  import { git, gitHead, gitRoot, withGitReadDeadline, withIndependentGitReadDeadline, withoutGitReadDeadline } from "./projects.js";
7
+ import { tokenDestination } from "./git-host-http.js";
7
8
  import { detectHost, providerFor, unknownHost } from "./git-hosts.js";
8
9
  import { hostCredentialIdentity } from "./git-host-auth.js";
9
10
  import { LookupCache } from "./lookup-cache.js";
@@ -130,6 +131,9 @@ async function readGitStatus(cwd, untrackedPath) {
130
131
  treeCache.delete(root);
131
132
  const data = await collect(root);
132
133
  const fallback = await defaultBranch(root, data.upstream?.split("/")[0] || "origin");
134
+ const host = await detectHost(root, data.branch);
135
+ const { apiHost } = await tokenDestination(root, host);
136
+ host.apiHost = apiHost;
133
137
  if (untrackedPath !== undefined) {
134
138
  const prefix = await repositoryPath(root, untrackedPath);
135
139
  if (!data.untracked.some(file => file.endsWith("/") && (prefix + "/").startsWith(file))
@@ -177,7 +181,7 @@ async function readGitStatus(cwd, untrackedPath) {
177
181
  branch: data.branch, upstream: data.upstream ?? null, ahead: data.ahead, behind: data.behind,
178
182
  staged: data.staged.size, unstaged: data.unstaged.size, untracked: data.untracked.length,
179
183
  additions: files.reduce((total, file) => total + file.additions, 0), deletions: files.reduce((total, file) => total + file.deletions, 0), files,
180
- defaultBranch: fallback };
184
+ defaultBranch: fallback, host };
181
185
  }
182
186
  /** The repository's remotes, so a branch ref can be told from a remote-tracking
183
187
  * one even when a local branch name contains a slash. */
@@ -330,7 +334,9 @@ export async function gitPulls(cwd, retried = false) {
330
334
  const { root, branch, host } = await withIndependentGitReadDeadline(async () => {
331
335
  const root = await repository(cwd);
332
336
  const branch = (await git(root, "branch", "--show-current").catch(() => "")).trim();
333
- return { root, branch, host: await detectHost(root, branch) };
337
+ const host = await detectHost(root, branch);
338
+ const { apiHost } = await tokenDestination(root, host);
339
+ return { root, branch, host: { ...host, apiHost } };
334
340
  });
335
341
  const provider = providerFor(host);
336
342
  const credential = await credentialIdentity(host);
@@ -1,8 +1,9 @@
1
1
  import { type Json } from "./protocol.js";
2
- /** `GET /v1/projects/:project/git`: the project's host, branch and open pull
2
+ /** Project git reads and token Connect share the same checkout lookup.
3
+ * `GET /v1/projects/:project/git`: the project's host, branch and open pull
3
4
  * requests with their checks, read from its checkout on this computer, so the
4
5
  * desktop's Projects page needs no session running there. */
5
6
  export declare const PROJECT_GIT_ROUTE: RegExp;
6
- /** The recorded source folder for this computer wins; otherwise the folders
7
- * `/v1/projects/locate` offers, newest session first. */
8
7
  export declare function projectGit(base: string, rawProject: string, activity: Json[]): Promise<Json>;
8
+ /** No pull-list read here: resolve locally before passing a token to the host. */
9
+ export declare function projectHostToken(base: string, rawProject: string, activity: Json[], data: unknown): Promise<Json>;
@@ -1,17 +1,20 @@
1
+ import { z } from "zod";
1
2
  import { getProjectSourcePath } from "../project-config.js";
2
3
  import { resolveProject } from "../store-routing.js";
3
4
  import { isValidProjectName } from "../utils.js";
5
+ import { gitHostToken } from "./git-publish.js";
4
6
  import { gitPulls } from "./git.js";
5
7
  import { locateProject } from "./locate.js";
6
8
  import { gitRoot } from "./projects.js";
7
9
  import { BridgeError } from "./protocol.js";
8
- /** `GET /v1/projects/:project/git`: the project's host, branch and open pull
10
+ /** Project git reads and token Connect share the same checkout lookup.
11
+ * `GET /v1/projects/:project/git`: the project's host, branch and open pull
9
12
  * requests with their checks, read from its checkout on this computer, so the
10
13
  * desktop's Projects page needs no session running there. */
11
- export const PROJECT_GIT_ROUTE = /^\/v1\/projects\/([^/]+)\/git$/;
14
+ export const PROJECT_GIT_ROUTE = /^\/v1\/projects\/([^/]+)\/git(?:\/(host-token))?$/;
12
15
  /** The recorded source folder for this computer wins; otherwise the folders
13
16
  * `/v1/projects/locate` offers, newest session first. */
14
- export async function projectGit(base, rawProject, activity) {
17
+ async function projectCheckout(base, rawProject, activity) {
15
18
  let project;
16
19
  try {
17
20
  project = decodeURIComponent(rawProject);
@@ -33,7 +36,17 @@ export async function projectGit(base, rawProject, activity) {
33
36
  for (const folder of folders) {
34
37
  const root = await gitRoot(folder).catch(() => undefined);
35
38
  if (root)
36
- return { project, directory: root, ...(await gitPulls(root)) };
39
+ return { project, directory: root };
37
40
  }
38
41
  throw new BridgeError(404, "No checkout of this project on this computer.", { code: "no-checkout" });
39
42
  }
43
+ export async function projectGit(base, rawProject, activity) {
44
+ const checkout = await projectCheckout(base, rawProject, activity);
45
+ return { ...checkout, ...(await gitPulls(checkout.directory)) };
46
+ }
47
+ /** No pull-list read here: resolve locally before passing a token to the host. */
48
+ export async function projectHostToken(base, rawProject, activity, data) {
49
+ const request = z.object({ token: z.string().max(4096), expectedHost: z.string().trim().min(1).max(253) }).parse(data);
50
+ const checkout = await projectCheckout(base, rawProject, activity);
51
+ return gitHostToken(checkout.directory, request);
52
+ }
@@ -64,8 +64,8 @@ export const requestID = () => randomUUID();
64
64
  export async function atomic(file, value, mode = 0o600) {
65
65
  const temporary = `${file}.${randomUUID()}.tmp`;
66
66
  const text = typeof value === "string" ? value : JSON.stringify(value);
67
- await writeFile(temporary, text, { mode, flag: "wx" });
68
67
  try {
68
+ await writeFile(temporary, text, { mode, flag: "wx" });
69
69
  await renameOver(temporary, file);
70
70
  }
71
71
  finally {
@@ -141,6 +141,7 @@ export declare const capabilities: {
141
141
  gitReview: boolean;
142
142
  memoryStoreBatch: boolean;
143
143
  gitHosts: boolean;
144
+ projectHostToken: boolean;
144
145
  };
145
146
  export declare function capabilitiesForModules(snapshot: ModuleSnapshot): Record<string, unknown>;
146
147
  export declare function requireRoute(snapshot: ModuleSnapshot, method: string, route: string): void;
@@ -28,7 +28,7 @@ import { MAX_FILE_RANGE, rangeInteger, readFileRange } from "./file-range.js";
28
28
  import { resolveFilePath } from "./file-resolve.js";
29
29
  import { storeRoute } from "./memory-store.js";
30
30
  import { memoryForFiles, memorySearch, PROJECT_MEMORY_ROUTE, projectMemory, saveFinding, tasksForBranch, completeProjectTask } from "./project-memory.js";
31
- import { PROJECT_GIT_ROUTE, projectGit } from "./project-git.js";
31
+ import { PROJECT_GIT_ROUTE, projectGit, projectHostToken } from "./project-git.js";
32
32
  import { liveBackground, markBackground, paneRecord, recordTitle, replyExcerpt } from "./session-activity.js";
33
33
  import { paneAccountField, paneChatState, panes, rpc, servers, snapshot, validateTarget, workspaceSnapshot } from "./herdr.js";
34
34
  import { locateProject } from "./locate.js";
@@ -81,7 +81,7 @@ async function childActivity(source, session) {
81
81
  export const capabilities = { transcript: true, progress: true, images: true, prompt: true, stop: true,
82
82
  terminal: "ssh-pty", shell: "ssh-pty", paneTerminal: "ssh-pty", paneLayout: true, deskPresence: true, herdr: true, sessionRename: true, diff: true, webServers: true, webPreview: "ssh-exec", activity: true,
83
83
  approvals: true, questions: false, accountUsage: true, providers: ["codex", "claude", "copilot", "opencode"],
84
- files: true, repositoryFiles: true, fileResolution: true, subagents: true, sideQuestions: true, dispatch: true, conductorSets: true, setLink: true, ownerInbox: true, workerReports: true, queuedHandOff: true, approvalPush: "direct-apns", simulators: process.platform === "darwin", code: true, codeFiles: true, overviewStream: true, speech: true, speechTimestamps: true, speechTimestampStream: true, speechLive: true, speechVoices: true, speechFormats: [...SPEECH_FORMATS], transcribe: true, memoryStore: true, promptOnce: true, promptStatus: true, deliveryFrames: true, paneDeliveries: true, resources: true, sudo: true, sudoOutcome: true, previewDeltas: true, quickChat: true, agentFolder: true, launchPermissionMode: true, sessionMove: true, moveNewChat: true, projectMemory: true, fileWrite: true, fileSearch: true, gitReview: true, memoryStoreBatch: true, gitHosts: true };
84
+ files: true, repositoryFiles: true, fileResolution: true, subagents: true, sideQuestions: true, dispatch: true, conductorSets: true, setLink: true, ownerInbox: true, workerReports: true, queuedHandOff: true, approvalPush: "direct-apns", simulators: process.platform === "darwin", code: true, codeFiles: true, overviewStream: true, speech: true, speechTimestamps: true, speechTimestampStream: true, speechLive: true, speechVoices: true, speechFormats: [...SPEECH_FORMATS], transcribe: true, memoryStore: true, promptOnce: true, promptStatus: true, deliveryFrames: true, paneDeliveries: true, resources: true, sudo: true, sudoOutcome: true, previewDeltas: true, quickChat: true, agentFolder: true, launchPermissionMode: true, sessionMove: true, moveNewChat: true, projectMemory: true, fileWrite: true, fileSearch: true, gitReview: true, memoryStoreBatch: true, gitHosts: true, projectHostToken: true };
85
85
  export function capabilitiesForModules(snapshot) {
86
86
  const allowed = new Set(snapshot.modules.flatMap(module => module.capabilities));
87
87
  const result = Object.fromEntries(Object.entries(capabilities).filter(([name]) => allowed.has(name)));
@@ -352,11 +352,14 @@ export function createRouteHandler(ctx) {
352
352
  result = await saveFinding(modules.store, project, await body(request));
353
353
  }
354
354
  else if (PROJECT_GIT_ROUTE.test(url.pathname)) {
355
- if (request.method !== "GET")
355
+ const [, project, tokenRoute] = PROJECT_GIT_ROUTE.exec(url.pathname);
356
+ if (request.method !== (tokenRoute ? "POST" : "GET"))
356
357
  throw new BridgeError(405, "Unsupported request method.");
357
358
  if (!modules.has("git"))
358
359
  throw new BridgeError(404, disabledHint("git"));
359
- result = await projectGit(modules.store, PROJECT_GIT_ROUTE.exec(url.pathname)[1], await journal.recent());
360
+ result = tokenRoute
361
+ ? await projectHostToken(modules.store, project, await journal.recent(), await body(request))
362
+ : await projectGit(modules.store, project, await journal.recent());
360
363
  }
361
364
  else if (url.pathname.startsWith("/v1/store/")) {
362
365
  result = await storeRoute(modules.store, request.method ?? "", url, request.method === "POST" ? await body(request) : undefined);
@@ -20616,8 +20616,8 @@ function withErrorCode(error62, code) {
20616
20616
  async function atomic(file4, value2, mode = 384) {
20617
20617
  const temporary = `${file4}.${randomUUID()}.tmp`;
20618
20618
  const text5 = typeof value2 === "string" ? value2 : JSON.stringify(value2);
20619
- await writeFile(temporary, text5, { mode, flag: "wx" });
20620
20619
  try {
20620
+ await writeFile(temporary, text5, { mode, flag: "wx" });
20621
20621
  await renameOver(temporary, file4);
20622
20622
  } finally {
20623
20623
  await unlink(temporary).catch(() => {
@@ -36703,7 +36703,7 @@ var init_package_metadata = __esm({
36703
36703
  __dirname = path35.dirname(fileURLToPath2(import.meta.url));
36704
36704
  ROOT = path35.join(__dirname, "..");
36705
36705
  PACKAGE_JSON_PATH = path35.join(ROOT, "package.json");
36706
- BUNDLED_VERSION = true ? "0.3.48" : "0.0.0";
36706
+ BUNDLED_VERSION = true ? "0.3.49" : "0.0.0";
36707
36707
  PACKAGE_JSON = readPackageJson();
36708
36708
  PACKAGE_NAME = PACKAGE_JSON.name || "phren";
36709
36709
  VERSION = PACKAGE_JSON.version || BUNDLED_VERSION;
@@ -38058,7 +38058,7 @@ var init_registry = __esm({
38058
38058
  "/v1/files/search",
38059
38059
  "/v1/files/list"
38060
38060
  ])],
38061
- capabilities: ["git", "diff", "fileWrite", "fileSearch", "gitReview", "gitHosts"],
38061
+ capabilities: ["git", "diff", "fileWrite", "fileSearch", "gitReview", "gitHosts", "projectHostToken"],
38062
38062
  storeFiles: [],
38063
38063
  localFiles: ["<bridge>/changes/**", "<bridge>/changes-scratch/**"],
38064
38064
  phoneScreens: [{ screen: "AgentChangesView", capability: "git" }],
@@ -54381,6 +54381,78 @@ var init_git_write_policy = __esm({
54381
54381
  }
54382
54382
  });
54383
54383
 
54384
+ // src/bridge/git-host-http.ts
54385
+ async function apiRoot(root, domain2, fallback2) {
54386
+ const configured = (await git(root, "config", "--global", "--get", `phren.${domain2}.api`).catch(() => "")).trim();
54387
+ return (configured || fallback2).replace(/\/+$/, "");
54388
+ }
54389
+ async function tokenDestination(root, host) {
54390
+ if (!host.domain || host.kind !== "gitlab" && host.kind !== "gitboy") return { api: null, apiHost: host.domain };
54391
+ const api = await apiRoot(root, host.domain, `https://${host.domain}/api/${host.kind === "gitlab" ? "v4" : "v1"}`);
54392
+ const url2 = new URL(api);
54393
+ if (!["https:", "http:"].includes(url2.protocol) || !url2.host) throw new HostApiError("failed", "Invalid git host API address.");
54394
+ return { api, apiHost: url2.host.toLowerCase() };
54395
+ }
54396
+ async function hostJson(url2, request9) {
54397
+ const headers = { accept: "application/json", "user-agent": "phren-hook" };
54398
+ if (request9.token) {
54399
+ if (request9.scheme === "private-token") headers["PRIVATE-TOKEN"] = request9.token;
54400
+ else headers.authorization = `Bearer ${request9.token}`;
54401
+ }
54402
+ if (request9.body !== void 0) headers["content-type"] = "application/json";
54403
+ let response;
54404
+ try {
54405
+ response = await fetch(url2, {
54406
+ method: request9.method ?? "GET",
54407
+ headers,
54408
+ redirect: "manual",
54409
+ body: request9.body === void 0 ? void 0 : JSON.stringify(request9.body),
54410
+ signal: AbortSignal.timeout(request9.timeoutMs ?? 15e3)
54411
+ });
54412
+ } catch (error62) {
54413
+ const timedOut = error62 instanceof Error && (error62.name === "TimeoutError" || error62.name === "AbortError");
54414
+ throw new HostApiError("unreachable", timedOut ? `${new URL(url2).host} did not answer within ${Math.round((request9.timeoutMs ?? 15e3) / 1e3)} seconds.` : `Could not reach ${new URL(url2).host}.`);
54415
+ }
54416
+ if (response.status >= 300 && response.status < 400) throw new HostApiError("failed", `${new URL(url2).host} redirected the API call; set its API address with git config phren.<domain>.api <url>.`, response.status);
54417
+ const text5 = await response.text();
54418
+ let json2 = null;
54419
+ try {
54420
+ json2 = text5 ? JSON.parse(text5) : null;
54421
+ } catch {
54422
+ json2 = null;
54423
+ }
54424
+ if (response.status === 401) throw new HostApiError("auth", "The host refused the token: it is missing, expired or revoked.", 401);
54425
+ if (response.status === 403) throw new HostApiError("auth", "The token cannot read this repository; it needs read access to its code, requests and pipelines.", 403);
54426
+ if (response.status === 404) throw new HostApiError("not-found", "The host has no such repository, or the token cannot see it.", 404);
54427
+ if (response.status >= 400) {
54428
+ const message = json2 && typeof json2 === "object" ? json2.message ?? json2.error : void 0;
54429
+ throw new HostApiError("failed", `${new URL(url2).host} answered ${response.status}${message ? `: ${typeof message === "string" ? message : JSON.stringify(message)}` : ""}`.slice(0, 500), response.status, json2);
54430
+ }
54431
+ return { status: response.status, json: json2, headers: response.headers };
54432
+ }
54433
+ function safeLink(value2) {
54434
+ return typeof value2 === "string" && /^https?:\/\//.test(value2) ? value2.slice(0, 2048) : void 0;
54435
+ }
54436
+ var HostApiError;
54437
+ var init_git_host_http = __esm({
54438
+ "src/bridge/git-host-http.ts"() {
54439
+ "use strict";
54440
+ init_projects();
54441
+ HostApiError = class extends Error {
54442
+ /** `body` is the host's own JSON for a refusal (gitboy's `details`, say). */
54443
+ constructor(reason2, message, status = 0, body2 = null) {
54444
+ super(message);
54445
+ this.reason = reason2;
54446
+ this.status = status;
54447
+ this.body = body2;
54448
+ }
54449
+ reason;
54450
+ status;
54451
+ body;
54452
+ };
54453
+ }
54454
+ });
54455
+
54384
54456
  // src/bridge/git-host-auth.ts
54385
54457
  import { createHash as createHash25 } from "node:crypto";
54386
54458
  import { execFile as execFile20 } from "node:child_process";
@@ -54517,71 +54589,6 @@ var init_git_host_auth = __esm({
54517
54589
  }
54518
54590
  });
54519
54591
 
54520
- // src/bridge/git-host-http.ts
54521
- async function apiRoot(root, domain2, fallback2) {
54522
- const configured = (await git(root, "config", "--global", "--get", `phren.${domain2}.api`).catch(() => "")).trim();
54523
- return (configured || fallback2).replace(/\/+$/, "");
54524
- }
54525
- async function hostJson(url2, request9) {
54526
- const headers = { accept: "application/json", "user-agent": "phren-hook" };
54527
- if (request9.token) {
54528
- if (request9.scheme === "private-token") headers["PRIVATE-TOKEN"] = request9.token;
54529
- else headers.authorization = `Bearer ${request9.token}`;
54530
- }
54531
- if (request9.body !== void 0) headers["content-type"] = "application/json";
54532
- let response;
54533
- try {
54534
- response = await fetch(url2, {
54535
- method: request9.method ?? "GET",
54536
- headers,
54537
- redirect: "manual",
54538
- body: request9.body === void 0 ? void 0 : JSON.stringify(request9.body),
54539
- signal: AbortSignal.timeout(request9.timeoutMs ?? 15e3)
54540
- });
54541
- } catch (error62) {
54542
- const timedOut = error62 instanceof Error && (error62.name === "TimeoutError" || error62.name === "AbortError");
54543
- throw new HostApiError("unreachable", timedOut ? `${new URL(url2).host} did not answer within ${Math.round((request9.timeoutMs ?? 15e3) / 1e3)} seconds.` : `Could not reach ${new URL(url2).host}.`);
54544
- }
54545
- if (response.status >= 300 && response.status < 400) throw new HostApiError("failed", `${new URL(url2).host} redirected the API call; set its API address with git config phren.<domain>.api <url>.`, response.status);
54546
- const text5 = await response.text();
54547
- let json2 = null;
54548
- try {
54549
- json2 = text5 ? JSON.parse(text5) : null;
54550
- } catch {
54551
- json2 = null;
54552
- }
54553
- if (response.status === 401) throw new HostApiError("auth", "The host refused the token: it is missing, expired or revoked.", 401);
54554
- if (response.status === 403) throw new HostApiError("auth", "The token cannot read this repository; it needs read access to its code, requests and pipelines.", 403);
54555
- if (response.status === 404) throw new HostApiError("not-found", "The host has no such repository, or the token cannot see it.", 404);
54556
- if (response.status >= 400) {
54557
- const message = json2 && typeof json2 === "object" ? json2.message ?? json2.error : void 0;
54558
- throw new HostApiError("failed", `${new URL(url2).host} answered ${response.status}${message ? `: ${typeof message === "string" ? message : JSON.stringify(message)}` : ""}`.slice(0, 500), response.status, json2);
54559
- }
54560
- return { status: response.status, json: json2, headers: response.headers };
54561
- }
54562
- function safeLink(value2) {
54563
- return typeof value2 === "string" && /^https?:\/\//.test(value2) ? value2.slice(0, 2048) : void 0;
54564
- }
54565
- var HostApiError;
54566
- var init_git_host_http = __esm({
54567
- "src/bridge/git-host-http.ts"() {
54568
- "use strict";
54569
- init_projects();
54570
- HostApiError = class extends Error {
54571
- /** `body` is the host's own JSON for a refusal (gitboy's `details`, say). */
54572
- constructor(reason2, message, status = 0, body2 = null) {
54573
- super(message);
54574
- this.reason = reason2;
54575
- this.status = status;
54576
- this.body = body2;
54577
- }
54578
- reason;
54579
- status;
54580
- body;
54581
- };
54582
- }
54583
- });
54584
-
54585
54592
  // src/bridge/git-publish.ts
54586
54593
  import { spawn as spawn10 } from "node:child_process";
54587
54594
  function runCombined(command, args, cwd, timeout, extraEnv = {}, killGraceMs = KILL_GRACE_MS2) {
@@ -54745,27 +54752,33 @@ async function gitMergeRequest(cwd, data) {
54745
54752
  }
54746
54753
  }
54747
54754
  async function gitHostToken(cwd, data) {
54748
- const { token } = external_exports.object({ token: external_exports.string().max(4096) }).parse(data);
54755
+ const { token, expectedHost } = external_exports.object({ token: external_exports.string().max(4096), expectedHost: external_exports.string().trim().min(1).max(253).optional() }).parse(data);
54749
54756
  const root = await repository(cwd);
54750
54757
  const branch = (await git(root, "branch", "--show-current").catch(() => "")).trim();
54751
54758
  const host = await detectHost(root, branch);
54759
+ const { api, apiHost } = await tokenDestination(root, host);
54760
+ host.apiHost = apiHost;
54761
+ if (expectedHost !== void 0 && apiHost !== expectedHost.toLowerCase()) {
54762
+ throw new BridgeError(409, "The project's remote changed. Reopen to review the new host.", { code: "host-changed" });
54763
+ }
54752
54764
  const provider2 = providerFor(host);
54753
54765
  if (!provider2 || !host.domain || !host.kind) {
54754
54766
  const { reason: reason2, message } = unknownHost(host);
54755
54767
  return { ok: false, reason: reason2, message, host };
54756
54768
  }
54757
- if (host.kind === "github" || !provider2.whoami) return { ok: false, reason: "unsupported", message: "GitHub uses the GitHub CLI's sign-in: run gh auth login on this computer.", host };
54769
+ if (host.kind === "github" || !provider2.whoami || !api) return { ok: false, reason: "unsupported", message: "GitHub uses the GitHub CLI's sign-in: run gh auth login on this computer.", host };
54758
54770
  const kind = host.kind;
54759
54771
  if (!token.trim()) {
54760
54772
  await writeHostToken(host.domain, kind, "");
54761
54773
  return { ok: true, disconnected: true, domain: host.domain, host };
54762
54774
  }
54763
54775
  try {
54764
- const { user } = await provider2.whoami(root, host, token.trim());
54776
+ const identity = await provider2.whoami(root, host, token.trim(), api);
54777
+ const user = identity.user.replaceAll(token.trim(), "[redacted]");
54765
54778
  await writeHostToken(host.domain, kind, token.trim(), user || void 0);
54766
54779
  return { ok: true, domain: host.domain, kind, ...user ? { user } : {}, host };
54767
54780
  } catch (error62) {
54768
- if (error62 instanceof HostApiError) return { ok: false, reason: error62.reason, message: error62.reason === "auth" ? `${host.name} refused that token.` : error62.message, host };
54781
+ if (error62 instanceof HostApiError) return { ok: false, reason: error62.reason, message: error62.reason === "auth" ? `${host.name} refused that token.` : `${host.name} could not validate that token.`, host };
54769
54782
  throw error62;
54770
54783
  }
54771
54784
  }
@@ -55019,9 +55032,9 @@ var init_git_host_gitlab = __esm({
55019
55032
  return { ok: false, reason: result.reason ?? "failed", message: result.message ?? "GitLab refused the merge." };
55020
55033
  }
55021
55034
  },
55022
- async whoami(root, host, token) {
55035
+ async whoami(root, host, token, checkedApi) {
55023
55036
  if (!host.domain) throw new HostApiError("failed", "This repository has no GitLab remote.");
55024
- const base = await apiRoot(root, host.domain, `https://${host.domain}/api/v4`);
55037
+ const base = checkedApi ?? await apiRoot(root, host.domain, `https://${host.domain}/api/v4`);
55025
55038
  const { json: json2 } = await hostJson(`${base}/user`, { token, scheme: "private-token" });
55026
55039
  return { user: String(obj(json2).username ?? "") };
55027
55040
  }
@@ -55278,9 +55291,9 @@ var init_git_host_gitboy = __esm({
55278
55291
  return { ok: false, reason: result.reason ?? "failed", message: result.message ?? "gitboy refused the merge." };
55279
55292
  }
55280
55293
  },
55281
- async whoami(root, host, token) {
55294
+ async whoami(root, host, token, checkedApi) {
55282
55295
  if (!host.domain) throw new HostApiError("failed", "This repository has no gitboy remote.");
55283
- const api = await apiRoot(root, host.domain, `https://${host.domain}/api/v1`);
55296
+ const api = checkedApi ?? await apiRoot(root, host.domain, `https://${host.domain}/api/v1`);
55284
55297
  const { json: json2 } = await hostJson(`${api}/user`, { token, scheme: "bearer" });
55285
55298
  return { user: String(obj2(json2).username ?? "") };
55286
55299
  }
@@ -55618,6 +55631,9 @@ async function readGitStatus(cwd, untrackedPath) {
55618
55631
  treeCache.delete(root);
55619
55632
  const data = await collect(root);
55620
55633
  const fallback2 = await defaultBranch(root, data.upstream?.split("/")[0] || "origin");
55634
+ const host = await detectHost(root, data.branch);
55635
+ const { apiHost } = await tokenDestination(root, host);
55636
+ host.apiHost = apiHost;
55621
55637
  if (untrackedPath !== void 0) {
55622
55638
  const prefix = await repositoryPath(root, untrackedPath);
55623
55639
  if (!data.untracked.some((file4) => file4.endsWith("/") && (prefix + "/").startsWith(file4)) || !(await lstat25(path95.join(root, prefix))).isDirectory() || await gitRoot(path95.join(root, prefix)) !== root) throw new BridgeError(409, "This is no longer an untracked directory in this repository.");
@@ -55665,7 +55681,8 @@ async function readGitStatus(cwd, untrackedPath) {
55665
55681
  additions: files.reduce((total, file4) => total + file4.additions, 0),
55666
55682
  deletions: files.reduce((total, file4) => total + file4.deletions, 0),
55667
55683
  files,
55668
- defaultBranch: fallback2
55684
+ defaultBranch: fallback2,
55685
+ host
55669
55686
  };
55670
55687
  }
55671
55688
  async function remotes(root) {
@@ -55780,7 +55797,9 @@ async function gitPulls(cwd, retried = false) {
55780
55797
  const { root, branch, host } = await withIndependentGitReadDeadline(async () => {
55781
55798
  const root2 = await repository2(cwd);
55782
55799
  const branch2 = (await git(root2, "branch", "--show-current").catch(() => "")).trim();
55783
- return { root: root2, branch: branch2, host: await detectHost(root2, branch2) };
55800
+ const host2 = await detectHost(root2, branch2);
55801
+ const { apiHost } = await tokenDestination(root2, host2);
55802
+ return { root: root2, branch: branch2, host: { ...host2, apiHost } };
55784
55803
  });
55785
55804
  const provider2 = providerFor(host);
55786
55805
  const credential = await credentialIdentity(host);
@@ -56112,6 +56131,7 @@ var init_git = __esm({
56112
56131
  "use strict";
56113
56132
  init_protocol();
56114
56133
  init_projects();
56134
+ init_git_host_http();
56115
56135
  init_git_hosts();
56116
56136
  init_git_host_auth();
56117
56137
  init_lookup_cache();
@@ -73021,7 +73041,7 @@ var init_project_memory = __esm({
73021
73041
  });
73022
73042
 
73023
73043
  // src/bridge/project-git.ts
73024
- async function projectGit(base, rawProject, activity) {
73044
+ async function projectCheckout(base, rawProject, activity) {
73025
73045
  let project;
73026
73046
  try {
73027
73047
  project = decodeURIComponent(rawProject);
@@ -73038,22 +73058,33 @@ async function projectGit(base, rawProject, activity) {
73038
73058
  for (const candidate of await locateProject(project, activity)) folders.push(candidate.directory);
73039
73059
  for (const folder of folders) {
73040
73060
  const root = await gitRoot(folder).catch(() => void 0);
73041
- if (root) return { project, directory: root, ...await gitPulls(root) };
73061
+ if (root) return { project, directory: root };
73042
73062
  }
73043
73063
  throw new BridgeError(404, "No checkout of this project on this computer.", { code: "no-checkout" });
73044
73064
  }
73065
+ async function projectGit(base, rawProject, activity) {
73066
+ const checkout = await projectCheckout(base, rawProject, activity);
73067
+ return { ...checkout, ...await gitPulls(checkout.directory) };
73068
+ }
73069
+ async function projectHostToken(base, rawProject, activity, data) {
73070
+ const request9 = external_exports.object({ token: external_exports.string().max(4096), expectedHost: external_exports.string().trim().min(1).max(253) }).parse(data);
73071
+ const checkout = await projectCheckout(base, rawProject, activity);
73072
+ return gitHostToken(checkout.directory, request9);
73073
+ }
73045
73074
  var PROJECT_GIT_ROUTE;
73046
73075
  var init_project_git = __esm({
73047
73076
  "src/bridge/project-git.ts"() {
73048
73077
  "use strict";
73078
+ init_zod();
73049
73079
  init_project_config();
73050
73080
  init_store_routing();
73051
73081
  init_utils();
73082
+ init_git_publish();
73052
73083
  init_git();
73053
73084
  init_locate();
73054
73085
  init_projects();
73055
73086
  init_protocol();
73056
- PROJECT_GIT_ROUTE = /^\/v1\/projects\/([^/]+)\/git$/;
73087
+ PROJECT_GIT_ROUTE = /^\/v1\/projects\/([^/]+)\/git(?:\/(host-token))?$/;
73057
73088
  }
73058
73089
  });
73059
73090
 
@@ -74252,9 +74283,10 @@ function createRouteHandler(ctx) {
74252
74283
  else if (route2 === "tasks/complete") result = completeProjectTask(modules.store, project, await body(request9));
74253
74284
  else result = await saveFinding(modules.store, project, await body(request9));
74254
74285
  } else if (PROJECT_GIT_ROUTE.test(url2.pathname)) {
74255
- if (request9.method !== "GET") throw new BridgeError(405, "Unsupported request method.");
74286
+ const [, project, tokenRoute] = PROJECT_GIT_ROUTE.exec(url2.pathname);
74287
+ if (request9.method !== (tokenRoute ? "POST" : "GET")) throw new BridgeError(405, "Unsupported request method.");
74256
74288
  if (!modules.has("git")) throw new BridgeError(404, disabledHint("git"));
74257
- result = await projectGit(modules.store, PROJECT_GIT_ROUTE.exec(url2.pathname)[1], await journal.recent());
74289
+ result = tokenRoute ? await projectHostToken(modules.store, project, await journal.recent(), await body(request9)) : await projectGit(modules.store, project, await journal.recent());
74258
74290
  } else if (url2.pathname.startsWith("/v1/store/")) {
74259
74291
  result = await storeRoute(modules.store, request9.method ?? "", url2, request9.method === "POST" ? await body(request9) : void 0);
74260
74292
  } else if (request9.method === "GET") {
@@ -74944,7 +74976,8 @@ var init_server_routes = __esm({
74944
74976
  fileSearch: true,
74945
74977
  gitReview: true,
74946
74978
  memoryStoreBatch: true,
74947
- gitHosts: true
74979
+ gitHosts: true,
74980
+ projectHostToken: true
74948
74981
  };
74949
74982
  }
74950
74983
  });
@@ -76658,7 +76691,7 @@ async function main() {
76658
76691
  return askpass2(args[1]);
76659
76692
  }
76660
76693
  const { runBridge: runBridge2 } = await Promise.resolve().then(() => (init_command(), command_exports));
76661
- return runBridge2(args, "0.3.48");
76694
+ return runBridge2(args, "0.3.49");
76662
76695
  }
76663
76696
  main().then((code) => {
76664
76697
  process.exitCode = code;
@@ -117,7 +117,7 @@ export const BUILTIN_MODULES = [
117
117
  "/v1/git/tree", "/v1/git/worktrees", "/v1/git/stage", "/v1/git/unstage", "/v1/git/discard",
118
118
  "/v1/git/commit", "/v1/git/push", "/v1/git/pr", "/v1/git/pr/merge", "/v1/git/host-token", "/v1/git/show", "/v1/git/checkout", "/v1/git/fetch", "/v1/git/pull", "/v1/git/file", "/v1/git/apply", "/v1/git/session-changes", "/v1/files/write", "/v1/files/search", "/v1/files/list",
119
119
  ])],
120
- capabilities: ["git", "diff", "fileWrite", "fileSearch", "gitReview", "gitHosts"], storeFiles: [], localFiles: ["<bridge>/changes/**", "<bridge>/changes-scratch/**"],
120
+ capabilities: ["git", "diff", "fileWrite", "fileSearch", "gitReview", "gitHosts", "projectHostToken"], storeFiles: [], localFiles: ["<bridge>/changes/**", "<bridge>/changes-scratch/**"],
121
121
  phoneScreens: [{ screen: "AgentChangesView", capability: "git" }], skills: [],
122
122
  },
123
123
  {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@phren/cli",
3
- "version": "0.3.48",
3
+ "version": "0.3.49",
4
4
  "description": "Knowledge layer for AI agents - CLI, MCP server, and data layer",
5
5
  "type": "module",
6
6
  "bin": {