ftown-bridge 0.30.49 → 0.30.51

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.
@@ -0,0 +1,97 @@
1
+ import { randomUUID } from 'node:crypto';
2
+ import { constants, appendFileSync, closeSync, fstatSync, futimesSync, renameSync, rmSync, utimesSync, mkdirSync, openSync, readSync, readFileSync, writeFileSync } from 'node:fs';
3
+ import { homedir } from 'node:os';
4
+ import { dirname, join } from 'node:path';
5
+ import { codexHome, claudeConfigDir } from './config-dirs.js';
6
+ export const instructionLimit = 64 * 1024;
7
+ export const instructionPath = (scope, home = homedir()) => join(home, '.ftown', scope + '.md');
8
+ export function readRevision(scope, home = homedir()) {
9
+ const fd = openSync(instructionPath(scope, home), constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
10
+ try {
11
+ const stat = fstatSync(fd);
12
+ if (!stat.isFile() || stat.size > instructionLimit)
13
+ throw new Error('Expected an instruction file of at most 64 KiB');
14
+ const buffer = Buffer.alloc(stat.size + 1);
15
+ let size = 0;
16
+ while (size < buffer.length) {
17
+ const count = readSync(fd, buffer, size, buffer.length - size, null);
18
+ if (!count)
19
+ break;
20
+ size += count;
21
+ }
22
+ if (size !== stat.size)
23
+ throw new Error('Instruction file changed while reading');
24
+ const text = new TextDecoder('utf-8', { fatal: true, ignoreBOM: true }).decode(buffer.subarray(0, size));
25
+ return { text, version: Math.round(stat.mtimeMs) };
26
+ }
27
+ finally {
28
+ closeSync(fd);
29
+ }
30
+ }
31
+ export function readInstructions(scope, home = homedir()) {
32
+ return readRevision(scope, home).text;
33
+ }
34
+ // Equal timestamps use a stable content order so every bridge picks the same winner.
35
+ export function mergeGlobal(value, home = homedir()) {
36
+ const remote = value;
37
+ if (!remote || typeof remote.text !== 'string' || Buffer.byteLength(remote.text) > instructionLimit
38
+ || typeof remote.version !== 'number' || !Number.isSafeInteger(remote.version) || remote.version < 0
39
+ || !Number.isFinite(new Date(remote.version).getTime()))
40
+ throw new Error('Invalid instruction revision');
41
+ const file = instructionPath('global', home);
42
+ const local = readRevision('global', home);
43
+ if (remote.version < local.version || (remote.version === local.version && remote.text <= local.text))
44
+ return local;
45
+ const temp = file + '.' + randomUUID();
46
+ try {
47
+ writeFileSync(temp, remote.text, { flag: 'wx', mode: 0o600 });
48
+ const timestamp = new Date(remote.version);
49
+ utimesSync(temp, timestamp, timestamp);
50
+ renameSync(temp, file);
51
+ return { text: remote.text, version: remote.version };
52
+ }
53
+ finally {
54
+ rmSync(temp, { force: true });
55
+ }
56
+ }
57
+ export function installInstructions(home = homedir(), env = process.env, harness) {
58
+ const refs = [];
59
+ for (const scope of ['global', 'bridge']) {
60
+ const file = instructionPath(scope, home);
61
+ mkdirSync(dirname(file), { recursive: true });
62
+ try {
63
+ const fd = openSync(file, 'wx', 0o600);
64
+ try {
65
+ futimesSync(fd, new Date(0), new Date(0));
66
+ }
67
+ finally {
68
+ closeSync(fd);
69
+ }
70
+ }
71
+ catch (error) {
72
+ if (error.code !== 'EEXIST')
73
+ throw error;
74
+ }
75
+ refs.push('Read the ' + scope + ' ftown instructions in `' + file + '`.');
76
+ }
77
+ const files = [];
78
+ if (harness !== 'claude')
79
+ files.push(join(codexHome(home, env), 'AGENTS.md'));
80
+ if (harness !== 'codex')
81
+ files.push(join(claudeConfigDir(home, env), 'CLAUDE.md'));
82
+ for (const file of files) {
83
+ mkdirSync(dirname(file), { recursive: true });
84
+ let prior = '';
85
+ try {
86
+ prior = readFileSync(file, 'utf8');
87
+ }
88
+ catch (error) {
89
+ if (error.code !== 'ENOENT')
90
+ throw error;
91
+ }
92
+ const missing = refs.filter(ref => !prior.split(/\r?\n/).includes(ref));
93
+ if (missing.length)
94
+ appendFileSync(file, (prior ? '\n\n' : '') + missing.join('\n') + '\n', { mode: 0o600 });
95
+ }
96
+ }
97
+ //# sourceMappingURL=instructions.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"instructions.js","sourceRoot":"","sources":["../src/instructions.ts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C,CAAC;QAC9C,IAAI,KAAK,GAAG,EAAE,CAAC;QACf,IAAI,CAAC;YAAC,KAAK,GAAG,YAAY,CAAC,IAAI,EAAE,MAAM,CAAC,CAAC;QAAC,CAAC;QAC3C,OAAO,KAAK,EAAE,CAAC;YAAC,IAAK,KAA+B,CAAC,IAAI,KAAK,QAAQ;gBAAE,MAAM,KAAK,CAAC;QAAC,CAAC;QACtF,MAAM,OAAO,GAAG,IAAI,CAAC,MAAM,CAAC,GAAG,CAAC,EAAE,CAAC,CAAC,KAAK,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,QAAQ,CAAC,GAAG,CAAC,CAAC,CAAC;QACxE,IAAI,OAAO,CAAC,MAAM;YAAE,cAAc,CAAC,IAAI,EAAE,CAAC,KAAK,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,CAAC,GAAG,OAAO,CAAC,IAAI,CAAC,IAAI,CAAC,GAAG,IAAI,EAAE,EAAE,IAAI,EAAE,KAAK,EAAE,CAAC,CAAC;IAC/G,CAAC;AACH,CAAC"}
@@ -86,6 +86,10 @@ export declare class LocalApiServer extends EventEmitter<HookServerEvents> {
86
86
  private transfers;
87
87
  setPeerControl(peers: PeerControl, links?: PeerLinks, transferStateDir?: string, remembered?: () => Promise<unknown[]>, hostResources?: () => Promise<HostResources>): void;
88
88
  closeTransfers(): Promise<void>;
89
+ private instructionTimer?;
90
+ startInstructionSync(ownBridgeId: string): void;
91
+ private syncInstructions;
92
+ private dispatchInstructions;
89
93
  private dispatchTransfer;
90
94
  /** GET /api/peers and POST /api/peers/http, for the OS-local CLI only (a browser or a peer bridge never relays through this bridge). */
91
95
  private dispatchPeers;
@@ -1,3 +1,5 @@
1
+ import { INSTRUCTIONS_LOCAL, INSTRUCTIONS_SYNC, INSTRUCTIONS_WIRE } from './instructions-protocol.js';
2
+ import { mergeGlobal, readRevision } from './instructions.js';
1
3
  import { peerResources } from './host-resources.js';
2
4
  import { TransferJournal } from './folder-transfer-journal.js';
3
5
  import { FolderTransfers, transferError } from './folder-transfer.js';
@@ -166,6 +168,66 @@ export class LocalApiServer extends EventEmitter {
166
168
  links?.setBinaryHandler((endpoint, channel, frame) => this.transfers?.binary(endpoint, channel, frame));
167
169
  }
168
170
  async closeTransfers() { await this.transfers?.close(); }
171
+ instructionTimer;
172
+ startInstructionSync(ownBridgeId) {
173
+ if (this.instructionTimer)
174
+ return;
175
+ let running = false;
176
+ const tick = async () => {
177
+ if (running || !this.peerControl)
178
+ return;
179
+ running = true;
180
+ try {
181
+ const peers = await this.peerControl.list();
182
+ // One initiator per pair avoids simultaneous offers. Either side can supply the winning file.
183
+ await Promise.allSettled(peers.filter(peer => ownBridgeId < peer.bridgeId).map(peer => this.syncInstructions(peer.bridgeId)));
184
+ }
185
+ finally {
186
+ running = false;
187
+ }
188
+ };
189
+ this.instructionTimer = setInterval(() => { void tick().catch(() => undefined); }, 30_000);
190
+ this.instructionTimer.unref();
191
+ }
192
+ async syncInstructions(target) {
193
+ const peers = this.peerControl;
194
+ if (!peers || !await peers.connectDirect(target))
195
+ throw new Error('Direct bridge link unavailable');
196
+ const result = await peers.directHttp(target, INSTRUCTIONS_SYNC, readRevision('global'));
197
+ if (result.status !== 200)
198
+ return result;
199
+ return { status: 200, body: mergeGlobal(result.body) };
200
+ }
201
+ async dispatchInstructions(message, path) {
202
+ const wire = path !== INSTRUCTIONS_LOCAL;
203
+ const { endpoint } = message.principal;
204
+ if (wire ? endpoint.kind !== 'bridge' || !this.security.peerBridges().some(peer => peer.endpoint.id === endpoint.id)
205
+ : endpoint.kind !== 'local-cli')
206
+ return { status: 403, body: { error: 'permission_denied' } };
207
+ await this.security.revalidate(message.principal);
208
+ const body = message.application.data?.body;
209
+ try {
210
+ if (path === INSTRUCTIONS_SYNC)
211
+ return { status: 200, body: mergeGlobal(body) };
212
+ if (body?.scope !== 'global' && body?.scope !== 'bridge')
213
+ return { status: 400, body: { error: 'Invalid scope' } };
214
+ if (wire)
215
+ return { status: 200, body: readRevision(body.scope) };
216
+ if (typeof body.bridge !== 'string')
217
+ return { status: 400, body: { error: 'Missing peer' } };
218
+ if (body.action === 'sync') {
219
+ if (body.scope !== 'global')
220
+ throw new Error('Only global instructions are shared');
221
+ return await this.syncInstructions(body.bridge);
222
+ }
223
+ if (!await this.peerControl?.connectDirect(body.bridge))
224
+ return { status: 503, body: { error: 'Direct bridge link unavailable' } };
225
+ return await this.peerControl.directHttp(body.bridge, INSTRUCTIONS_WIRE, { scope: body.scope });
226
+ }
227
+ catch (error) {
228
+ return { status: 400, body: { error: error instanceof Error ? error.message : 'Instruction request failed' } };
229
+ }
230
+ }
169
231
  async dispatchTransfer(message, path) {
170
232
  const { endpoint } = message.principal;
171
233
  const wire = path === TRANSFER_WIRE;
@@ -301,6 +363,8 @@ export class LocalApiServer extends EventEmitter {
301
363
  if (route.kind !== 'http')
302
364
  throw new Error('Invalid application route');
303
365
  const routePath = route.path.split('?')[0];
366
+ if (routePath === INSTRUCTIONS_LOCAL || routePath === INSTRUCTIONS_WIRE || routePath === INSTRUCTIONS_SYNC)
367
+ return this.dispatchInstructions(message, routePath);
304
368
  if (routePath === '/api/host-resources' && route.method === 'GET') {
305
369
  await this.security.revalidate(message.principal);
306
370
  if (!this.hostResources)
@@ -949,6 +1013,8 @@ export class LocalApiServer extends EventEmitter {
949
1013
  return this.server;
950
1014
  }
951
1015
  stop() {
1016
+ clearInterval(this.instructionTimer);
1017
+ this.instructionTimer = undefined;
952
1018
  for (const wake of this.localEventWaiters)
953
1019
  wake();
954
1020
  this.recoveryStopped = true;