@phren/cli 0.3.36 → 0.3.39
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/bridge/account-choice.d.ts +82 -0
- package/dist/bridge/account-choice.js +173 -0
- package/dist/bridge/account-failover.d.ts +61 -0
- package/dist/bridge/account-failover.js +189 -0
- package/dist/bridge/account-usage.d.ts +7 -2
- package/dist/bridge/account-usage.js +53 -8
- package/dist/bridge/agent-hooks.js +2 -0
- package/dist/bridge/changes.d.ts +5 -0
- package/dist/bridge/changes.js +4 -0
- package/dist/bridge/claude-accounts.d.ts +15 -4
- package/dist/bridge/claude-accounts.js +31 -16
- package/dist/bridge/claude-credits.d.ts +43 -0
- package/dist/bridge/claude-credits.js +236 -0
- package/dist/bridge/claude-question-dialog.js +6 -2
- package/dist/bridge/command.js +64 -3
- package/dist/bridge/device-enroll.d.ts +34 -0
- package/dist/bridge/device-enroll.js +57 -0
- package/dist/bridge/dispatch-command.d.ts +2 -0
- package/dist/bridge/dispatch-command.js +25 -1
- package/dist/bridge/dispatch-returns.d.ts +19 -0
- package/dist/bridge/dispatch-returns.js +93 -12
- package/dist/bridge/dispatch.d.ts +83 -3
- package/dist/bridge/dispatch.js +82 -10
- package/dist/bridge/file-range.d.ts +3 -0
- package/dist/bridge/file-range.js +5 -4
- package/dist/bridge/file-search.d.ts +37 -0
- package/dist/bridge/file-search.js +87 -0
- package/dist/bridge/file-write.d.ts +6 -0
- package/dist/bridge/file-write.js +120 -0
- package/dist/bridge/git-host-auth.d.ts +31 -0
- package/dist/bridge/git-host-auth.js +110 -0
- package/dist/bridge/git-host-gitboy.d.ts +46 -0
- package/dist/bridge/git-host-gitboy.js +296 -0
- package/dist/bridge/git-host-gitlab.d.ts +25 -0
- package/dist/bridge/git-host-gitlab.js +229 -0
- package/dist/bridge/git-host-http.d.ts +33 -0
- package/dist/bridge/git-host-http.js +70 -0
- package/dist/bridge/git-hosts.d.ts +92 -0
- package/dist/bridge/git-hosts.js +244 -0
- package/dist/bridge/git-publish.d.ts +15 -5
- package/dist/bridge/git-publish.js +69 -21
- package/dist/bridge/git-review.d.ts +23 -0
- package/dist/bridge/git-review.js +170 -0
- package/dist/bridge/git-sync.d.ts +14 -0
- package/dist/bridge/git-sync.js +143 -0
- package/dist/bridge/git.d.ts +20 -7
- package/dist/bridge/git.js +87 -68
- package/dist/bridge/gitboy-contract.d.ts +32 -0
- package/dist/bridge/gitboy-contract.js +46 -0
- package/dist/bridge/hand-off.d.ts +75 -3
- package/dist/bridge/hand-off.js +113 -27
- package/dist/bridge/health.d.ts +1 -1
- package/dist/bridge/health.js +5 -3
- package/dist/bridge/install.d.ts +14 -0
- package/dist/bridge/install.js +40 -1
- package/dist/bridge/launch-brief.d.ts +3 -0
- package/dist/bridge/launch-brief.js +16 -0
- package/dist/bridge/memory-store.d.ts +8 -0
- package/dist/bridge/memory-store.js +80 -2
- package/dist/bridge/pair.d.ts +6 -1
- package/dist/bridge/pair.js +74 -2
- package/dist/bridge/peers.js +4 -2
- package/dist/bridge/project-memory.d.ts +94 -0
- package/dist/bridge/project-memory.js +235 -0
- package/dist/bridge/push.d.ts +15 -0
- package/dist/bridge/push.js +39 -0
- package/dist/bridge/schedule-launch.js +5 -1
- package/dist/bridge/schedule-watch.d.ts +3 -0
- package/dist/bridge/schedule-watch.js +27 -1
- package/dist/bridge/scoped-gateway.d.ts +29 -0
- package/dist/bridge/scoped-gateway.js +239 -0
- package/dist/bridge/server-launch.d.ts +12 -0
- package/dist/bridge/server-launch.js +23 -12
- package/dist/bridge/server-pane-routes.js +54 -3
- package/dist/bridge/server-routes.d.ts +12 -0
- package/dist/bridge/server-routes.js +64 -5
- package/dist/bridge/server.js +50 -5
- package/dist/bridge/session-move.d.ts +288 -0
- package/dist/bridge/session-move.js +600 -0
- package/dist/bridge/subscription.d.ts +15 -0
- package/dist/bridge/subscription.js +23 -0
- package/dist/bridge/transport.js +21 -1
- package/dist/bridge/usage.d.ts +23 -4
- package/dist/bridge/usage.js +63 -11
- package/dist/bridge-hook.mjs +23280 -13252
- package/dist/cli/config.js +28 -2
- package/dist/cli-registry.js +10 -4
- package/dist/computers/command.js +3 -1
- package/dist/computers/read.d.ts +3 -0
- package/dist/computers/read.js +6 -0
- package/dist/content/summarize.d.ts +21 -0
- package/dist/content/summarize.js +56 -18
- package/dist/init/preferences.d.ts +6 -0
- package/dist/modules/registry.js +13 -13
- package/dist/project-config.d.ts +12 -0
- package/dist/project-config.js +29 -0
- package/dist/shared/retrieval.d.ts +1 -0
- package/dist/shared/retrieval.js +1 -1
- package/dist/sync/conflict-resolve.js +5 -6
- package/dist/tools/dispatch.js +20 -3
- package/dist/tools/finding.d.ts +25 -0
- package/dist/tools/finding.js +2 -1
- package/package.json +57 -1
|
@@ -1,6 +1,8 @@
|
|
|
1
1
|
import { z } from "zod";
|
|
2
2
|
import { type DispatchHost } from "./dispatch-hosts.js";
|
|
3
3
|
import { type Json, type Provider, type Target } from "./protocol.js";
|
|
4
|
+
import { type HarnessInventory } from "./harnesses.js";
|
|
5
|
+
import type { AccountRoom, WindowRoom } from "./account-choice.js";
|
|
4
6
|
import { type BriefArrival } from "./launch-brief.js";
|
|
5
7
|
export declare const projectName: z.ZodString;
|
|
6
8
|
/** The harnesses a dispatch, a code note's hand-off or a schedule can start. */
|
|
@@ -84,6 +86,25 @@ export declare const dispatchSchema: z.ZodObject<{
|
|
|
84
86
|
}, z.core.$strip>>;
|
|
85
87
|
}, z.core.$strict>;
|
|
86
88
|
export type DispatchInput = z.infer<typeof dispatchSchema>;
|
|
89
|
+
/** Where a session moves to (session-move.ts): a harness with its account, model and effort, as a dispatch names them. */
|
|
90
|
+
export declare const moveToSchema: z.ZodObject<{
|
|
91
|
+
harness: z.ZodEnum<{
|
|
92
|
+
claude: "claude";
|
|
93
|
+
codex: "codex";
|
|
94
|
+
copilot: "copilot";
|
|
95
|
+
opencode: "opencode";
|
|
96
|
+
}>;
|
|
97
|
+
account: z.ZodOptional<z.ZodString>;
|
|
98
|
+
model: z.ZodOptional<z.ZodString>;
|
|
99
|
+
effort: z.ZodOptional<z.ZodEnum<{
|
|
100
|
+
high: "high";
|
|
101
|
+
low: "low";
|
|
102
|
+
max: "max";
|
|
103
|
+
medium: "medium";
|
|
104
|
+
minimal: "minimal";
|
|
105
|
+
xhigh: "xhigh";
|
|
106
|
+
}>>;
|
|
107
|
+
}, z.core.$strict>;
|
|
87
108
|
/** The local pane that asked for the dispatch, where return notices go. */
|
|
88
109
|
export declare const originPaneSchema: z.ZodObject<{
|
|
89
110
|
server: z.ZodString;
|
|
@@ -214,6 +235,48 @@ declare const receiptSchema: z.ZodObject<{
|
|
|
214
235
|
launch: "launch";
|
|
215
236
|
typed: "typed";
|
|
216
237
|
}>>;
|
|
238
|
+
accountChoice: z.ZodOptional<z.ZodString>;
|
|
239
|
+
continued: z.ZodOptional<z.ZodObject<{
|
|
240
|
+
id: z.ZodOptional<z.ZodString>;
|
|
241
|
+
computer: z.ZodOptional<z.ZodString>;
|
|
242
|
+
account: z.ZodOptional<z.ZodString>;
|
|
243
|
+
at: z.ZodString;
|
|
244
|
+
error: z.ZodOptional<z.ZodString>;
|
|
245
|
+
}, z.core.$strict>>;
|
|
246
|
+
continues: z.ZodOptional<z.ZodString>;
|
|
247
|
+
moves: z.ZodOptional<z.ZodArray<z.ZodObject<{
|
|
248
|
+
id: z.ZodString;
|
|
249
|
+
at: z.ZodString;
|
|
250
|
+
handoff: z.ZodOptional<z.ZodString>;
|
|
251
|
+
from: z.ZodObject<{
|
|
252
|
+
harness: z.ZodEnum<{
|
|
253
|
+
claude: "claude";
|
|
254
|
+
codex: "codex";
|
|
255
|
+
copilot: "copilot";
|
|
256
|
+
opencode: "opencode";
|
|
257
|
+
phren: "phren";
|
|
258
|
+
}>;
|
|
259
|
+
account: z.ZodOptional<z.ZodString>;
|
|
260
|
+
}, z.core.$strict>;
|
|
261
|
+
to: z.ZodObject<{
|
|
262
|
+
harness: z.ZodEnum<{
|
|
263
|
+
claude: "claude";
|
|
264
|
+
codex: "codex";
|
|
265
|
+
copilot: "copilot";
|
|
266
|
+
opencode: "opencode";
|
|
267
|
+
}>;
|
|
268
|
+
account: z.ZodOptional<z.ZodString>;
|
|
269
|
+
model: z.ZodOptional<z.ZodString>;
|
|
270
|
+
effort: z.ZodOptional<z.ZodEnum<{
|
|
271
|
+
high: "high";
|
|
272
|
+
low: "low";
|
|
273
|
+
max: "max";
|
|
274
|
+
medium: "medium";
|
|
275
|
+
minimal: "minimal";
|
|
276
|
+
xhigh: "xhigh";
|
|
277
|
+
}>>;
|
|
278
|
+
}, z.core.$strict>;
|
|
279
|
+
}, z.core.$strict>>>;
|
|
217
280
|
granted: z.ZodOptional<z.ZodString>;
|
|
218
281
|
authority: z.ZodOptional<z.ZodString>;
|
|
219
282
|
authorityConfirmed: z.ZodOptional<z.ZodString>;
|
|
@@ -270,6 +333,10 @@ declare const receiptSchema: z.ZodObject<{
|
|
|
270
333
|
error: z.ZodOptional<z.ZodString>;
|
|
271
334
|
truncated: z.ZodOptional<z.ZodBoolean>;
|
|
272
335
|
question: z.ZodOptional<z.ZodString>;
|
|
336
|
+
checkout: z.ZodOptional<z.ZodObject<{
|
|
337
|
+
path: z.ZodString;
|
|
338
|
+
branch: z.ZodOptional<z.ZodString>;
|
|
339
|
+
}, z.core.$strict>>;
|
|
273
340
|
prs: z.ZodOptional<z.ZodArray<z.ZodObject<{
|
|
274
341
|
url: z.ZodURL;
|
|
275
342
|
repo: z.ZodString;
|
|
@@ -365,6 +432,8 @@ type Room = {
|
|
|
365
432
|
leftPercent?: number;
|
|
366
433
|
exhausted?: boolean;
|
|
367
434
|
until?: string;
|
|
435
|
+
fiveHour?: WindowRoom;
|
|
436
|
+
week?: WindowRoom;
|
|
368
437
|
};
|
|
369
438
|
/** The account this dispatch would run under there, as its capacity probe reports it: Codex's one, or the named Claude home. */
|
|
370
439
|
export declare function roomFor(data: {
|
|
@@ -372,11 +441,14 @@ export declare function roomFor(data: {
|
|
|
372
441
|
account?: string;
|
|
373
442
|
}, usage: readonly Room[] | undefined): Room | undefined;
|
|
374
443
|
/** Why `anywhere` must not pick a computer for quota: only an account with none left (at 100% or refusing requests).
|
|
375
|
-
* Low quota is not a reason; the owner often wants it used before it resets.
|
|
444
|
+
* Low quota is not a reason; the owner often wants it used before it resets. A Claude dispatch that names no
|
|
445
|
+
* account runs under whichever has room there, so with several accounts that computer is out only when all are. */
|
|
376
446
|
export declare function outOfQuota(data: {
|
|
377
447
|
harness: string;
|
|
378
448
|
account?: string;
|
|
379
449
|
}, usage: readonly Room[] | undefined, now?: number): string | undefined;
|
|
450
|
+
/** A computer's signed-in Claude accounts with their room, from its capacity probe. */
|
|
451
|
+
export declare function capacityClaudeRooms(harnesses: HarnessInventory["harnesses"] | undefined, usage: readonly Room[] | undefined): AccountRoom[];
|
|
380
452
|
/** What the worker's own hooks reported for a brief that went with its
|
|
381
453
|
* launch, or undefined when the receiving Hook has no such brief. */
|
|
382
454
|
export declare function arrivalOf(peer: Pick<DispatchHost, "request">, id: string): Promise<BriefArrival | undefined>;
|
|
@@ -404,8 +476,9 @@ export declare class DispatchService {
|
|
|
404
476
|
* socket); tests replace it so they never reach a real Hook. */
|
|
405
477
|
constructor(identity?: DispatchIdentity | undefined, local?: () => DispatchHost, settleIntervalMs?: number);
|
|
406
478
|
/** `originValue` is the local pane the request came from, as its agent's
|
|
407
|
-
* Herdr variables name it; a pane without a running agent is left out.
|
|
408
|
-
|
|
479
|
+
* Herdr variables name it; a pane without a running agent is left out.
|
|
480
|
+
* `continues` names the dispatch whose worker hit its usage limit (account-failover.ts). */
|
|
481
|
+
dispatch(input: unknown, originValue?: unknown, continues?: string): Promise<Json>;
|
|
409
482
|
/** Launches placed on `computer` whose brief is still being confirmed. */
|
|
410
483
|
private inFlight;
|
|
411
484
|
/**
|
|
@@ -427,6 +500,13 @@ export declare class DispatchService {
|
|
|
427
500
|
* uncertain, and the returns loop keeps asking.
|
|
428
501
|
*/
|
|
429
502
|
private confirmLaunched;
|
|
503
|
+
/** Every connected computer's signed-in Claude accounts and their room, this computer first:
|
|
504
|
+
* where a worker that hit its usage limit can continue (account-failover.ts). */
|
|
505
|
+
claudeRooms(): Promise<Array<{
|
|
506
|
+
computer: string;
|
|
507
|
+
local: boolean;
|
|
508
|
+
rooms: AccountRoom[];
|
|
509
|
+
}>>;
|
|
430
510
|
/** The query a conductor's dispatch sends with each capacity probe; undefined for any other caller. */
|
|
431
511
|
private conductorCaller;
|
|
432
512
|
private origin;
|
package/dist/bridge/dispatch.js
CHANGED
|
@@ -32,7 +32,7 @@ export const dispatchSchema = z.object({
|
|
|
32
32
|
model: text(200).optional().describe("Explicit model, otherwise the remote harness default."),
|
|
33
33
|
effort: z.enum(launchEfforts).optional().describe("Reasoning effort for the worker (minimal, low, medium, high, xhigh, max), otherwise the harness default."),
|
|
34
34
|
account: z.string().refine(isAccountSlug, "Account must be default or a lowercase slug.").optional()
|
|
35
|
-
.describe("Claude account id to run the worker under (default, or a slug from `phren bridge accounts`). anywhere only picks computers where that account is signed in; a named computer without it fails."),
|
|
35
|
+
.describe("Claude account id to run the worker under (default, or a slug from `phren bridge accounts`). anywhere only picks computers where that account is signed in; a named computer without it fails. Without it, a computer with several signed-in Claude accounts picks the one with the most 5-hour room, then weekly; the receipt's accountChoice says why."),
|
|
36
36
|
permissionMode: z.enum(PERMISSION_MODES).optional().describe("Permission mode the worker starts in: supervised, auto-edits, auto or full-access (Claude, Codex and Copilot; not OpenCode); otherwise the receiving computer's own default."),
|
|
37
37
|
releaseActions: z.array(releaseAction).min(1).max(RELEASE_ACTIONS.length).optional()
|
|
38
38
|
.describe("Release-type actions the brief asks the worker to do (merge, publish, deploy, app-store, github-admin). Ask-first projects refuse them from an agent unless the owner confirmed."),
|
|
@@ -43,6 +43,17 @@ export const dispatchSchema = z.object({
|
|
|
43
43
|
parent: dispatchParentSchema.optional().describe("Explicit local conversation parent for work-tree attachment."),
|
|
44
44
|
parentTarget: targetSchema.optional().describe("Complete live target for the explicit parent."),
|
|
45
45
|
}).strict();
|
|
46
|
+
/** Where a session moves to (session-move.ts): a harness with its account, model and effort, as a dispatch names them. */
|
|
47
|
+
export const moveToSchema = z.object({
|
|
48
|
+
harness: z.enum(DISPATCH_HARNESSES).describe("Harness to continue in: claude, codex, opencode or copilot."),
|
|
49
|
+
account: z.string().refine(isAccountSlug, "Account must be default or a lowercase slug.").optional()
|
|
50
|
+
.describe("Claude account id (default, or a slug from `phren bridge accounts`); only for claude."),
|
|
51
|
+
model: text(200).optional().describe("Model for the new agent, otherwise the harness default."),
|
|
52
|
+
effort: z.enum(launchEfforts).optional().describe("Reasoning effort for the new agent, otherwise the harness default."),
|
|
53
|
+
}).strict().superRefine((value, context) => {
|
|
54
|
+
if (value.account && value.harness !== "claude")
|
|
55
|
+
context.addIssue({ code: "custom", message: "Only a Claude target takes an account." });
|
|
56
|
+
});
|
|
46
57
|
const remoteTarget = z.union([targetSchema, startingTargetSchema]);
|
|
47
58
|
/** The local pane that asked for the dispatch, where return notices go. */
|
|
48
59
|
export const originPaneSchema = z.object({ server: serverName, workspace: id, tab: id, pane: id }).strict();
|
|
@@ -55,6 +66,14 @@ const receiptSchema = dispatchSchema.omit({ prompt: true }).extend({
|
|
|
55
66
|
target: remoteTarget.optional(), error: z.string().max(500).optional(),
|
|
56
67
|
brief: z.enum(["launch", "typed"]).optional()
|
|
57
68
|
.describe("How the brief reached the worker: as its first prompt at launch (confirmed by the worker's hook), or typed into its pane."),
|
|
69
|
+
accountChoice: z.string().max(400).optional().describe("Why the receiving Hook ran the worker under `account` when the dispatch named none."),
|
|
70
|
+
continued: z.object({ id: z.string().uuid().optional(), computer: z.string().max(200).optional(), account: z.string().max(64).optional(),
|
|
71
|
+
at: timestamp, error: z.string().max(500).optional() }).strict().optional()
|
|
72
|
+
.describe("The worker hit its Claude usage limit: the dispatch that continues it on another account, or why none could."),
|
|
73
|
+
continues: z.string().uuid().optional().describe("The dispatch this one continues after its worker hit its usage limit."),
|
|
74
|
+
moves: z.array(z.object({ id: z.string().uuid(), at: timestamp, handoff: z.string().max(4096).optional(),
|
|
75
|
+
from: z.object({ harness: provider, account: z.string().max(64).optional() }).strict(), to: moveToSchema }).strict()).max(16).optional()
|
|
76
|
+
.describe("Each move of this worker to another agent (session-move.ts): from, to, when, and the hand-off file on the worker's computer. `target`, `harness`, `account`, `model` and `effort` are the current agent's."),
|
|
58
77
|
granted: z.string().max(200).optional().describe("Scope of the conductor grant that allowed this call."),
|
|
59
78
|
authority: z.string().max(600).optional().describe("The release authority policy's line for this project, as a conductor quotes it."),
|
|
60
79
|
authorityConfirmed: z.string().datetime().optional().describe("When the owner confirmed the ask-first release actions this agent dispatch used."),
|
|
@@ -71,6 +90,8 @@ const receiptSchema = dispatchSchema.omit({ prompt: true }).extend({
|
|
|
71
90
|
returned: z.object({
|
|
72
91
|
state: z.enum(["done", "needs-you", "failed", "blocked", "stalled", "gone"]), at: timestamp,
|
|
73
92
|
reply: z.string().max(4000).optional(), error: z.string().max(500).optional(), truncated: z.boolean().optional(), question: z.string().max(200).optional(),
|
|
93
|
+
checkout: z.object({ path: z.string().max(4096), branch: z.string().max(256).optional() }).strict().optional()
|
|
94
|
+
.describe("Where a worker that failed was working, for the dispatch that continues it."),
|
|
74
95
|
prs: prsSchema.optional(),
|
|
75
96
|
integratorDelivery: z.object({ deliveryId: z.string(), state: z.enum(["pending", "queued", "delivered", "uncertain", "failed"]), at: timestamp, integrator: integratorSchema.optional() }).strict().optional(),
|
|
76
97
|
stalledSince: timestamp.optional(), stallFor: z.number().nonnegative().optional(),
|
|
@@ -182,6 +203,7 @@ export async function dispatchStatus() {
|
|
|
182
203
|
}
|
|
183
204
|
return receipts.sort((a, b) => b.createdAt.localeCompare(a.createdAt));
|
|
184
205
|
}
|
|
206
|
+
const windowRoom = z.object({ leftPercent: z.number().min(0).max(100).optional(), resetsAt: z.string().max(40).optional() }).passthrough().optional();
|
|
185
207
|
async function capacity(host, caller) {
|
|
186
208
|
const value = await host.request(caller && !host.local ? `/v1/dispatch/capacity?${caller}` : "/v1/dispatch/capacity");
|
|
187
209
|
const result = z.object({ product: z.literal("phren-hook"), protocol: z.literal(PROTOCOL), working: z.number().int().nonnegative(),
|
|
@@ -191,7 +213,7 @@ async function capacity(host, caller) {
|
|
|
191
213
|
accounts: z.array(z.object({ id: z.string(), usable: z.boolean(), reason: z.string().optional() }).passthrough()).optional() }).passthrough()).optional(),
|
|
192
214
|
// Missing from an older Hook or a slow read: that computer's quota is unknown, so it is never ruled out by it.
|
|
193
215
|
usage: z.array(z.object({ source: z.string(), account: z.string().optional(), leftPercent: z.number().min(0).max(100).optional(),
|
|
194
|
-
exhausted: z.boolean().optional(), until: z.string().max(40).optional() }).passthrough()).max(64).optional(),
|
|
216
|
+
exhausted: z.boolean().optional(), until: z.string().max(40).optional(), fiveHour: windowRoom, week: windowRoom }).passthrough()).max(64).optional(),
|
|
195
217
|
knowsCaller: z.boolean().optional() }).parse(value);
|
|
196
218
|
// This computer places on whichever Herdr server its own Hook runs.
|
|
197
219
|
if (host.local && !result.servers.includes(host.server) && result.servers[0])
|
|
@@ -207,22 +229,48 @@ export function roomFor(data, usage) {
|
|
|
207
229
|
const account = data.account ?? "default";
|
|
208
230
|
return usage?.find(item => item.source === data.harness && (data.harness !== "claude" || (item.account ?? "default") === account));
|
|
209
231
|
}
|
|
232
|
+
/** " for about 3 more hours" until `until`, or nothing when it is unknown. */
|
|
233
|
+
function backIn(until, now) {
|
|
234
|
+
const at = until ? Date.parse(until) : NaN;
|
|
235
|
+
const minutes = Number.isFinite(at) ? Math.max(1, Math.round((at - now) / 60_000)) : undefined;
|
|
236
|
+
return minutes === undefined ? "" : minutes >= 1440 ? ` for about ${Math.round(minutes / 1440)} more days` : minutes >= 60 ? ` for about ${Math.round(minutes / 60)} more hours` : ` for about ${minutes} more minutes`;
|
|
237
|
+
}
|
|
210
238
|
/** Why `anywhere` must not pick a computer for quota: only an account with none left (at 100% or refusing requests).
|
|
211
|
-
* Low quota is not a reason; the owner often wants it used before it resets.
|
|
239
|
+
* Low quota is not a reason; the owner often wants it used before it resets. A Claude dispatch that names no
|
|
240
|
+
* account runs under whichever has room there, so with several accounts that computer is out only when all are. */
|
|
212
241
|
export function outOfQuota(data, usage, now = Date.now()) {
|
|
242
|
+
const claude = usage?.filter(item => item.source === "claude") ?? [];
|
|
243
|
+
if (data.harness === "claude" && !data.account && claude.length > 1) {
|
|
244
|
+
if (claude.some(item => !item.exhausted))
|
|
245
|
+
return undefined;
|
|
246
|
+
return `Its claude accounts all have no quota left${backIn(claude.map(item => item.until).filter((value) => Boolean(value)).sort()[0], now)}.`;
|
|
247
|
+
}
|
|
213
248
|
const room = roomFor(data, usage);
|
|
214
249
|
if (!room?.exhausted)
|
|
215
250
|
return undefined;
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
251
|
+
return `Its ${data.harness}${data.harness === "claude" ? ` account ${data.account ?? "default"}` : ""} has no quota left${backIn(room.until, now)}.`;
|
|
252
|
+
}
|
|
253
|
+
/** A computer's signed-in Claude accounts with their room, from its capacity probe. */
|
|
254
|
+
export function capacityClaudeRooms(harnesses, usage) {
|
|
255
|
+
const accounts = harnesses?.find(entry => entry.source === "claude")?.accounts ?? [];
|
|
256
|
+
return accounts.map(account => {
|
|
257
|
+
const room = usage?.find(item => item.source === "claude" && (item.account ?? "default") === account.id);
|
|
258
|
+
return { account: account.id, ...(account.key ? { key: account.key } : {}), usable: account.usable,
|
|
259
|
+
...(room?.fiveHour ? { fiveHour: room.fiveHour } : {}), ...(room?.week ? { week: room.week } : {}),
|
|
260
|
+
...(room?.exhausted ? { exhausted: true, ...(room.until ? { until: room.until } : {}) } : {}) };
|
|
261
|
+
});
|
|
220
262
|
}
|
|
221
263
|
/** Why a computer cannot run this dispatch's harness and account, or undefined when it can or cannot yet be told.
|
|
222
264
|
* `unknown` (no `harnesses`) only counts against a computer when a non-default account was asked for. */
|
|
223
265
|
function unusable(data, harnesses, strictUnknown) {
|
|
224
266
|
if (!harnesses)
|
|
225
267
|
return strictUnknown && data.account && data.account !== "default" ? "Its Hook does not report harnesses or accounts (update it)." : undefined;
|
|
268
|
+
// No account named: any signed-in Claude account there will do (the launch picks one).
|
|
269
|
+
if (data.harness === "claude" && !data.account) {
|
|
270
|
+
const usable = harnesses.find(entry => entry.source === "claude")?.accounts?.find(account => account.usable);
|
|
271
|
+
if (usable)
|
|
272
|
+
return unusable({ harness: "claude", account: usable.id }, harnesses, strictUnknown);
|
|
273
|
+
}
|
|
226
274
|
const availability = hasUsable({ harnesses }, data.harness, data.account);
|
|
227
275
|
return availability.ok ? undefined : availability.reason;
|
|
228
276
|
}
|
|
@@ -419,8 +467,9 @@ export class DispatchService {
|
|
|
419
467
|
this.settleIntervalMs = settleIntervalMs;
|
|
420
468
|
}
|
|
421
469
|
/** `originValue` is the local pane the request came from, as its agent's
|
|
422
|
-
* Herdr variables name it; a pane without a running agent is left out.
|
|
423
|
-
|
|
470
|
+
* Herdr variables name it; a pane without a running agent is left out.
|
|
471
|
+
* `continues` names the dispatch whose worker hit its usage limit (account-failover.ts). */
|
|
472
|
+
async dispatch(input, originValue, continues) {
|
|
424
473
|
const data = dispatchSchema.parse(input);
|
|
425
474
|
if (data.permissionMode && data.harness === "opencode")
|
|
426
475
|
throw new BridgeError(400, "OpenCode takes its permissions from its own config; permissionMode is for Claude, Codex and Copilot workers.");
|
|
@@ -532,7 +581,7 @@ export class DispatchService {
|
|
|
532
581
|
createdAt: new Date().toISOString(), updatedAt: new Date().toISOString(), state: "launching",
|
|
533
582
|
...(grant ? { granted: grantLabel(grant) } : {}), ...(authority?.listed ? { authority: authority.line.slice(0, 600) } : {}),
|
|
534
583
|
...(checked?.confirmation ? { authorityConfirmed: checked.confirmation.confirmedAt } : {}),
|
|
535
|
-
...(skipped.length ? { skipped } : {}), ...(origin ? { origin } : {}) };
|
|
584
|
+
...(skipped.length ? { skipped } : {}), ...(origin ? { origin } : {}), ...(continues ? { continues } : {}) };
|
|
536
585
|
await save(receipt);
|
|
537
586
|
try {
|
|
538
587
|
// The brief goes with the launch: a Hook that can start the harness
|
|
@@ -541,6 +590,13 @@ export class DispatchService {
|
|
|
541
590
|
// Placed: the brief is confirmed outside the lock.
|
|
542
591
|
placed = peer.name;
|
|
543
592
|
this.placing.set(placed, this.inFlight(placed) + 1);
|
|
593
|
+
// The receiving Hook chose the Claude account (the one with the most room) when none was named.
|
|
594
|
+
if (!data.account && typeof launched.account === "string" && isAccountSlug(launched.account)) {
|
|
595
|
+
receipt.account = launched.account;
|
|
596
|
+
if (typeof launched.accountChoice === "string")
|
|
597
|
+
receipt.accountChoice = launched.accountChoice.slice(0, 400);
|
|
598
|
+
logger.info("dispatch", `${receipt.label} on ${peer.name} runs under Claude account ${launched.account}${receipt.accountChoice ? `: ${receipt.accountChoice}` : ""}.`);
|
|
599
|
+
}
|
|
544
600
|
release();
|
|
545
601
|
// An older Hook ignores the field and starts the worker in its own default mode.
|
|
546
602
|
const ignored = data.permissionMode && launched.permissionMode !== data.permissionMode ? IGNORED_MODE : undefined;
|
|
@@ -695,6 +751,22 @@ export class DispatchService {
|
|
|
695
751
|
}
|
|
696
752
|
receipt.error = `${receipt.harness} started with the brief on ${receipt.computer} but has not confirmed it yet (last status ${status ?? "unknown"}). The Hook keeps checking.`.slice(0, 500);
|
|
697
753
|
}
|
|
754
|
+
/** Every connected computer's signed-in Claude accounts and their room, this computer first:
|
|
755
|
+
* where a worker that hit its usage limit can continue (account-failover.ts). */
|
|
756
|
+
async claudeRooms() {
|
|
757
|
+
const here = this.local();
|
|
758
|
+
const hosts = [here, ...(await hookPeers().catch(() => [])).map(candidate => peerHost(candidate))];
|
|
759
|
+
const found = await Promise.all(hosts.map(async (host) => {
|
|
760
|
+
try {
|
|
761
|
+
const reported = await capacity(host);
|
|
762
|
+
return { computer: host.name, local: host.local, rooms: capacityClaudeRooms(reported.harnesses, reported.usage) };
|
|
763
|
+
}
|
|
764
|
+
catch {
|
|
765
|
+
return undefined;
|
|
766
|
+
}
|
|
767
|
+
}));
|
|
768
|
+
return found.filter((item) => !!item);
|
|
769
|
+
}
|
|
698
770
|
/** The query a conductor's dispatch sends with each capacity probe; undefined for any other caller. */
|
|
699
771
|
async conductorCaller(value) {
|
|
700
772
|
const pane = originPaneSchema.safeParse(value);
|
|
@@ -1,5 +1,8 @@
|
|
|
1
|
+
import { type Stats } from "node:fs";
|
|
1
2
|
export declare const MAX_FILE_RANGE: number;
|
|
2
3
|
export declare function fileContentType(file: string): string;
|
|
4
|
+
/** A file's identity and content stamp; any write, rename or replacement changes it. */
|
|
5
|
+
export declare function fileVersion(stat: Stats): string;
|
|
3
6
|
export declare function rangeInteger(value: string | null, fallback: number): number;
|
|
4
7
|
/** Roots are selected by the server, never supplied unchecked by the phone.
|
|
5
8
|
* A zero length request checks existence and metadata without reading bytes.
|
|
@@ -16,7 +16,8 @@ export function fileContentType(file) {
|
|
|
16
16
|
return types[ext] ?? (/^(ts|tsx|js|jsx|swift|py|rs|go|rb|sh|bash|zsh|c|h|cpp|hpp|cs|java|kt|html|css|scss|sql|toml|ini)$/.test(ext)
|
|
17
17
|
? "text/plain" : "application/octet-stream");
|
|
18
18
|
}
|
|
19
|
-
|
|
19
|
+
/** A file's identity and content stamp; any write, rename or replacement changes it. */
|
|
20
|
+
export function fileVersion(stat) {
|
|
20
21
|
return `${stat.dev}:${stat.ino}:${stat.size}:${stat.mtimeMs}:${stat.ctimeMs}`;
|
|
21
22
|
}
|
|
22
23
|
export function rangeInteger(value, fallback) {
|
|
@@ -57,10 +58,10 @@ export async function readFileRange(root, requested, offset, length, expectedVer
|
|
|
57
58
|
try {
|
|
58
59
|
const current = await handle.stat();
|
|
59
60
|
// Recheck the name after opening, including parent directory replacements.
|
|
60
|
-
if (!current.isFile() ||
|
|
61
|
+
if (!current.isFile() || fileVersion(current) !== fileVersion(metadata) || await realpath(file) !== resolved) {
|
|
61
62
|
throw new BridgeError(409, "The file changed. Open it again.");
|
|
62
63
|
}
|
|
63
|
-
const revision =
|
|
64
|
+
const revision = fileVersion(current);
|
|
64
65
|
if (expectedVersion !== undefined && expectedVersion !== revision)
|
|
65
66
|
throw new BridgeError(409, "The file changed. Open it again.");
|
|
66
67
|
if (offset > current.size)
|
|
@@ -73,7 +74,7 @@ export async function readFileRange(root, requested, offset, length, expectedVer
|
|
|
73
74
|
break;
|
|
74
75
|
read += next.bytesRead;
|
|
75
76
|
}
|
|
76
|
-
if (
|
|
77
|
+
if (fileVersion(await handle.stat()) !== revision || read !== bytes.length)
|
|
77
78
|
throw new BridgeError(409, "The file changed. Open it again.");
|
|
78
79
|
return { path: requested, offset, length: read, total: current.size, contentType: fileContentType(file),
|
|
79
80
|
version: revision, eof: offset + read === current.size, data: bytes.toString("base64") };
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
import { z } from "zod";
|
|
2
|
+
/** What find-in-files accepts: a literal or extended regular expression, the
|
|
3
|
+
* usual case and whole-word switches, and optional git pathspecs to include. */
|
|
4
|
+
export declare const fileSearchSchema: z.ZodObject<{
|
|
5
|
+
query: z.ZodString;
|
|
6
|
+
regex: z.ZodOptional<z.ZodBoolean>;
|
|
7
|
+
caseSensitive: z.ZodOptional<z.ZodBoolean>;
|
|
8
|
+
wholeWord: z.ZodOptional<z.ZodBoolean>;
|
|
9
|
+
include: z.ZodOptional<z.ZodArray<z.ZodString>>;
|
|
10
|
+
limit: z.ZodOptional<z.ZodNumber>;
|
|
11
|
+
}, z.core.$strip>;
|
|
12
|
+
export type FileSearch = z.infer<typeof fileSearchSchema>;
|
|
13
|
+
/**
|
|
14
|
+
* Find in files for the desktop editor: `git grep` over tracked and untracked
|
|
15
|
+
* (not ignored) text files in the repository root the server chose, so it works
|
|
16
|
+
* wherever git does and respects .gitignore. Results are grouped by file with
|
|
17
|
+
* 1-based line and column; long lines are cut around the match.
|
|
18
|
+
*/
|
|
19
|
+
export declare function searchRepository(root: string, input: FileSearch): Promise<{
|
|
20
|
+
matches: {
|
|
21
|
+
file: string;
|
|
22
|
+
lines: {
|
|
23
|
+
line: number;
|
|
24
|
+
column: number;
|
|
25
|
+
text: string;
|
|
26
|
+
}[];
|
|
27
|
+
}[];
|
|
28
|
+
files: number;
|
|
29
|
+
total: number;
|
|
30
|
+
truncated: boolean;
|
|
31
|
+
}>;
|
|
32
|
+
/** Every tracked and untracked (not ignored) file path, for the editor's quick open. */
|
|
33
|
+
export declare function listRepositoryFiles(root: string): Promise<{
|
|
34
|
+
files: string[];
|
|
35
|
+
total: number;
|
|
36
|
+
truncated: boolean;
|
|
37
|
+
}>;
|
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
import { z } from "zod";
|
|
2
|
+
import { git } from "./projects.js";
|
|
3
|
+
import { BridgeError } from "./protocol.js";
|
|
4
|
+
/** What find-in-files accepts: a literal or extended regular expression, the
|
|
5
|
+
* usual case and whole-word switches, and optional git pathspecs to include. */
|
|
6
|
+
export const fileSearchSchema = z.object({
|
|
7
|
+
query: z.string().min(1).max(200).refine(value => !/[\x00\n\r]/.test(value), "One line of text only."),
|
|
8
|
+
regex: z.boolean().optional(),
|
|
9
|
+
caseSensitive: z.boolean().optional(),
|
|
10
|
+
wholeWord: z.boolean().optional(),
|
|
11
|
+
include: z.array(z.string().min(1).max(200).refine(value => !value.startsWith(":") && !value.includes("\0") && !value.split("/").includes(".."), "Invalid path pattern.")).max(8).optional(),
|
|
12
|
+
limit: z.number().int().min(1).max(1000).optional(),
|
|
13
|
+
});
|
|
14
|
+
const MAX_PER_FILE = 50;
|
|
15
|
+
const MAX_TEXT = 300;
|
|
16
|
+
/**
|
|
17
|
+
* Find in files for the desktop editor: `git grep` over tracked and untracked
|
|
18
|
+
* (not ignored) text files in the repository root the server chose, so it works
|
|
19
|
+
* wherever git does and respects .gitignore. Results are grouped by file with
|
|
20
|
+
* 1-based line and column; long lines are cut around the match.
|
|
21
|
+
*/
|
|
22
|
+
export async function searchRepository(root, input) {
|
|
23
|
+
const limit = input.limit ?? 300;
|
|
24
|
+
const args = ["grep", "-n", "--column", "-I", "--untracked", "--no-color", "--full-name", "-z",
|
|
25
|
+
`--max-count=${MAX_PER_FILE}`, input.regex ? "-E" : "-F"];
|
|
26
|
+
if (!input.caseSensitive)
|
|
27
|
+
args.push("-i");
|
|
28
|
+
if (input.wholeWord)
|
|
29
|
+
args.push("-w");
|
|
30
|
+
args.push("-e", input.query, "--");
|
|
31
|
+
// Literal pathspecs only through glob magic, never other pathspec magic.
|
|
32
|
+
// A bare pattern like "*.ts" matches in every folder, as editors expect.
|
|
33
|
+
for (const pattern of input.include ?? [])
|
|
34
|
+
args.push(`:(glob)${pattern.includes("/") ? pattern : `**/${pattern}`}`);
|
|
35
|
+
let output;
|
|
36
|
+
try {
|
|
37
|
+
output = await git(root, ...args);
|
|
38
|
+
}
|
|
39
|
+
catch (error) {
|
|
40
|
+
// git grep exits 1 when nothing matches; that is an empty result, not a failure.
|
|
41
|
+
if (error instanceof BridgeError && error.details?.exitCode === "1" && error.details?.code === "git-failed" && /could not complete$/.test(error.message)) {
|
|
42
|
+
return { matches: [], files: 0, total: 0, truncated: false };
|
|
43
|
+
}
|
|
44
|
+
if (error instanceof BridgeError && error.details?.code === "git-output-limit") {
|
|
45
|
+
throw new BridgeError(413, "Too many matches. Narrow the search or add a path pattern.", { code: "search-too-broad" });
|
|
46
|
+
}
|
|
47
|
+
if (error instanceof BridgeError && /fatal: .*(regexp|regex|Invalid)/i.test(error.message)) {
|
|
48
|
+
throw new BridgeError(400, "That regular expression is not valid.", { code: "search-invalid-regex" });
|
|
49
|
+
}
|
|
50
|
+
throw error;
|
|
51
|
+
}
|
|
52
|
+
const groups = new Map();
|
|
53
|
+
let total = 0;
|
|
54
|
+
let truncated = false;
|
|
55
|
+
for (const row of output.split("\n")) {
|
|
56
|
+
if (!row)
|
|
57
|
+
continue;
|
|
58
|
+
const [file, line, column, ...rest] = row.split("\0");
|
|
59
|
+
const text = rest.join("\0");
|
|
60
|
+
if (!file || !line || !column)
|
|
61
|
+
continue;
|
|
62
|
+
if (total >= limit) {
|
|
63
|
+
truncated = true;
|
|
64
|
+
break;
|
|
65
|
+
}
|
|
66
|
+
total += 1;
|
|
67
|
+
const col = Number(column);
|
|
68
|
+
// Keep the match in view when a line is long: start a little before it.
|
|
69
|
+
const start = text.length > MAX_TEXT ? Math.max(0, Math.min(col - 1 - 40, text.length - MAX_TEXT)) : 0;
|
|
70
|
+
const shown = text.slice(start, start + MAX_TEXT);
|
|
71
|
+
const entry = { line: Number(line), column: col, text: shown, ...(start ? { offset: start } : {}) };
|
|
72
|
+
const list = groups.get(file) ?? [];
|
|
73
|
+
list.push(entry);
|
|
74
|
+
groups.set(file, list);
|
|
75
|
+
}
|
|
76
|
+
return {
|
|
77
|
+
matches: [...groups].map(([file, lines]) => ({ file, lines })),
|
|
78
|
+
files: groups.size, total, truncated,
|
|
79
|
+
};
|
|
80
|
+
}
|
|
81
|
+
const MAX_LISTED = 20_000;
|
|
82
|
+
/** Every tracked and untracked (not ignored) file path, for the editor's quick open. */
|
|
83
|
+
export async function listRepositoryFiles(root) {
|
|
84
|
+
const output = await git(root, "ls-files", "-z", "--cached", "--others", "--exclude-standard", "--full-name");
|
|
85
|
+
const all = [...new Set(output.split("\0").filter(Boolean))];
|
|
86
|
+
return { files: all.slice(0, MAX_LISTED), total: all.length, truncated: all.length > MAX_LISTED };
|
|
87
|
+
}
|
|
@@ -0,0 +1,120 @@
|
|
|
1
|
+
import { randomBytes } from "node:crypto";
|
|
2
|
+
import { constants } from "node:fs";
|
|
3
|
+
import { lstat, open, realpath, rename, rm } from "node:fs/promises";
|
|
4
|
+
import path from "node:path";
|
|
5
|
+
import { fileVersion, MAX_FILE_RANGE } from "./file-range.js";
|
|
6
|
+
import { BridgeError } from "./protocol.js";
|
|
7
|
+
/**
|
|
8
|
+
* Write one text file inside a repository root the server chose (a pane's
|
|
9
|
+
* checkout), for the desktop editor. The same path rules as reads: relative,
|
|
10
|
+
* no `..`, no `.git`, no symbolic link anywhere on the way, no control
|
|
11
|
+
* characters. An update must name the version the editor read
|
|
12
|
+
* (`fileVersion`) and fails with 409 `file-changed` when the file moved since;
|
|
13
|
+
* leaving the version out creates a new file and fails with `file-exists`
|
|
14
|
+
* when one is there. Updates go through a temp file in the same folder and a
|
|
15
|
+
* rename, keeping the file's mode, so a reader never sees half a file.
|
|
16
|
+
*/
|
|
17
|
+
/** One write at a time per file in this Hook, so two saves naming the same
|
|
18
|
+
* version cannot both pass the check and overwrite each other. */
|
|
19
|
+
const fileLocks = new Map();
|
|
20
|
+
async function serialized(key, work) {
|
|
21
|
+
const previous = fileLocks.get(key) ?? Promise.resolve();
|
|
22
|
+
const run = previous.catch(() => undefined).then(work);
|
|
23
|
+
fileLocks.set(key, run);
|
|
24
|
+
try {
|
|
25
|
+
return await run;
|
|
26
|
+
}
|
|
27
|
+
finally {
|
|
28
|
+
if (fileLocks.get(key) === run)
|
|
29
|
+
fileLocks.delete(key);
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
export async function writeRepoFile(root, requested, content, expectedVersion) {
|
|
33
|
+
const key = `${await realpath(root).catch(() => root)}\u0000${requested}`;
|
|
34
|
+
return serialized(key, () => writeRepoFileNow(root, requested, content, expectedVersion));
|
|
35
|
+
}
|
|
36
|
+
async function writeRepoFileNow(root, requested, content, expectedVersion) {
|
|
37
|
+
if (typeof requested !== "string" || !requested || requested.length > 4096 || path.isAbsolute(requested)
|
|
38
|
+
|| /[\x00-\x1f\x7f\\]/.test(requested) || requested.split("/").some(part => part === ".." || part.toLowerCase() === ".git" || part === "")) {
|
|
39
|
+
throw new BridgeError(400, "Invalid file path.");
|
|
40
|
+
}
|
|
41
|
+
if (typeof content !== "string")
|
|
42
|
+
throw new BridgeError(400, "Supply the file's text.");
|
|
43
|
+
const bytes = Buffer.from(content, "utf8");
|
|
44
|
+
if (bytes.length > MAX_FILE_RANGE)
|
|
45
|
+
throw new BridgeError(413, "Files over 4 MiB cannot be saved from here.");
|
|
46
|
+
if (expectedVersion !== undefined && (typeof expectedVersion !== "string" || expectedVersion.length > 200))
|
|
47
|
+
throw new BridgeError(400, "Invalid file version.");
|
|
48
|
+
const base = await realpath(root);
|
|
49
|
+
const parts = requested.split("/");
|
|
50
|
+
let directory = base;
|
|
51
|
+
for (const part of parts.slice(0, -1)) {
|
|
52
|
+
directory = path.join(directory, part);
|
|
53
|
+
const info = await lstat(directory).catch(() => undefined);
|
|
54
|
+
if (!info)
|
|
55
|
+
throw new BridgeError(404, "That folder does not exist.");
|
|
56
|
+
if (info.isSymbolicLink())
|
|
57
|
+
throw new BridgeError(403, "Symbolic links cannot be written through.");
|
|
58
|
+
if (!info.isDirectory())
|
|
59
|
+
throw new BridgeError(400, "That folder is not a directory.");
|
|
60
|
+
}
|
|
61
|
+
if ((await realpath(directory)) !== directory)
|
|
62
|
+
throw new BridgeError(403, "This file is outside the repository.");
|
|
63
|
+
const file = path.join(directory, parts[parts.length - 1]);
|
|
64
|
+
if (file !== base && !file.startsWith(base + path.sep))
|
|
65
|
+
throw new BridgeError(403, "This file is outside the repository.");
|
|
66
|
+
const existing = await lstat(file).catch((error) => {
|
|
67
|
+
if (error.code === "ENOENT")
|
|
68
|
+
return undefined;
|
|
69
|
+
throw error;
|
|
70
|
+
});
|
|
71
|
+
if (existing?.isSymbolicLink())
|
|
72
|
+
throw new BridgeError(403, "Symbolic links cannot be written through.");
|
|
73
|
+
if (existing && !existing.isFile())
|
|
74
|
+
throw new BridgeError(400, "Only regular files can be saved.");
|
|
75
|
+
if (expectedVersion === undefined) {
|
|
76
|
+
if (existing)
|
|
77
|
+
throw new BridgeError(409, "A file with that name already exists.", { code: "file-exists" });
|
|
78
|
+
// Exclusive create: a file that appears in between is never overwritten.
|
|
79
|
+
const handle = await open(file, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | constants.O_NOFOLLOW, 0o644).catch((error) => {
|
|
80
|
+
if (error.code === "EEXIST")
|
|
81
|
+
throw new BridgeError(409, "A file with that name already exists.", { code: "file-exists" });
|
|
82
|
+
throw error;
|
|
83
|
+
});
|
|
84
|
+
try {
|
|
85
|
+
await handle.writeFile(bytes);
|
|
86
|
+
await handle.sync();
|
|
87
|
+
}
|
|
88
|
+
finally {
|
|
89
|
+
await handle.close();
|
|
90
|
+
}
|
|
91
|
+
const created = await lstat(file);
|
|
92
|
+
return { path: requested, version: fileVersion(created), size: created.size, created: true };
|
|
93
|
+
}
|
|
94
|
+
if (!existing)
|
|
95
|
+
throw new BridgeError(409, "The file is gone. It changed since you opened it.", { code: "file-changed" });
|
|
96
|
+
if (fileVersion(existing) !== expectedVersion)
|
|
97
|
+
throw new BridgeError(409, "The file changed since you opened it.", { code: "file-changed" });
|
|
98
|
+
const temporary = path.join(directory, `.${parts[parts.length - 1]}.phren-${randomBytes(6).toString("hex")}.tmp`);
|
|
99
|
+
try {
|
|
100
|
+
const handle = await open(temporary, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | constants.O_NOFOLLOW, existing.mode & 0o777);
|
|
101
|
+
try {
|
|
102
|
+
await handle.writeFile(bytes);
|
|
103
|
+
await handle.sync();
|
|
104
|
+
}
|
|
105
|
+
finally {
|
|
106
|
+
await handle.close();
|
|
107
|
+
}
|
|
108
|
+
// Recheck right before the swap so a write that landed meanwhile is not lost.
|
|
109
|
+
const current = await lstat(file).catch(() => undefined);
|
|
110
|
+
if (!current || current.isSymbolicLink() || fileVersion(current) !== expectedVersion) {
|
|
111
|
+
throw new BridgeError(409, "The file changed since you opened it.", { code: "file-changed" });
|
|
112
|
+
}
|
|
113
|
+
await rename(temporary, file);
|
|
114
|
+
}
|
|
115
|
+
finally {
|
|
116
|
+
await rm(temporary, { force: true });
|
|
117
|
+
}
|
|
118
|
+
const saved = await lstat(file);
|
|
119
|
+
return { path: requested, version: fileVersion(saved), size: saved.size, created: false };
|
|
120
|
+
}
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
/** Tokens for the git hosts the Hook reads over HTTP (GitLab, gitboy). GitHub
|
|
2
|
+
* goes through gh, which keeps its own sign-in.
|
|
3
|
+
*
|
|
4
|
+
* A token comes from, in order: the host's own environment variable, the
|
|
5
|
+
* Hook's git-hosts.json (machine config like elevenlabs.json: mode 600, never
|
|
6
|
+
* in the synced store), then the host's CLI where it has one (glab). The Hook
|
|
7
|
+
* runs as a service that doesn't see shell env, so the file is the durable
|
|
8
|
+
* source, written by `phren bridge git-host set` or the desktop's Connect. */
|
|
9
|
+
export type TokenHostKind = "gitlab" | "gitboy";
|
|
10
|
+
export type TokenSource = "environment" | "file" | "cli";
|
|
11
|
+
export interface HostToken {
|
|
12
|
+
token: string;
|
|
13
|
+
source: TokenSource;
|
|
14
|
+
user?: string;
|
|
15
|
+
}
|
|
16
|
+
export declare function gitHostsFile(): string;
|
|
17
|
+
/** Store (or, with an empty token, forget) one domain's token. */
|
|
18
|
+
export declare function writeHostToken(domain: string, kind: TokenHostKind, token: string, user?: string, file?: string): Promise<void>;
|
|
19
|
+
export interface TokenLookup {
|
|
20
|
+
env?: NodeJS.ProcessEnv;
|
|
21
|
+
file?: string;
|
|
22
|
+
cli?: boolean;
|
|
23
|
+
}
|
|
24
|
+
export declare function resolveHostToken(kind: TokenHostKind, domain: string, options?: TokenLookup): Promise<HostToken | undefined>;
|
|
25
|
+
/** Each stored domain with its kind and who it signs in as. Never a token. */
|
|
26
|
+
export declare function listHostTokens(file?: string): Promise<{
|
|
27
|
+
domain: string;
|
|
28
|
+
kind: TokenHostKind;
|
|
29
|
+
user?: string;
|
|
30
|
+
savedAt?: string;
|
|
31
|
+
}[] | "unsafe">;
|