@phren/cli 0.3.1 → 0.3.3

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.
@@ -28275,7 +28275,7 @@ var init_package_metadata = __esm({
28275
28275
  __dirname = path24.dirname(fileURLToPath2(import.meta.url));
28276
28276
  ROOT = path24.join(__dirname, "..");
28277
28277
  PACKAGE_JSON_PATH = path24.join(ROOT, "package.json");
28278
- BUNDLED_VERSION = true ? "0.3.1" : "0.0.0";
28278
+ BUNDLED_VERSION = true ? "0.3.3" : "0.0.0";
28279
28279
  PACKAGE_JSON = readPackageJson();
28280
28280
  PACKAGE_NAME = PACKAGE_JSON.name || "phren";
28281
28281
  VERSION = PACKAGE_JSON.version || BUNDLED_VERSION;
@@ -30522,7 +30522,7 @@ var require_websocket = __commonJS({
30522
30522
  var http = __require("http");
30523
30523
  var net = __require("net");
30524
30524
  var tls = __require("tls");
30525
- var { randomBytes: randomBytes4, createHash: createHash19 } = __require("crypto");
30525
+ var { randomBytes: randomBytes5, createHash: createHash19 } = __require("crypto");
30526
30526
  var { Duplex: Duplex2, Readable } = __require("stream");
30527
30527
  var { URL: URL2 } = __require("url");
30528
30528
  var PerMessageDeflate2 = require_permessage_deflate();
@@ -31060,7 +31060,7 @@ var require_websocket = __commonJS({
31060
31060
  }
31061
31061
  }
31062
31062
  const defaultPort = isSecure ? 443 : 80;
31063
- const key = randomBytes4(16).toString("base64");
31063
+ const key = randomBytes5(16).toString("base64");
31064
31064
  const request6 = isSecure ? https.request : http.request;
31065
31065
  const protocolSet = /* @__PURE__ */ new Set();
31066
31066
  let perMessageDeflate;
@@ -33310,6 +33310,7 @@ var BUILTIN_MODULES = [
33310
33310
  "simulators",
33311
33311
  "overviewStream",
33312
33312
  "speech",
33313
+ "speechTimestamps",
33313
33314
  "transcribe"
33314
33315
  ],
33315
33316
  storeFiles: [".runtime/sessions/opencode-*.events.jsonl", ".runtime/approvals/opencode-*.json"],
@@ -34506,17 +34507,28 @@ async function removeGrant(input2, root = bridgeRoot()) {
34506
34507
  // src/bridge/push.ts
34507
34508
  init_zod();
34508
34509
  init_protocol();
34509
- import { createPrivateKey, sign } from "node:crypto";
34510
+ import { createCipheriv, createHmac as createHmac2, createPrivateKey, randomBytes as randomBytes3, sign } from "node:crypto";
34510
34511
  import { readFile as readFile12, stat as stat9 } from "node:fs/promises";
34511
34512
  import { connect as connect2 } from "node:http2";
34512
34513
  import path34 from "node:path";
34514
+ var relaySchema = external_exports.object({
34515
+ url: external_exports.string().url().refine(
34516
+ (value2) => /^https:\/\//.test(value2) || /^http:\/\/(127\.0\.0\.1|localhost)(:\d+)?\//.test(`${value2}/`),
34517
+ "The relay must use https."
34518
+ ),
34519
+ relayId: external_exports.string().regex(/^[A-Za-z0-9_-]{40,400}$/),
34520
+ secret: external_exports.string().regex(/^[A-Za-z0-9_-]{20,100}$/),
34521
+ key: external_exports.string().regex(/^[A-Za-z0-9_-]{43}$/)
34522
+ });
34513
34523
  var deviceSchema = external_exports.object({
34514
34524
  deviceID: external_exports.string().uuid(),
34515
34525
  hostID: external_exports.string().uuid(),
34516
- token: external_exports.string().regex(/^[0-9a-f]{64}$/),
34526
+ /** The APNs token, for a Hook with its own key (apns.json). */
34527
+ token: external_exports.string().regex(/^[0-9a-f]{64}$/).optional(),
34528
+ relay: relaySchema.optional(),
34517
34529
  environment: external_exports.enum(["development", "production"]),
34518
34530
  kinds: external_exports.array(external_exports.enum(["approval", "scheduleStarted", "scheduleFinished", "scheduleFailed", "scheduleBlocked"])).max(5).default(["approval"])
34519
- });
34531
+ }).refine((device) => device.token !== void 0 || device.relay !== void 0, "A phone needs an APNs token or a relay registration.");
34520
34532
  var configSchema2 = external_exports.object({
34521
34533
  keyId: external_exports.string().regex(/^[A-Z0-9]{10}$/),
34522
34534
  teamId: external_exports.string().regex(/^[A-Z0-9]{10}$/),
@@ -34596,13 +34608,62 @@ function apnsSetupSteps(configFile = process.env.PHREN_APNS_CONFIG || path34.joi
34596
34608
  ].join("\n");
34597
34609
  }
34598
34610
  function approvalPushCapability(status) {
34599
- return status.configured ? "direct-apns" : void 0;
34611
+ if (!status.configured) return void 0;
34612
+ return status.direct === false ? "relay" : "direct-apns";
34600
34613
  }
34601
34614
  function upsertPushDevice(devices, value2) {
34602
34615
  const device = deviceSchema.parse(value2);
34603
34616
  return [...devices.filter((item) => item.deviceID !== device.deviceID), device].slice(-16);
34604
34617
  }
34605
34618
  var base64url3 = (value2) => Buffer.from(value2).toString("base64url");
34619
+ var RELAY_MAX_CIPHERTEXT = 2800;
34620
+ function relayCiphertext(key, payload, nonce = randomBytes3(12)) {
34621
+ const aps = payload.aps ?? {};
34622
+ let body2 = aps.alert?.body ?? "";
34623
+ for (; ; ) {
34624
+ const content = JSON.stringify({
34625
+ t: aps.alert?.title ?? "phren",
34626
+ b: body2,
34627
+ ...aps.category ? { c: aps.category } : {},
34628
+ ...aps["interruption-level"] ? { i: aps["interruption-level"] } : {},
34629
+ ...payload.phren ? { p: payload.phren } : {}
34630
+ });
34631
+ const cipher = createCipheriv("chacha20-poly1305", Buffer.from(key, "base64url"), nonce, { authTagLength: 16 });
34632
+ const sealed = Buffer.concat([nonce, cipher.update(content, "utf8"), cipher.final(), cipher.getAuthTag()]).toString("base64url");
34633
+ if (sealed.length <= RELAY_MAX_CIPHERTEXT || !body2) return sealed;
34634
+ body2 = body2.length > 40 ? `${body2.slice(0, Math.floor(body2.length * 0.8))}\u2026` : "";
34635
+ }
34636
+ }
34637
+ function relaySignature(secret, timestamp4, body2) {
34638
+ return createHmac2("sha256", secret).update(`${timestamp4}.${body2}`).digest("base64url");
34639
+ }
34640
+ async function sendThroughRelay(relay2, payload, headers, fetcher = fetch, now = Date.now) {
34641
+ const aps = payload.aps ?? {};
34642
+ const body2 = JSON.stringify({
34643
+ kind: "alert",
34644
+ ciphertext: relayCiphertext(relay2.key, payload),
34645
+ collapseId: headers.collapseId.slice(0, 64),
34646
+ expiration: Number(headers.expiration) || 0,
34647
+ ...aps.category ? { category: aps.category } : {}
34648
+ });
34649
+ const timestamp4 = String(Math.floor(now() / 1e3));
34650
+ try {
34651
+ const response = await fetcher(`${relay2.url.replace(/\/+$/, "")}/v1/send`, {
34652
+ method: "POST",
34653
+ body: body2,
34654
+ signal: AbortSignal.timeout(1e4),
34655
+ headers: {
34656
+ "content-type": "application/json",
34657
+ "x-phren-relay": relay2.relayId,
34658
+ "x-phren-timestamp": timestamp4,
34659
+ "x-phren-signature": relaySignature(relay2.secret, timestamp4, body2)
34660
+ }
34661
+ });
34662
+ return response.status === 410 ? "gone" : response.ok ? "sent" : "failed";
34663
+ } catch {
34664
+ return "failed";
34665
+ }
34666
+ }
34606
34667
  var APNsSender = class {
34607
34668
  constructor(config3, key, now = Date.now) {
34608
34669
  this.config = config3;
@@ -34669,21 +34730,44 @@ var ApprovalPushService = class {
34669
34730
  const key = await secureFile(keyPath);
34670
34731
  if (key) this.sender = new APNsSender(config3, key);
34671
34732
  }
34733
+ /** Phones this Hook can reach: through the relay, or direct with its own key. */
34734
+ get reachable() {
34735
+ return this.devices.filter((device) => device.relay || this.sender && device.token);
34736
+ }
34672
34737
  get available() {
34673
- return this.sender !== void 0 && this.devices.length > 0;
34738
+ return this.reachable.length > 0;
34674
34739
  }
34675
34740
  get status() {
34676
- return { supported: true, configured: this.sender !== void 0, devices: this.devices.length };
34741
+ const relay2 = this.devices.filter((device) => device.relay).length;
34742
+ return {
34743
+ supported: true,
34744
+ configured: this.sender !== void 0 || relay2 > 0,
34745
+ direct: this.sender !== void 0,
34746
+ devices: this.devices.length,
34747
+ relay: relay2
34748
+ };
34677
34749
  }
34678
34750
  async register(value2) {
34679
34751
  this.devices = upsertPushDevice(this.devices, value2);
34680
34752
  await atomic(this.devicesFile, JSON.stringify(this.devices));
34681
34753
  }
34754
+ /** One phone: the relay when it registered through one, otherwise direct. */
34755
+ async send(device, payload, headers) {
34756
+ if (device.relay) {
34757
+ const result = await sendThroughRelay(device.relay, payload, headers);
34758
+ if (result === "gone") {
34759
+ this.devices = this.devices.filter((item) => item.deviceID !== device.deviceID);
34760
+ await atomic(this.devicesFile, JSON.stringify(this.devices)).catch(() => {
34761
+ });
34762
+ }
34763
+ return result === "sent";
34764
+ }
34765
+ return this.sender && device.token ? this.sender.send(device, payload, headers) : false;
34766
+ }
34682
34767
  async notify(value2) {
34683
- if (!this.sender || !this.devices.length) return false;
34684
- const devices = this.devices.filter((device) => device.kinds.includes("approval"));
34768
+ const devices = this.reachable.filter((device) => device.kinds.includes("approval"));
34685
34769
  if (!devices.length) return false;
34686
- return (await Promise.all(devices.map((device) => this.sender.send(device, approvalPushPayload(value2, device.hostID), {
34770
+ return (await Promise.all(devices.map((device) => this.send(device, approvalPushPayload(value2, device.hostID), {
34687
34771
  expiration: String(Math.floor(Date.parse(value2.expiresAt) / 1e3)),
34688
34772
  collapseId: value2.binding
34689
34773
  })))).some(Boolean);
@@ -34692,21 +34776,21 @@ var ApprovalPushService = class {
34692
34776
  * phones already accept agent alerts; the payload carries the reason so the
34693
34777
  * notification is actionable on its own. */
34694
34778
  async notifyFanoutBlocked(value2) {
34695
- if (!this.sender || !this.devices.length) return false;
34696
- const devices = this.devices.filter((device) => device.kinds.includes("approval"));
34779
+ const devices = this.reachable.filter((device) => device.kinds.includes("approval"));
34697
34780
  if (!devices.length) return false;
34698
- return (await Promise.all(devices.map((device) => this.sender.send(device, fanoutBlockedPushPayload(value2), {
34781
+ return (await Promise.all(devices.map((device) => this.send(device, fanoutBlockedPushPayload(value2), {
34699
34782
  expiration: "0",
34700
34783
  collapseId: `fanout-${value2.job}`
34701
34784
  })))).some(Boolean);
34702
34785
  }
34703
34786
  async notifySchedule(value2) {
34704
- if (!this.sender) return { notified: false, reason: "no push config" };
34705
- let devices = this.devices.filter((device) => device.kinds.includes(value2.kind));
34706
- if (!devices.length && value2.kind === "scheduleBlocked") devices = this.devices.filter((device) => device.kinds.includes("scheduleFailed"));
34787
+ const reachable = this.reachable;
34788
+ if (!reachable.length) return { notified: false, reason: this.sender || this.devices.length ? "no registered devices" : "no push config" };
34789
+ let devices = reachable.filter((device) => device.kinds.includes(value2.kind));
34790
+ if (!devices.length && value2.kind === "scheduleBlocked") devices = reachable.filter((device) => device.kinds.includes("scheduleFailed"));
34707
34791
  if (!devices.length) return { notified: false, reason: "no registered devices" };
34708
34792
  try {
34709
- const notified = (await Promise.all(devices.map((device) => this.sender.send(device, schedulePushPayload(value2), {
34793
+ const notified = (await Promise.all(devices.map((device) => this.send(device, schedulePushPayload(value2), {
34710
34794
  expiration: "0",
34711
34795
  collapseId: scheduleCollapseId(value2.kind, value2.runId)
34712
34796
  })))).some(Boolean);
@@ -35798,6 +35882,25 @@ var AgentHooks = class {
35798
35882
  if (!entry.response.destroyed) entry.response.end("{}");
35799
35883
  }
35800
35884
  }
35885
+ /** The phone's Esc or Cancel on a question the Hook holds. A held
35886
+ * AskUserQuestion has no terminal choice, so `releaseChoice` never lets it
35887
+ * go and the terminal stays frozen until the hold timer; decline it now so
35888
+ * Claude moves on. True when a held question was cancelled. */
35889
+ cancelHeldQuestion(target) {
35890
+ let cancelled = false;
35891
+ for (const [id2, entry] of this.pending) {
35892
+ if (entry.tool !== "AskUserQuestion" || JSON.stringify(entry.target) !== JSON.stringify(target)) continue;
35893
+ this.pending.delete(id2);
35894
+ this.dropPushBindings(id2);
35895
+ clearTimeout(entry.timer);
35896
+ if (!entry.response.destroyed) entry.response.end(JSON.stringify({ hookSpecificOutput: {
35897
+ hookEventName: "PermissionRequest",
35898
+ decision: { behavior: "deny", message: "The user cancelled this question in Phren without answering." }
35899
+ } }));
35900
+ cancelled = true;
35901
+ }
35902
+ return cancelled;
35903
+ }
35801
35904
  async answerPush(binding, decision) {
35802
35905
  if (!["approve", "deny"].includes(String(decision))) throw new BridgeError(400, "The approval answer is not valid.");
35803
35906
  const linked = this.pushBindings.consume(binding);
@@ -44452,6 +44555,8 @@ function conflictStrategy(relFile) {
44452
44555
  if (/^\.config\/task-archive\/[^/]+\.md$/i.test(file2)) return "archive";
44453
44556
  if (/(^|\/)reference\/topics\/[^/]+\.md$/i.test(file2)) return "topic";
44454
44557
  if (name === "summary.md") return "summary";
44558
+ if (name === "review.md") return "union";
44559
+ if (/(^|\/)(notes|journal)\/[^/]+\.md$/i.test(file2)) return "union";
44455
44560
  return null;
44456
44561
  }
44457
44562
  function git4(cwd, args) {
@@ -44491,11 +44596,26 @@ function mergeText(base, ours, theirs) {
44491
44596
  fs32.rmSync(dir, { recursive: true, force: true });
44492
44597
  }
44493
44598
  }
44494
- function mergeWithGeneratedBlock(base, ours, theirs, start, end, where) {
44599
+ function unionText(base, ours, theirs) {
44600
+ const clean2 = mergeText(base, ours, theirs);
44601
+ if (clean2 !== null) return clean2;
44602
+ const dir = fs32.mkdtempSync(path65.join(os3.tmpdir(), "phren-merge-"));
44603
+ try {
44604
+ const [o, b, t] = ["ours", "base", "theirs"].map((name) => path65.join(dir, name));
44605
+ fs32.writeFileSync(o, ours);
44606
+ fs32.writeFileSync(b, base);
44607
+ fs32.writeFileSync(t, theirs);
44608
+ const result = spawnSync2("git", ["merge-file", "--union", "-p", o, b, t], { encoding: "utf8", env: nonInteractiveGitEnv(), timeout: EXEC_TIMEOUT_MS });
44609
+ return result.status === 0 ? result.stdout : null;
44610
+ } finally {
44611
+ fs32.rmSync(dir, { recursive: true, force: true });
44612
+ }
44613
+ }
44614
+ function mergeWithGeneratedBlock(base, ours, theirs, start, end, where, merge2 = unionText) {
44495
44615
  const b = splitBlock(base, start, end);
44496
44616
  const o = splitBlock(ours, start, end);
44497
44617
  const t = splitBlock(theirs, start, end);
44498
- const rest = mergeText(b.rest, o.rest, t.rest);
44618
+ const rest = merge2(b.rest, o.rest, t.rest);
44499
44619
  if (rest === null) return null;
44500
44620
  const block = t.block ?? o.block;
44501
44621
  if (!block) return rest;
@@ -44512,8 +44632,13 @@ function resolveContent(strategy, base, ours, theirs) {
44512
44632
  return mergeTask(theirs, ours);
44513
44633
  case "topic":
44514
44634
  return mergeWithGeneratedBlock(base, ours, theirs, NOW_START, NOW_END, "top");
44635
+ // Summaries are regenerated from the store: when the hand-written part
44636
+ // doesn't merge cleanly, take the incoming file whole and let the next
44637
+ // summarize pass fold in anything only this machine had.
44515
44638
  case "summary":
44516
- return mergeWithGeneratedBlock(base, ours, theirs, KNOWS_START, KNOWS_END, "bottom");
44639
+ return mergeWithGeneratedBlock(base, ours, theirs, KNOWS_START, KNOWS_END, "bottom", mergeText) ?? theirs;
44640
+ case "union":
44641
+ return unionText(base, ours, theirs);
44517
44642
  }
44518
44643
  }
44519
44644
  function resolveStoreConflicts(cwd) {
@@ -46764,8 +46889,11 @@ async function paneRoute(ctx, url2, data, response) {
46764
46889
  const keys = external_exports.array(external_exports.enum(ANSWER_KEYS)).min(1).max(4).parse(data.keys);
46765
46890
  const status = String(pane.agent_status), menu = agentHooks.menuOpen(target);
46766
46891
  const holding = menu || !!agentHooks.terminalPrompt(target);
46767
- if (!holding && (keys.every((key) => key === "Escape") ? !["working", "blocked", "waiting", "unknown"].includes(status) : !["blocked", "waiting", "unknown"].includes(status))) throw new BridgeError(409, keys.every((key) => key === "Escape") ? "This agent is no longer working." : "This agent is not waiting for an answer.");
46768
- if (await agentHooks.answerReleasedQuestion(target, keys)) {
46892
+ const cancelled = keys.every((key) => key === "Escape") && agentHooks.cancelHeldQuestion(target);
46893
+ if (!cancelled && !holding && (keys.every((key) => key === "Escape") ? !["working", "blocked", "waiting", "unknown"].includes(status) : !["blocked", "waiting", "unknown"].includes(status))) throw new BridgeError(409, keys.every((key) => key === "Escape") ? "This agent is no longer working." : "This agent is not waiting for an answer.");
46894
+ if (cancelled) {
46895
+ result = { ok: true };
46896
+ } else if (await agentHooks.answerReleasedQuestion(target, keys)) {
46769
46897
  result = { ok: true };
46770
46898
  } else {
46771
46899
  const answerKeys = await agentHooks.dialogAnswerKeys(target, keys);
@@ -47126,7 +47254,12 @@ var OUTPUT_FORMAT = "pcm_24000";
47126
47254
  var SPEECH_MODEL = "eleven_flash_v2_5";
47127
47255
  var DEFAULT_SPEECH_VOICE = "SAz9YHcvj6GT2YYXdXww";
47128
47256
  var MAX_TEXT = 2e3;
47129
- var speechRequest = external_exports.object({ text: external_exports.string().trim().min(1).max(MAX_TEXT) });
47257
+ var speechRequest = external_exports.object({
47258
+ text: external_exports.string().trim().min(1).max(MAX_TEXT),
47259
+ /** Answer JSON with the audio and when each character is spoken, so the
47260
+ * phone can highlight the word being read (talk mode's karaoke). */
47261
+ timestamps: external_exports.boolean().optional()
47262
+ });
47130
47263
  async function speechError(upstream) {
47131
47264
  let detail = "";
47132
47265
  try {
@@ -47149,11 +47282,41 @@ async function speechError(upstream) {
47149
47282
  return new BridgeError(502, `ElevenLabs failed (HTTP ${upstream.status}).`, { code: "speech-failed" });
47150
47283
  }
47151
47284
  }
47285
+ function speakableText(text3) {
47286
+ return text3.replace(/```[\s\S]*?(?:```|$)/g, " ").replace(/!\[([^\]]*)\]\([^)]*\)/g, "$1").replace(/\[([^\]]+)\]\([^)]*\)/g, "$1").replace(/https?:\/\/\S+/g, "a link").replace(/`([^`]*)`/g, "$1").split(/\r?\n/).map((line) => {
47287
+ const block = /^\s{0,3}(?:#{1,6}\s|[-*+]\s|\d+[.)]\s|\|)/.test(line);
47288
+ const words = line.replace(/^\s*\|?[\s:|-]*-[\s:|-]*\|?\s*$/, "").replace(/^\s{0,3}(?:#{1,6}\s+|>\s?|[-*+]\s+(?:\[[ xX]\]\s+)?)/, "").replace(/\s*\|\s*/g, (bar, offset, whole) => offset === 0 || offset + bar.length === whole.length ? "" : ", ").replace(/(\*\*|__|~~)(.+?)\1/g, "$2").replace(/(^|[^\w*])[*_](\S(?:.*?\S)?)[*_](?![\w*])/g, "$1$2").trim();
47289
+ return block && words && !/[.!?:;,]$/.test(words) ? `${words}.` : words;
47290
+ }).filter(Boolean).join(" ").replace(/\s+/g, " ").trim();
47291
+ }
47152
47292
  async function synthesizeSpeech(text3, signal, options = {}) {
47293
+ const upstream = await elevenLabs("stream", text3, signal, options);
47294
+ if (!upstream.body) throw await speechError(upstream);
47295
+ return upstream.body;
47296
+ }
47297
+ async function synthesizeTimedSpeech(text3, signal, options = {}) {
47298
+ const upstream = await elevenLabs("with-timestamps", text3, signal, options);
47299
+ let body2;
47300
+ try {
47301
+ body2 = await upstream.json();
47302
+ } catch {
47303
+ throw new BridgeError(502, "ElevenLabs sent an unreadable reply.", { code: "speech-failed" });
47304
+ }
47305
+ if (typeof body2.audio_base64 !== "string") throw new BridgeError(502, "ElevenLabs sent an unreadable reply.", { code: "speech-failed" });
47306
+ return { audio: body2.audio_base64, alignment: alignmentOf(body2.alignment) };
47307
+ }
47308
+ function alignmentOf(raw) {
47309
+ const characters = raw?.characters, starts = raw?.character_start_times_seconds, ends = raw?.character_end_times_seconds;
47310
+ if (!Array.isArray(characters) || !Array.isArray(starts) || !Array.isArray(ends)) return null;
47311
+ if (characters.length !== starts.length || characters.length !== ends.length) return null;
47312
+ if (!characters.every((c) => typeof c === "string") || ![...starts, ...ends].every((t) => typeof t === "number" && Number.isFinite(t))) return null;
47313
+ return { characters, starts, ends };
47314
+ }
47315
+ async function elevenLabs(endpoint, text3, signal, options) {
47153
47316
  const key = await (options.key ?? readSpeechKey)();
47154
47317
  if (!key) throw new BridgeError(503, "Spoken replies aren't set up on this computer: it has no ElevenLabs key.", { code: "speech-unconfigured" });
47155
47318
  const voice = options.voice ?? process.env.PHREN_SPEECH_VOICE ?? DEFAULT_SPEECH_VOICE;
47156
- const url2 = `https://api.elevenlabs.io/v1/text-to-speech/${encodeURIComponent(voice)}/stream?output_format=${OUTPUT_FORMAT}`;
47319
+ const url2 = `https://api.elevenlabs.io/v1/text-to-speech/${encodeURIComponent(voice)}/${endpoint}?output_format=${OUTPUT_FORMAT}`;
47157
47320
  let upstream;
47158
47321
  try {
47159
47322
  upstream = await (options.fetch ?? fetch)(url2, {
@@ -47165,15 +47328,25 @@ async function synthesizeSpeech(text3, signal, options = {}) {
47165
47328
  } catch {
47166
47329
  throw new BridgeError(502, "Couldn't reach ElevenLabs from this computer.", { code: "speech-unreachable" });
47167
47330
  }
47168
- if (!upstream.ok || !upstream.body) throw await speechError(upstream);
47169
- return upstream.body;
47331
+ if (!upstream.ok) throw await speechError(upstream);
47332
+ return upstream;
47170
47333
  }
47171
47334
  async function streamSpeech(data, response, options = {}) {
47172
- const { text: text3 } = speechRequest.parse(data);
47335
+ const request6 = speechRequest.parse(data);
47336
+ const text3 = speakableText(request6.text);
47337
+ if (!text3) throw new BridgeError(400, "There is nothing to say in this reply.", { code: "speech-invalid" });
47338
+ const { timestamps } = request6;
47173
47339
  const abort = new AbortController();
47174
47340
  response.once("close", () => {
47175
47341
  if (!response.writableEnded) abort.abort();
47176
47342
  });
47343
+ if (timestamps) {
47344
+ const { audio: audio2, alignment } = await synthesizeTimedSpeech(text3, abort.signal, options);
47345
+ response.statusCode = 200;
47346
+ response.setHeader("Content-Type", "application/json");
47347
+ response.end(JSON.stringify({ audio: audio2, audioFormat: SPEECH_AUDIO, alignment }));
47348
+ return;
47349
+ }
47177
47350
  const audio = await synthesizeSpeech(text3, abort.signal, options);
47178
47351
  response.statusCode = 200;
47179
47352
  response.setHeader("Content-Type", "application/octet-stream");
@@ -47232,6 +47405,7 @@ var capabilities = {
47232
47405
  code: true,
47233
47406
  overviewStream: true,
47234
47407
  speech: true,
47408
+ speechTimestamps: true,
47235
47409
  transcribe: true,
47236
47410
  memoryStore: true
47237
47411
  };
@@ -48833,7 +49007,8 @@ async function runBridge(args, version3) {
48833
49007
  return 0;
48834
49008
  }
48835
49009
  function approvalPushCheck(helper2) {
48836
- const configured = object2(helper2.capabilities).approvalPush === "direct-apns";
49010
+ const capability = object2(helper2.capabilities).approvalPush;
49011
+ const configured = capability === "direct-apns" || capability === "relay";
48837
49012
  return configured ? { configured } : { configured, warning: apnsSetupSteps() };
48838
49013
  }
48839
49014
  var SPEECH_KEY_USAGE = "Usage: phren bridge speech-key set (paste the key when asked, or pipe it on stdin)";
@@ -48879,7 +49054,7 @@ async function readSecret(prompt) {
48879
49054
  // src/bridge/hook-main.ts
48880
49055
  init_utils_helpers();
48881
49056
  Object.assign(process.env, nonInteractiveGitEnv());
48882
- runBridge(process.argv.slice(2), "0.3.1").then((code) => {
49057
+ runBridge(process.argv.slice(2), "0.3.3").then((code) => {
48883
49058
  process.exitCode = code;
48884
49059
  }).catch((error62) => {
48885
49060
  console.error(error62 instanceof Error ? error62.message : "Phren Hook failed.");
@@ -6,16 +6,67 @@ import { getPhrenPath } from "../shared.js";
6
6
  import { isValidProjectName, errorMessage, getOptionValue } from "../utils.js";
7
7
  import { resolveAllStores, addStoreToRegistry, removeStoreFromRegistry, generateStoreId, getStoreProjectDirs, readTeamBootstrap, } from "../store-registry.js";
8
8
  import { mergeStoreUpstream } from "../sync/store-merge.js";
9
+ import { aheadBehind, logSyncOutcome } from "../sync/outcome.js";
10
+ import { getRuntimeHealth, updateRuntimeHealth } from "../shared/governance.js";
9
11
  function printStoreUsage() {
10
12
  console.log("Usage:");
11
13
  console.log(" phren store list List registered stores");
12
14
  console.log(" phren store add <name> --remote <url> Add a team store");
13
15
  console.log(" phren store remove <name> Remove a store (local only)");
14
- console.log(" phren store sync Pull all stores");
16
+ console.log(" phren store sync Pull and push all stores");
15
17
  console.log(" phren store activity [--limit N] Recent team findings");
16
18
  console.log(" phren store subscribe <name> <project...> Subscribe store to projects");
17
19
  console.log(" phren store unsubscribe <name> <project...> Unsubscribe store from projects");
18
20
  }
21
+ /**
22
+ * Push what a sync left ahead of the upstream: the merge commit and any local
23
+ * commits. Without this a merge that resolved conflicts stayed local, and the
24
+ * store sat N commits ahead until someone ran `git push` by hand.
25
+ */
26
+ async function pushStoreUpstream(store, git) {
27
+ if (store.sync === "pull-only" || store.role === "readonly")
28
+ return { status: "skipped", detail: "pull-only store" };
29
+ const counts = await aheadBehind(store.path, git);
30
+ if (!counts)
31
+ return { status: "skipped", detail: "no tracking remote" };
32
+ if (counts.ahead === 0)
33
+ return { status: "in-sync", detail: "nothing to push" };
34
+ const branch = await git(store.path, ["symbolic-ref", "--quiet", "HEAD"]);
35
+ const refs = branch.ok
36
+ ? await git(store.path, ["for-each-ref", "--format=%(upstream:remotename)%09%(upstream:remoteref)", branch.output])
37
+ : branch;
38
+ const [remote, remoteRef] = refs.ok ? refs.output.split("\t") : [];
39
+ if (!remote || !remoteRef)
40
+ return { status: "failed", detail: "cannot read the upstream branch" };
41
+ const pushed = await git(store.path, ["push", "--quiet", "--", remote, `HEAD:${remoteRef}`]);
42
+ if (!pushed.ok)
43
+ return { status: "failed", detail: `push failed: ${(pushed.error || "unknown Git error").split("\n")[0]}` };
44
+ return { status: "pushed", detail: `pushed ${counts.ahead} commit${counts.ahead === 1 ? "" : "s"}` };
45
+ }
46
+ /** Record a sync's push on the primary store, so doctor's runtime-auto-save check reflects it. */
47
+ async function recordPrimaryPush(phrenPath, push, git) {
48
+ if (push.status === "skipped")
49
+ return;
50
+ const now = new Date().toISOString();
51
+ const previous = getRuntimeHealth(phrenPath).lastSync;
52
+ const counts = await aheadBehind(phrenPath, git);
53
+ const detail = `store sync: ${push.detail}`;
54
+ const failed = push.status === "failed";
55
+ updateRuntimeHealth(phrenPath, {
56
+ lastAutoSave: { at: now, status: failed ? "sync-failed" : "saved-pushed", detail },
57
+ lastSync: {
58
+ ...previous,
59
+ lastPushAt: now,
60
+ lastPushStatus: failed ? "push-failed" : "saved-pushed",
61
+ lastPushDetail: detail,
62
+ unsyncedCommits: counts?.ahead ?? previous?.unsyncedCommits,
63
+ consecutiveFailures: failed ? (previous?.consecutiveFailures ?? 0) + 1 : 0,
64
+ ...(failed ? {} : { lastSuccessfulPushAt: now }),
65
+ ...(counts ?? {}),
66
+ },
67
+ });
68
+ logSyncOutcome(phrenPath, "store-sync", { ok: !failed, detail: push.detail, counts });
69
+ }
19
70
  function countStoreProjects(store) {
20
71
  if (!fs.existsSync(store.path))
21
72
  return 0;
@@ -214,6 +265,7 @@ export async function handleStoreNamespace(args) {
214
265
  if (subcommand === "sync") {
215
266
  const stores = resolveAllStores(phrenPath);
216
267
  let hasErrors = false;
268
+ let primarySynced = false;
217
269
  const git = async (cwd, gitArgs) => {
218
270
  try {
219
271
  const output = execFileSync("git", gitArgs, {
@@ -278,13 +330,42 @@ export async function handleStoreNamespace(args) {
278
330
  // sparse-checkout not configured — nothing to reapply
279
331
  }
280
332
  }
281
- console.log(` ${store.name}: ok (${result.detail})`);
333
+ const push = await pushStoreUpstream(store, git);
334
+ if (store.role === "primary")
335
+ await recordPrimaryPush(store.path, push, git);
336
+ if (push.status === "failed") {
337
+ console.log(` ${store.name}: PUSH FAILED (${result.detail} ${push.detail}; the store is still ahead of the remote)`);
338
+ hasErrors = true;
339
+ }
340
+ else {
341
+ console.log(` ${store.name}: ok (${result.detail}${push.status === "pushed" ? ` Then ${push.detail}.` : ""})`);
342
+ }
343
+ if (store.role === "primary")
344
+ primarySynced = true;
282
345
  }
283
346
  catch (err) {
284
347
  console.log(` ${store.name}: FAILED (${errorMessage(err).split("\n")[0]})`);
285
348
  hasErrors = true;
286
349
  }
287
350
  }
351
+ // A pull can bring new skills or a changed global AGENTS.md. Refresh the
352
+ // home and repo links the way SessionStart does, so doctor doesn't report
353
+ // drift until the next session or a `doctor --fix`.
354
+ if (primarySynced) {
355
+ try {
356
+ const [{ repairPreexistingInstall }, { refreshLinkedContext }, { resolveRuntimeProfile }] = await Promise.all([
357
+ import("../init/setup.js"),
358
+ import("../link/refresh.js"),
359
+ import("../runtime-profile.js"),
360
+ ]);
361
+ repairPreexistingInstall(phrenPath);
362
+ refreshLinkedContext(phrenPath, resolveRuntimeProfile(phrenPath));
363
+ }
364
+ catch (err) {
365
+ console.log(` relink: FAILED (${errorMessage(err).split("\n")[0]}). Run 'phren doctor --fix'.`);
366
+ hasErrors = true;
367
+ }
368
+ }
288
369
  if (hasErrors) {
289
370
  console.error("\nSome stores failed to sync. Run 'phren doctor' for details.");
290
371
  }
@@ -121,7 +121,7 @@ const STORE_SUBCOMMANDS = [
121
121
  { name: "list", usage: "phren store list", summary: "List registered stores" },
122
122
  { name: "add", usage: "phren store add <name> --remote <url>", summary: "Add a team store" },
123
123
  { name: "remove", usage: "phren store remove <name>", summary: "Remove a store (local only)" },
124
- { name: "sync", usage: "phren store sync", summary: "Pull all stores" },
124
+ { name: "sync", usage: "phren store sync", summary: "Pull and push all stores" },
125
125
  ];
126
126
  const TEAM_SUBCOMMANDS = [
127
127
  { name: "init", usage: "phren team init <name> [--remote <url>]", summary: "Create a new team store" },
@@ -362,7 +362,7 @@ export async function runWalkthrough(phrenPath, options) {
362
362
  printSection("Semantic Search (Optional)");
363
363
  log("Phren can use a local embedding model for semantic (fuzzy) search via Ollama.");
364
364
  log(" Best fit: paraphrase-heavy or weak-lexical queries.");
365
- log(" Skip it if you mostly search by filenames, symbols, commands, or exact phrases.");
365
+ log(" Skip it if you mostly search by filenames, function names, commands, or exact phrases.");
366
366
  log(" - Model: nomic-embed-text (274 MB, one-time download)");
367
367
  log(" - Ollama runs locally, no cloud, no cost");
368
368
  log(" - Falls back to FTS5 keyword search if disabled or unavailable");
package/dist/link/link.js CHANGED
@@ -525,8 +525,13 @@ export async function runLink(phrenPath, opts = {}) {
525
525
  logger.debug("link", `link writeSkillMd: ${errorMessage(err)}`);
526
526
  }
527
527
  log("");
528
- // Step 7: Context file
529
- if (opts.task === "debugging") {
528
+ // Step 7: Context file. ~/.phren-context.md and the root MEMORY.md in Claude
529
+ // Code's memory directory are home surfaces: only presets with selfHeal
530
+ // (managed, or an explicit override) create them, matching repair and doctor.
531
+ if (!caps.selfHeal) {
532
+ log(" ~/.phren-context.md and Claude memory skipped (preset without self-heal)");
533
+ }
534
+ else if (opts.task === "debugging") {
530
535
  writeContextDebugging(machine, profile, mcpStatusForContext, projects, phrenPath);
531
536
  }
532
537
  else if (opts.task === "planning") {
@@ -540,7 +545,8 @@ export async function runLink(phrenPath, opts = {}) {
540
545
  }
541
546
  // Step 8: Memory (read back native changes, then rebuild)
542
547
  readBackNativeMemory(phrenPath, projects);
543
- rebuildMemory(phrenPath, projects);
548
+ if (caps.selfHeal)
549
+ rebuildMemory(phrenPath, projects);
544
550
  log(`\nDone. Profile '${profile}' is active.`);
545
551
  if (opts.task)
546
552
  log(`Task mode: ${opts.task}`);
@@ -1,13 +1,12 @@
1
1
  /** Refresh existing managed context destinations after a store pull, without relinking the installation. */
2
2
  import * as fs from "fs";
3
3
  import * as path from "path";
4
- import { atomicWriteText, homePath } from "../phren-paths.js";
4
+ import { homePath } from "../phren-paths.js";
5
5
  import { getProjectDirs } from "../shared.js";
6
6
  import { readProjectConfig, getProjectSourcePath, getProjectOwnershipMode } from "../project-config.js";
7
7
  import { findProjectDir } from "../project-locator.js";
8
8
  import { resolveManagementCapabilities } from "../init/management-preset.js";
9
9
  import { syncScopeSkillsToDir } from "../skill/files.js";
10
- import { buildSkillManifest, renderSkillInstructionsSection } from "../skill/registry.js";
11
10
  export function refreshLinkedContext(phrenPath, profile) {
12
11
  const caps = resolveManagementCapabilities(phrenPath);
13
12
  if (caps.installSkillLinks) {
@@ -30,18 +29,20 @@ export function refreshLinkedContext(phrenPath, profile) {
30
29
  if (!target || !fs.existsSync(target))
31
30
  continue;
32
31
  const skillsDir = path.join(target, ".claude", "skills");
33
- const manifest = config.skills !== false && fs.existsSync(path.join(target, ".claude", "skill-manifest.json"))
34
- ? syncScopeSkillsToDir(phrenPath, project, skillsDir)
35
- : buildSkillManifest(phrenPath, profile, project);
32
+ if (config.skills !== false && fs.existsSync(path.join(target, ".claude", "skill-manifest.json"))) {
33
+ syncScopeSkillsToDir(phrenPath, project, skillsDir);
34
+ }
36
35
  const agentsPath = path.join(target, "AGENTS.md");
37
36
  const claudePath = path.join(source, "AGENTS.md");
38
- // The generated file is a snapshot, unlike the live AGENTS.md symlink.
39
- // Preserve native/user-owned instructions and installations without a Codex mirror.
37
+ // Older releases wrote AGENTS.md as a generated snapshot with a skills table;
38
+ // link and doctor --fix replace that with a symlink to the store's AGENTS.md.
39
+ // Do the same here instead of regenerating the snapshot, or a pull and a
40
+ // doctor run keep flipping the file between the two shapes.
40
41
  if (!fs.existsSync(agentsPath) || !fs.existsSync(claudePath) || fs.lstatSync(agentsPath).isSymbolicLink())
41
42
  continue;
42
- const marker = "<!-- phren:generated-agents -->";
43
- if (!fs.readFileSync(agentsPath, "utf8").includes(marker))
43
+ if (!fs.readFileSync(agentsPath, "utf8").includes("<!-- phren:generated-agents -->"))
44
44
  continue;
45
- atomicWriteText(agentsPath, `${fs.readFileSync(claudePath, "utf8").trimEnd()}\n\n${marker}\n${renderSkillInstructionsSection(manifest)}\n`);
45
+ fs.unlinkSync(agentsPath);
46
+ fs.symlinkSync(claudePath, agentsPath);
46
47
  }
47
48
  }
@@ -96,7 +96,7 @@ export const BUILTIN_MODULES = [
96
96
  capabilities: [
97
97
  "hook", "transcript", "progress", "images", "prompt", "stop", "terminal", "shell", "herdr",
98
98
  "webServers", "webPreview", "activity", "approvals", "questions", "accountUsage", "providers",
99
- "files", "repositoryFiles", "subagents", "sideQuestions", "approvalPush", "simulators", "overviewStream", "speech", "transcribe",
99
+ "files", "repositoryFiles", "subagents", "sideQuestions", "approvalPush", "simulators", "overviewStream", "speech", "speechTimestamps", "transcribe",
100
100
  ],
101
101
  storeFiles: [".runtime/sessions/opencode-*.events.jsonl", ".runtime/approvals/opencode-*.json"],
102
102
  localFiles: ["<bridge>/installed.json", "<bridge>/versions/**", "<bridge>/current", "<bridge>/dispatch", "<bridge>/computer-id", "<bridge>/canary.json", "<bridge>/canary-daily"],
@@ -2,7 +2,7 @@ export interface ConflictResolution {
2
2
  resolved: string[];
3
3
  unresolved: string[];
4
4
  }
5
- type Strategy = "tasks" | "findings" | "archive" | "topic" | "summary" | null;
5
+ type Strategy = "tasks" | "findings" | "archive" | "topic" | "summary" | "union" | null;
6
6
  export declare function conflictStrategy(relFile: string): Strategy;
7
7
  /** Resolves what it can in the store's in-progress merge and stages it. */
8
8
  export declare function resolveStoreConflicts(cwd: string): ConflictResolution;