@phren/cli 0.3.50 → 0.3.52

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.
Files changed (36) hide show
  1. package/dist/bridge/computers.js +5 -4
  2. package/dist/bridge/conductor-role.d.ts +4 -0
  3. package/dist/bridge/conductor-role.js +20 -1
  4. package/dist/bridge/dispatch-origins.d.ts +32 -0
  5. package/dist/bridge/dispatch-origins.js +44 -0
  6. package/dist/bridge/dispatch-returns.d.ts +2 -1
  7. package/dist/bridge/dispatch-returns.js +9 -2
  8. package/dist/bridge/dispatch.d.ts +5 -0
  9. package/dist/bridge/dispatch.js +119 -23
  10. package/dist/bridge/gitboy-webhooks.d.ts +25 -0
  11. package/dist/bridge/gitboy-webhooks.js +200 -0
  12. package/dist/bridge/hand-off.d.ts +1 -0
  13. package/dist/bridge/hand-off.js +1 -1
  14. package/dist/bridge/install.d.ts +1 -0
  15. package/dist/bridge/install.js +7 -0
  16. package/dist/bridge/request-origin.d.ts +6 -0
  17. package/dist/bridge/request-origin.js +6 -0
  18. package/dist/bridge/scoped-gateway.d.ts +3 -0
  19. package/dist/bridge/scoped-gateway.js +22 -4
  20. package/dist/bridge/server-routes.d.ts +5 -0
  21. package/dist/bridge/server-routes.js +18 -3
  22. package/dist/bridge/server.js +7 -2
  23. package/dist/bridge/session-move.d.ts +10 -2
  24. package/dist/bridge/session-move.js +124 -12
  25. package/dist/bridge/store-pull.d.ts +22 -0
  26. package/dist/bridge/store-pull.js +62 -0
  27. package/dist/bridge-hook.mjs +3380 -2519
  28. package/dist/modules/registry.js +3 -3
  29. package/dist/sync/gitboy-webhook.d.ts +43 -0
  30. package/dist/sync/gitboy-webhook.js +119 -0
  31. package/dist/sync/pull-now.d.ts +11 -0
  32. package/dist/sync/pull-now.js +64 -0
  33. package/dist/sync/pull.d.ts +1 -1
  34. package/dist/sync/pull.js +4 -4
  35. package/dist/tools/dispatch.js +1 -1
  36. package/package.json +1 -1
@@ -40,7 +40,7 @@ export const BUILTIN_MODULES = [
40
40
  { agents: ["claude", "codex", "copilot", "cursor"], events: ["Stop"], handler: "phren hook-stop" },
41
41
  { agents: ["claude"], events: ["PostToolUse"], handler: "phren hook-tool" },
42
42
  ],
43
- hookRoutes: [...routes("GET", ["/v1/store/head", "/v1/store/tree", "/v1/store/blob"]), ...routes("POST", ["/v1/store/blobs", "/v1/store/file", "/v1/store/delete"])],
43
+ hookRoutes: [...routes("GET", ["/v1/store/head", "/v1/store/tree", "/v1/store/blob"]), ...routes("POST", ["/v1/store/pull-now", "/v1/store/blobs", "/v1/store/file", "/v1/store/delete"])],
44
44
  capabilities: ["memory", "memoryStore", "memoryStoreBatch", "projectMemory"],
45
45
  storeFiles: [
46
46
  "phren.root.yaml", "machines.yaml", "profiles/*.yaml", ".config/modules.yaml", ".config/*.json",
@@ -98,10 +98,10 @@ export const BUILTIN_MODULES = [
98
98
  capabilities: [
99
99
  "hook", "transcript", "progress", "images", "prompt", "stop", "terminal", "shell", "paneTerminal", "paneLayout", "deskPresence", "herdr",
100
100
  "webServers", "webPreview", "activity", "approvals", "questions", "accountUsage", "providers",
101
- "files", "repositoryFiles", "fileResolution", "subagents", "sideQuestions", "approvalPush", "simulators", "overviewStream", "speech", "speechTimestamps", "speechTimestampStream", "speechLive", "speechVoices", "speechFormats", "transcribe", "promptOnce", "promptStatus", "deliveryFrames", "resources", "sessionRename", "sudo", "sudoOutcome", "previewDeltas", "quickChat", "agentFolder", "launchPermissionMode", "sessionMove", "moveNewChat",
101
+ "files", "repositoryFiles", "fileResolution", "subagents", "sideQuestions", "approvalPush", "simulators", "overviewStream", "speech", "speechTimestamps", "speechTimestampStream", "speechLive", "speechVoices", "speechFormats", "transcribe", "promptOnce", "promptStatus", "deliveryFrames", "resources", "sessionRename", "sudo", "sudoOutcome", "previewDeltas", "quickChat", "agentFolder", "launchPermissionMode", "sessionMove", "moveNewChat", "moveConductor",
102
102
  ],
103
103
  storeFiles: [".runtime/sessions/opencode-*.events.jsonl", ".runtime/approvals/opencode-*.json"],
104
- localFiles: ["<bridge>/installed.json", "<bridge>/versions/**", "<bridge>/current", "<bridge>/dispatch", "<bridge>/askpass", "<bridge>/computer-id", "<bridge>/canary.json", "<bridge>/canary-daily", "<bridge>/moves/*.json"],
104
+ localFiles: ["<bridge>/gitboy-webhooks.json", "<bridge>/installed.json", "<bridge>/versions/**", "<bridge>/current", "<bridge>/dispatch", "<bridge>/askpass", "<bridge>/computer-id", "<bridge>/canary.json", "<bridge>/canary-daily", "<bridge>/moves/*.json"],
105
105
  phoneScreens: [{ screen: "LiveSessionsView", capability: "hook" }, { screen: "AgentChatView", capability: "transcript" }],
106
106
  skills: [],
107
107
  },
@@ -0,0 +1,43 @@
1
+ export interface GitboyPushUpdate {
2
+ ref: string;
3
+ old: string;
4
+ new: string;
5
+ /** Files changed between old and new; null when gitboy could not say (new branch, deletion, tag, over budget). */
6
+ changedPaths: string[] | null;
7
+ truncated: boolean;
8
+ }
9
+ export interface GitboyPush {
10
+ deliveryId: string;
11
+ event: "push";
12
+ repository: {
13
+ owner: string;
14
+ name: string;
15
+ } | null;
16
+ updates: GitboyPushUpdate[];
17
+ }
18
+ export interface GitboyStoreRepo {
19
+ owner: string;
20
+ name: string;
21
+ branch: string;
22
+ }
23
+ /** True when `header` is `sha256=<hex HMAC-SHA256 of rawBody>` under `secret`. */
24
+ export declare function verifyGitboySignature(secret: string, rawBody: Buffer, header: string | undefined): boolean;
25
+ type Headers = Record<string, string | string[] | undefined>;
26
+ /** A gitboy `push` delivery, or null for any other event, a missing delivery id or a malformed body. Never throws. */
27
+ export declare function parseGitboyPush(rawBody: Buffer, headers: Headers): GitboyPush | null;
28
+ /**
29
+ * True when the push is to the store's repository (owner and name compared case-insensitively,
30
+ * as gitboy resolves them) and moves `refs/heads/<branch>` exactly.
31
+ */
32
+ export declare function storePushMatches(push: GitboyPush, store: GitboyStoreRepo): boolean;
33
+ export declare const DEFAULT_DELIVERY_LOG_SIZE = 1000;
34
+ /** Recently seen delivery ids, oldest evicted first. gitboy retries keep the delivery id. */
35
+ export declare class DeliveryLog {
36
+ private readonly capacity;
37
+ private readonly ids;
38
+ constructor(capacity?: number);
39
+ /** Records `id` and reports whether it had already been seen. */
40
+ seen(id: string): boolean;
41
+ get size(): number;
42
+ }
43
+ export {};
@@ -0,0 +1,119 @@
1
+ /**
2
+ * Transport-agnostic core for gitboy push webhooks: signature checks, push payload parsing,
3
+ * matching a push to a store's branch, and delivery de-duplication. Used by the optional
4
+ * Hook receiver; periodic polling (pull.ts) stays the fallback.
5
+ */
6
+ import { createHmac, timingSafeEqual } from "crypto";
7
+ const SIGNATURE_PREFIX = "sha256=";
8
+ const SHA256_HEX = /^[0-9a-f]{64}$/i;
9
+ /** True when `header` is `sha256=<hex HMAC-SHA256 of rawBody>` under `secret`. */
10
+ export function verifyGitboySignature(secret, rawBody, header) {
11
+ if (!secret || typeof header !== "string" || !header.startsWith(SIGNATURE_PREFIX))
12
+ return false;
13
+ const hex = header.slice(SIGNATURE_PREFIX.length);
14
+ if (!SHA256_HEX.test(hex))
15
+ return false;
16
+ const expected = createHmac("sha256", secret).update(rawBody).digest();
17
+ const given = Buffer.from(hex, "hex");
18
+ return given.length === expected.length && timingSafeEqual(given, expected);
19
+ }
20
+ function header(headers, name) {
21
+ const wanted = name.toLowerCase();
22
+ for (const [key, value] of Object.entries(headers)) {
23
+ if (key.toLowerCase() !== wanted)
24
+ continue;
25
+ const first = Array.isArray(value) ? value[0] : value;
26
+ return typeof first === "string" ? first : undefined;
27
+ }
28
+ return undefined;
29
+ }
30
+ function isRecord(value) {
31
+ return typeof value === "object" && value !== null && !Array.isArray(value);
32
+ }
33
+ /** gitboy's push payload names the repository `full_name: "owner/name"` beside `name`. */
34
+ function parseRepository(value) {
35
+ if (!isRecord(value) || typeof value.full_name !== "string")
36
+ return null;
37
+ const slash = value.full_name.indexOf("/");
38
+ if (slash <= 0)
39
+ return null;
40
+ const owner = value.full_name.slice(0, slash);
41
+ const name = value.full_name.slice(slash + 1);
42
+ if (!name || name.includes("/"))
43
+ return null;
44
+ return { owner, name };
45
+ }
46
+ function parseUpdate(value) {
47
+ if (!isRecord(value))
48
+ return null;
49
+ const { ref, old, new: next } = value;
50
+ if (typeof ref !== "string" || typeof old !== "string" || typeof next !== "string")
51
+ return null;
52
+ const paths = value.changed_paths;
53
+ const changedPaths = Array.isArray(paths) && paths.every((p) => typeof p === "string") ? paths : null;
54
+ return { ref, old, new: next, changedPaths, truncated: value.changed_paths_truncated === true };
55
+ }
56
+ /** A gitboy `push` delivery, or null for any other event, a missing delivery id or a malformed body. Never throws. */
57
+ export function parseGitboyPush(rawBody, headers) {
58
+ if (header(headers, "x-gitboy-event") !== "push")
59
+ return null;
60
+ const deliveryId = header(headers, "x-gitboy-delivery");
61
+ if (!deliveryId)
62
+ return null;
63
+ let payload;
64
+ try {
65
+ payload = JSON.parse(rawBody.toString("utf8"));
66
+ }
67
+ catch {
68
+ return null;
69
+ }
70
+ if (!isRecord(payload) || !Array.isArray(payload.updates))
71
+ return null;
72
+ const updates = [];
73
+ for (const entry of payload.updates) {
74
+ const update = parseUpdate(entry);
75
+ if (update)
76
+ updates.push(update);
77
+ }
78
+ return { deliveryId, event: "push", repository: parseRepository(payload.repository), updates };
79
+ }
80
+ /**
81
+ * True when the push is to the store's repository (owner and name compared case-insensitively,
82
+ * as gitboy resolves them) and moves `refs/heads/<branch>` exactly.
83
+ */
84
+ export function storePushMatches(push, store) {
85
+ const repo = push.repository;
86
+ if (!repo || !store.branch)
87
+ return false;
88
+ if (repo.owner.toLowerCase() !== store.owner.toLowerCase())
89
+ return false;
90
+ if (repo.name.toLowerCase() !== store.name.toLowerCase())
91
+ return false;
92
+ const ref = `refs/heads/${store.branch}`;
93
+ return push.updates.some((update) => update.ref === ref);
94
+ }
95
+ export const DEFAULT_DELIVERY_LOG_SIZE = 1_000;
96
+ /** Recently seen delivery ids, oldest evicted first. gitboy retries keep the delivery id. */
97
+ export class DeliveryLog {
98
+ capacity;
99
+ ids = new Set();
100
+ constructor(capacity = DEFAULT_DELIVERY_LOG_SIZE) {
101
+ this.capacity = capacity;
102
+ }
103
+ /** Records `id` and reports whether it had already been seen. */
104
+ seen(id) {
105
+ if (this.ids.has(id))
106
+ return true;
107
+ this.ids.add(id);
108
+ while (this.ids.size > this.capacity) {
109
+ const oldest = this.ids.values().next().value;
110
+ if (oldest === undefined)
111
+ break;
112
+ this.ids.delete(oldest);
113
+ }
114
+ return false;
115
+ }
116
+ get size() {
117
+ return this.ids.size;
118
+ }
119
+ }
@@ -0,0 +1,11 @@
1
+ import { type PullResult } from "./pull.js";
2
+ /** One running pull and one pending wakeup per store; also respects sibling-process locks. */
3
+ export declare class ImmediatePulls {
4
+ private readonly pull;
5
+ private readonly intervalMs;
6
+ private readonly states;
7
+ private stopped;
8
+ constructor(pull?: (store: string) => Promise<PullResult>, intervalMs?: number);
9
+ request(store: string): void;
10
+ stop(): void;
11
+ }
@@ -0,0 +1,64 @@
1
+ import { pollStore } from "./pull.js";
2
+ /** One running pull and one pending wakeup per store; also respects sibling-process locks. */
3
+ export class ImmediatePulls {
4
+ pull;
5
+ intervalMs;
6
+ states = new Map();
7
+ stopped = false;
8
+ constructor(pull = store => pollStore(store, 0, undefined, Date.now(), true), intervalMs = 10_000) {
9
+ this.pull = pull;
10
+ this.intervalMs = intervalMs;
11
+ }
12
+ request(store) {
13
+ if (this.stopped)
14
+ return;
15
+ let state = this.states.get(store);
16
+ if (!state) {
17
+ state = { pending: false, running: false, last: -Infinity, retries: 0 };
18
+ this.states.set(store, state);
19
+ }
20
+ state.pending = true;
21
+ state.retries = 0;
22
+ if (state.running || state.timer)
23
+ return;
24
+ const run = async () => {
25
+ state.timer = undefined;
26
+ if (this.stopped)
27
+ return;
28
+ state.pending = false;
29
+ state.running = true;
30
+ state.last = Date.now();
31
+ try {
32
+ const result = await this.pull(store);
33
+ // A sibling process may own either coordination lock. Keep one wakeup until it releases.
34
+ if (result.status === "deferred" && (result.detail === "Coordinated pull is running."
35
+ || result.detail === "Periodic pull deferred: another Phren Git operation is running."
36
+ || result.detail === "Periodic pull deferred: a Git operation is in progress.")) {
37
+ if (state.retries < 2) {
38
+ state.retries++;
39
+ state.pending = true;
40
+ }
41
+ }
42
+ else
43
+ state.retries = 0;
44
+ }
45
+ catch { /* The next nudge or fallback poll retries failures. */ }
46
+ finally {
47
+ state.running = false;
48
+ if (state.pending && !this.stopped)
49
+ schedule();
50
+ }
51
+ };
52
+ const schedule = () => {
53
+ const delay = Math.max(0, state.last + this.intervalMs * Math.max(1, state.retries) - Date.now());
54
+ state.timer = setTimeout(() => { void run(); }, delay);
55
+ state.timer.unref();
56
+ };
57
+ schedule();
58
+ }
59
+ stop() {
60
+ this.stopped = true;
61
+ for (const state of this.states.values())
62
+ clearTimeout(state.timer);
63
+ }
64
+ }
@@ -27,7 +27,7 @@ export interface PullResult {
27
27
  */
28
28
  export declare function readPollState(phrenPath: string): PollState;
29
29
  /** Shared timestamps + a process lock give all MCP clients one check per store/interval. */
30
- export declare function pollStore(phrenPath: string, seconds: number, git?: RunGit, now?: number): Promise<PullResult>;
30
+ export declare function pollStore(phrenPath: string, seconds: number, git?: RunGit, now?: number, immediate?: boolean): Promise<PullResult>;
31
31
  interface PollingOptions {
32
32
  onChange: () => Promise<void>;
33
33
  /** Share the MCP write queue so background updates cannot overlap its writes. */
package/dist/sync/pull.js CHANGED
@@ -104,13 +104,13 @@ function logPeriodicSync(phrenPath, detail) {
104
104
  appendSyncLog(phrenPath, "periodic-pull", detail);
105
105
  }
106
106
  /** Shared timestamps + a process lock give all MCP clients one check per store/interval. */
107
- export async function pollStore(phrenPath, seconds, git = runPollGit, now = Date.now()) {
107
+ export async function pollStore(phrenPath, seconds, git = runPollGit, now = Date.now(), immediate = false) {
108
108
  const skipped = { status: "not-due", detail: "Periodic check not due." };
109
- if (!seconds || !periodicPullEnabled(phrenPath) || !fs.existsSync(path.join(phrenPath, ".git")))
109
+ if ((!seconds && !immediate) || !periodicPullEnabled(phrenPath) || !fs.existsSync(path.join(phrenPath, ".git")))
110
110
  return skipped;
111
111
  const releasePoll = tryFileLock(runtimeFile(phrenPath, "pull-poll"));
112
112
  if (!releasePoll)
113
- return skipped;
113
+ return immediate ? { status: "deferred", detail: "Coordinated pull is running." } : skipped;
114
114
  try {
115
115
  const auth = activeStoreAuthFailure(phrenPath);
116
116
  if (authBackoffActive(auth, now))
@@ -119,7 +119,7 @@ export async function pollStore(phrenPath, seconds, git = runPollGit, now = Date
119
119
  const previous = readPollState(phrenPath);
120
120
  const failures = Math.min(10, Math.max(0, Number(previous.failures) || 0));
121
121
  const delay = Math.min(seconds * 2 ** failures, Math.max(seconds, 1800)) * 1000;
122
- if (typeof previous.checkedAt === "number" && now >= previous.checkedAt && now - previous.checkedAt < delay)
122
+ if (!immediate && typeof previous.checkedAt === "number" && now >= previous.checkedAt && now - previous.checkedAt < delay)
123
123
  return skipped;
124
124
  const finish = async (result, verifiedRemote = false) => {
125
125
  atomicWriteText(runtimeFile(phrenPath, "pull-poll.json"), JSON.stringify({
@@ -141,7 +141,7 @@ export function register(server) {
141
141
  inputSchema: moveSessionSchema,
142
142
  }, async (input) => {
143
143
  try {
144
- const result = await moveSession(input);
144
+ const result = await moveSession(input, { agent: true });
145
145
  const move = result.move;
146
146
  const message = move.state === "moved" ? `Moved to ${String(object(move.to).harness)} (${String(move.placement)}); hand-off at ${String(object(move.handoff).path)}.`
147
147
  : move.state === "failed" ? `Move failed: ${String(move.error ?? "unknown error")}` : `Move ${String(move.id)} is ${String(move.state)}; check again with status:true.`;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@phren/cli",
3
- "version": "0.3.50",
3
+ "version": "0.3.52",
4
4
  "description": "Knowledge layer for AI agents - CLI, MCP server, and data layer",
5
5
  "type": "module",
6
6
  "bin": {