eversince 0.2.2 → 0.2.4

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.
@@ -7,8 +7,13 @@ const CLIENT_URI = 'https://eversince.ai';
7
7
  function base64url(input) {
8
8
  return input.toString('base64').replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
9
9
  }
10
+ const AUTH_REQUEST_TIMEOUT_MS = 10_000;
11
+ export const RENEWAL_DEADLINE_MS = 15_000;
12
+ export class RenewalRefused extends Error {
13
+ }
10
14
  async function getJson(url, init) {
11
15
  const res = await fetch(url, {
16
+ signal: AbortSignal.timeout(AUTH_REQUEST_TIMEOUT_MS),
12
17
  ...init,
13
18
  headers: { accept: 'application/json', 'user-agent': USER_AGENT, ...(init?.headers ?? {}) },
14
19
  });
@@ -23,8 +28,9 @@ async function getJson(url, init) {
23
28
  throw new Error(`${url} did not return JSON`);
24
29
  }
25
30
  }
26
- export async function discoverAuthorizationServer(baseUrl) {
27
- const metadata = (await getJson(new URL('/.well-known/oauth-protected-resource', baseUrl).toString()));
31
+ export async function discoverAuthorizationServer(baseUrl, signal) {
32
+ const init = signal ? { signal } : undefined;
33
+ const metadata = (await getJson(new URL('/.well-known/oauth-protected-resource', baseUrl).toString(), init));
28
34
  const issuer = metadata.authorization_servers?.[0];
29
35
  if (!issuer)
30
36
  throw new Error(`${baseUrl} does not advertise an authorization server.`);
@@ -32,10 +38,10 @@ export async function discoverAuthorizationServer(baseUrl) {
32
38
  const wellKnown = new URL(`/.well-known/oauth-authorization-server${issuerUrl.pathname.replace(/\/$/, '')}`, issuerUrl.origin).toString();
33
39
  let server;
34
40
  try {
35
- server = (await getJson(wellKnown));
41
+ server = (await getJson(wellKnown, init));
36
42
  }
37
43
  catch {
38
- server = (await getJson(new URL('.well-known/oauth-authorization-server', `${issuer}/`).toString()));
44
+ server = (await getJson(new URL('.well-known/oauth-authorization-server', `${issuer}/`).toString(), init));
39
45
  }
40
46
  if (!server.authorization_endpoint || !server.token_endpoint) {
41
47
  throw new Error('Authorization server metadata is missing its endpoints.');
@@ -77,10 +83,11 @@ function openBrowser(url) {
77
83
  catch {
78
84
  }
79
85
  }
80
- const DONE_PAGE = `<!doctype html><meta charset="utf-8"><title>Signed in</title>
81
- <style>body{font:16px/1.6 -apple-system,system-ui,sans-serif;display:grid;place-items:center;height:100vh;margin:0;color:#111}
82
- @media(prefers-color-scheme:dark){body{background:#111;color:#eee}}</style>
83
- <body><div><p><strong>Signed in to Eversince.</strong></p><p>You can close this tab and go back to the terminal.</p></div>`;
86
+ const DONE_PAGE = `<!doctype html><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Eversince is connected</title>
87
+ <style>body{font-family:Inter,-apple-system,system-ui,sans-serif;display:grid;place-items:center;height:100vh;margin:0;padding:0 16px;background:#fff;color:#18181b;text-align:center;-webkit-font-smoothing:antialiased}
88
+ h1{font-size:14px;font-weight:500;margin:0}p{font-size:14px;color:#71717a;margin:6px 0 0}
89
+ @media(prefers-color-scheme:dark){body{background:#161616;color:#f4f4f5}p{color:#a1a1aa}}</style>
90
+ <body><div><h1>You're all set</h1><p>You can close this tab and go back to your agent</p></div>`;
84
91
  const PREFERRED_PORTS = [51703, 51704, 51705, 0];
85
92
  async function awaitCallback(timeoutMs) {
86
93
  let settle = null;
@@ -180,8 +187,9 @@ export async function browserLogin(baseUrl, opts) {
180
187
  callback.close();
181
188
  }
182
189
  }
183
- async function exchange(server, params) {
190
+ async function exchange(server, params, signal) {
184
191
  const res = await fetch(server.token_endpoint, {
192
+ signal: signal ?? AbortSignal.timeout(AUTH_REQUEST_TIMEOUT_MS),
185
193
  method: 'POST',
186
194
  headers: { 'content-type': 'application/x-www-form-urlencoded', accept: 'application/json', 'user-agent': USER_AGENT },
187
195
  body: new URLSearchParams(params).toString(),
@@ -195,7 +203,8 @@ async function exchange(server, params) {
195
203
  throw new Error(`Token endpoint returned non-JSON (${res.status}).`);
196
204
  }
197
205
  if (!res.ok || !payload.access_token) {
198
- throw new Error(payload.error_description || payload.error || `Token exchange failed (${res.status}).`);
206
+ const reason = payload.error_description || payload.msg || payload.error_code || payload.error || `Token exchange failed (${res.status}).`;
207
+ throw res.status === 400 || res.status === 401 ? new RenewalRefused(reason) : new Error(reason);
199
208
  }
200
209
  return {
201
210
  accessToken: payload.access_token,
@@ -204,11 +213,12 @@ async function exchange(server, params) {
204
213
  };
205
214
  }
206
215
  export async function refreshTokens(baseUrl, clientId, refreshToken) {
207
- const { server, resource } = await discoverAuthorizationServer(baseUrl);
216
+ const signal = AbortSignal.timeout(RENEWAL_DEADLINE_MS);
217
+ const { server, resource } = await discoverAuthorizationServer(baseUrl, signal);
208
218
  return exchange(server, {
209
219
  grant_type: 'refresh_token',
210
220
  refresh_token: refreshToken,
211
221
  client_id: clientId,
212
222
  resource,
213
- });
223
+ }, signal);
214
224
  }
@@ -1,22 +1,24 @@
1
1
  import { homedir } from 'node:os';
2
2
  import { join } from 'node:path';
3
- import { mkdir, readFile, writeFile, rm, chmod } from 'node:fs/promises';
3
+ import { mkdir, readFile, writeFile, rm, chmod, open, stat, unlink, rename } from 'node:fs/promises';
4
+ import { randomUUID } from 'node:crypto';
4
5
  import { execFile } from 'node:child_process';
5
6
  import { promisify } from 'node:util';
6
7
  const run = promisify(execFile);
7
8
  const SERVICE = 'eversince-cli';
8
9
  export function stateDir() {
9
- return join(homedir(), '.eversince');
10
+ return process.env.ES_STATE_DIR || join(homedir(), '.eversince');
10
11
  }
11
12
  function credentialsPath() {
12
13
  return join(stateDir(), 'credentials.json');
13
14
  }
14
- const keychainUsable = process.platform === 'darwin';
15
+ const keychainUsable = process.platform === 'darwin' && !process.env.ES_STATE_DIR;
16
+ const KEYCHAIN_TIMEOUT_MS = 3_000;
15
17
  async function keychainGet(host) {
16
18
  if (!keychainUsable)
17
19
  return null;
18
20
  try {
19
- const { stdout } = await run('security', ['find-generic-password', '-s', SERVICE, '-a', host, '-w']);
21
+ const { stdout } = await run('security', ['find-generic-password', '-s', SERVICE, '-a', host, '-w'], { timeout: KEYCHAIN_TIMEOUT_MS });
20
22
  return JSON.parse(stdout.trim());
21
23
  }
22
24
  catch {
@@ -31,7 +33,7 @@ async function keychainSet(host, creds) {
31
33
  'add-generic-password', '-U',
32
34
  '-s', SERVICE, '-a', host,
33
35
  '-w', JSON.stringify(creds),
34
- ]);
36
+ ], { timeout: KEYCHAIN_TIMEOUT_MS });
35
37
  }
36
38
  catch {
37
39
  return false;
@@ -63,6 +65,52 @@ async function fileWrite(next) {
63
65
  await writeFile(credentialsPath(), `${JSON.stringify(next, null, 2)}\n`, { mode: 0o600 });
64
66
  await chmod(credentialsPath(), 0o600);
65
67
  }
68
+ const LOCK_STALE_MS = 40_000;
69
+ const LOCK_WAIT_MS = 45_000;
70
+ const LOCK_BUSY = new Set(['EEXIST', 'EPERM', 'EBUSY', 'EACCES']);
71
+ export class RenewalBusy extends Error {
72
+ }
73
+ export async function withRenewalLock(host, run) {
74
+ await mkdir(stateDir(), { recursive: true, mode: 0o700 });
75
+ const path = join(stateDir(), `renew-${host.replace(/[^a-z0-9.-]/gi, '_')}.lock`);
76
+ const owner = randomUUID();
77
+ const deadline = Date.now() + LOCK_WAIT_MS;
78
+ for (;;) {
79
+ try {
80
+ const handle = await open(path, 'wx', 0o600);
81
+ await handle.writeFile(owner);
82
+ await handle.close();
83
+ break;
84
+ }
85
+ catch (error) {
86
+ if (!LOCK_BUSY.has(error.code ?? ''))
87
+ throw error;
88
+ const held = await stat(path).then((s) => ({ age: Date.now() - s.mtimeMs }), () => null);
89
+ if (held && held.age > LOCK_STALE_MS) {
90
+ const before = await readFile(path, 'utf8').catch(() => null);
91
+ const aside = `${path}.${owner}`;
92
+ if (before !== null && await rename(path, aside).then(() => true, () => false)) {
93
+ const moved = await readFile(aside, 'utf8').catch(() => null);
94
+ if (moved === before)
95
+ await unlink(aside).catch(() => { });
96
+ else
97
+ await rename(aside, path).catch(() => unlink(aside).catch(() => { }));
98
+ }
99
+ }
100
+ if (Date.now() > deadline)
101
+ throw new RenewalBusy('Another Eversince process is renewing the session.');
102
+ await new Promise((resolve) => setTimeout(resolve, 150));
103
+ }
104
+ }
105
+ try {
106
+ return await run();
107
+ }
108
+ finally {
109
+ const mine = await readFile(path, 'utf8').then((text) => text === owner, () => false);
110
+ if (mine)
111
+ await unlink(path).catch(() => { });
112
+ }
113
+ }
66
114
  export async function readCredentials(host) {
67
115
  const fromKeychain = await keychainGet(host);
68
116
  if (fromKeychain)
package/dist/client.js CHANGED
@@ -2,8 +2,8 @@ import { randomUUID } from 'node:crypto';
2
2
  import { DEFAULT_BASE_URL, normalizeBaseUrl, readSettings, resolveBaseUrl, resolveWorkspace } from './config.js';
3
3
  import { localDoor } from './local.js';
4
4
  import { note } from './output.js';
5
- import { readCredentials, writeCredentials } from './auth/store.js';
6
- import { refreshTokens } from './auth/oauth.js';
5
+ import { readCredentials, withRenewalLock, writeCredentials } from './auth/store.js';
6
+ import { RenewalRefused, refreshTokens } from './auth/oauth.js';
7
7
  import { hostOf } from './config.js';
8
8
  import { isConnectFailure } from './retry.js';
9
9
  import { USER_AGENT } from './version.js';
@@ -29,6 +29,8 @@ const RETRYABLE_STATUS = new Set([429, 502, 503, 504]);
29
29
  const MAX_ATTEMPTS = 4;
30
30
  const MAX_WRITE_ATTEMPTS = 2;
31
31
  const WRITE_RETRY_PAUSE_MS = 500;
32
+ class RenewalUnreachable extends Error {
33
+ }
32
34
  function sleep(ms) {
33
35
  return new Promise((r) => setTimeout(r, ms));
34
36
  }
@@ -39,6 +41,7 @@ export class Client {
39
41
  baseUrl;
40
42
  workspace;
41
43
  credentials;
44
+ fromStore;
42
45
  debug;
43
46
  defaultTimeoutMs;
44
47
  local;
@@ -49,6 +52,7 @@ export class Client {
49
52
  this.debug = opts.debug === true || process.env.ES_DEBUG === '1';
50
53
  this.defaultTimeoutMs = (opts.timeout ?? 600) * 1000;
51
54
  this.local = local;
55
+ this.fromStore = !opts.credentials && !local;
52
56
  }
53
57
  static async create(opts = {}) {
54
58
  if (await mayUseDesktop(opts)) {
@@ -111,14 +115,46 @@ export class Client {
111
115
  message: 'Session expired and cannot be renewed. Run `eversince login`.',
112
116
  });
113
117
  }
114
- const next = await refreshTokens(this.baseUrl, clientId, refreshToken);
115
- this.credentials = {
116
- ...this.credentials,
117
- token: next.accessToken,
118
- refreshToken: next.refreshToken ?? refreshToken,
119
- expiresAt: next.expiresAt,
120
- };
121
- await writeCredentials(this.credentials);
118
+ const host = this.credentials.host;
119
+ const expired = this.credentials.expiresAt;
120
+ try {
121
+ await withRenewalLock(host, async () => {
122
+ if (this.credentials.expiresAt !== expired)
123
+ return;
124
+ const stored = await readCredentials(host);
125
+ if (!stored && this.fromStore) {
126
+ throw new ApiError(401, { code: 'unauthorized', message: `Signed out of ${host}. Run \`eversince login\`.` });
127
+ }
128
+ if (stored && stored.kind !== 'oauth') {
129
+ this.credentials = stored;
130
+ return;
131
+ }
132
+ if (stored && stored.token !== this.credentials.token && stored.expiresAt && Date.now() < stored.expiresAt) {
133
+ this.credentials = stored;
134
+ return;
135
+ }
136
+ const base = stored ?? this.credentials;
137
+ if (!base.refreshToken || !base.clientId) {
138
+ throw new ApiError(401, { code: 'unauthorized', message: 'Session expired and cannot be renewed. Run `eversince login`.' });
139
+ }
140
+ const next = await refreshTokens(this.baseUrl, base.clientId, base.refreshToken);
141
+ this.credentials = {
142
+ ...base,
143
+ token: next.accessToken,
144
+ refreshToken: next.refreshToken ?? base.refreshToken,
145
+ expiresAt: next.expiresAt,
146
+ };
147
+ await writeCredentials(this.credentials);
148
+ });
149
+ }
150
+ catch (error) {
151
+ if (error instanceof RenewalRefused) {
152
+ throw new ApiError(401, { code: 'unauthorized', message: `The session could not be renewed (${error.message}). Run \`eversince login\`.` });
153
+ }
154
+ if (error instanceof ApiError)
155
+ throw error;
156
+ throw new RenewalUnreachable(error instanceof Error ? error.message : String(error));
157
+ }
122
158
  }
123
159
  async request(method, path, options) {
124
160
  const url = new URL(path, this.baseUrl);
@@ -206,7 +242,7 @@ export class Client {
206
242
  continue;
207
243
  }
208
244
  const aborted = error instanceof Error && error.name === 'AbortError';
209
- const connectFailure = !aborted && isConnectFailure(error);
245
+ const connectFailure = !aborted && (isConnectFailure(error) || error instanceof RenewalUnreachable);
210
246
  const wrapped = new ApiError(0, {
211
247
  code: aborted ? 'timeout' : 'network_error',
212
248
  message: aborted
@@ -1,6 +1,6 @@
1
1
  import { createInterface } from 'node:readline/promises';
2
2
  import { browserLogin } from '../auth/oauth.js';
3
- import { readCredentials, writeCredentials, deleteCredentials, storageKind } from '../auth/store.js';
3
+ import { readCredentials, writeCredentials, deleteCredentials, storageKind, withRenewalLock } from '../auth/store.js';
4
4
  import { resolveBaseUrl, resolveWorkspace, writeSettings, hostOf } from '../config.js';
5
5
  import { Client, ApiError, loadCredentials } from '../client.js';
6
6
  import { line, note, printResult } from '../output.js';
@@ -78,7 +78,7 @@ export async function login(argv, connection, mode) {
78
78
  }
79
79
  throw error;
80
80
  }
81
- const where = await writeCredentials(stored);
81
+ const where = await withRenewalLock(host, () => writeCredentials(stored));
82
82
  if (connection.baseUrl)
83
83
  await writeSettings({ baseUrl });
84
84
  printResult(mode, { host, kind: stored.kind, storage: where }, () => {
@@ -92,8 +92,11 @@ export async function login(argv, connection, mode) {
92
92
  export async function logout(connection, mode) {
93
93
  const baseUrl = await resolveBaseUrl(connection.baseUrl);
94
94
  const host = hostOf(baseUrl);
95
- const had = await readCredentials(host);
96
- await deleteCredentials(host);
95
+ const had = await withRenewalLock(host, async () => {
96
+ const found = await readCredentials(host);
97
+ await deleteCredentials(host);
98
+ return found;
99
+ });
97
100
  printResult(mode, { host, removed: had !== null }, () => {
98
101
  line(had ? `Signed out of ${host}.` : `Nothing stored for ${host}.`);
99
102
  if (process.env.ES_API_KEY) {
@@ -1,5 +1,5 @@
1
1
  import { existsSync } from 'node:fs';
2
- import { readFile, writeFile, mkdir, copyFile, access, rename } from 'node:fs/promises';
2
+ import { readFile, writeFile, mkdir, copyFile, access, rename, stat } from 'node:fs/promises';
3
3
  import { join, dirname } from 'node:path';
4
4
  import { homedir } from 'node:os';
5
5
  import { discoverAuthorizationServer } from '../auth/oauth.js';
@@ -56,8 +56,9 @@ function manualFor(agent, mcpUrl) {
56
56
  }
57
57
  async function writeAtomic(path, text) {
58
58
  await mkdir(dirname(path), { recursive: true });
59
+ const mode = await stat(path).then((s) => s.mode & 0o777, () => 0o600);
59
60
  const temp = `${path}.eversince-${process.pid}.tmp`;
60
- await writeFile(temp, text);
61
+ await writeFile(temp, text, { mode });
61
62
  await rename(temp, path);
62
63
  }
63
64
  function skillTargets(scope) {
@@ -125,7 +126,18 @@ async function backup(path) {
125
126
  await copyFile(path, target);
126
127
  return target;
127
128
  }
128
- async function writeMcpEntry(target, mcpUrl, dryRun) {
129
+ function pointsHere(url, mcpUrl, baseUrl) {
130
+ const bare = (u) => u.replace(/\/+$/, '');
131
+ if (bare(url) === bare(mcpUrl))
132
+ return true;
133
+ try {
134
+ return new URL(url).origin === new URL(baseUrl).origin;
135
+ }
136
+ catch {
137
+ return false;
138
+ }
139
+ }
140
+ async function writeMcpEntry(target, mcpUrl, baseUrl, dryRun) {
129
141
  const entry = { type: 'http', url: mcpUrl };
130
142
  let current = {};
131
143
  const had = await exists(target.path);
@@ -146,16 +158,18 @@ async function writeMcpEntry(target, mcpUrl, dryRun) {
146
158
  const merged = existing && typeof existing === 'object'
147
159
  ? { ...entry, ...existing }
148
160
  : entry;
161
+ const keptUrl = merged.url;
162
+ const elsewhere = typeof keptUrl === 'string' && !pointsHere(keptUrl, mcpUrl, baseUrl) ? { points_to: keptUrl } : {};
149
163
  if (existing && JSON.stringify(existing) === JSON.stringify(merged)) {
150
- return { agent: target.agent, path: target.path, action: 'unchanged' };
164
+ return { agent: target.agent, path: target.path, action: 'unchanged', ...elsewhere };
151
165
  }
152
166
  if (dryRun) {
153
- return { agent: target.agent, path: target.path, action: had ? 'updated' : 'created' };
167
+ return { agent: target.agent, path: target.path, action: had ? 'updated' : 'created', ...elsewhere };
154
168
  }
155
169
  const saved = had ? await backup(target.path) : undefined;
156
170
  servers[SERVER_KEY] = merged;
157
171
  await writeAtomic(target.path, `${JSON.stringify({ ...current, [target.key]: servers }, null, 2)}\n`);
158
- return { agent: target.agent, path: target.path, action: had ? 'updated' : 'created', backup: saved };
172
+ return { agent: target.agent, path: target.path, action: had ? 'updated' : 'created', backup: saved, ...elsewhere };
159
173
  }
160
174
  async function writeSkill(target, body, force, dryRun) {
161
175
  if (await exists(target.path)) {
@@ -277,10 +291,12 @@ export async function init(argv, connection, mode) {
277
291
  const offerApp = !app;
278
292
  const changes = [];
279
293
  const skipped = [];
294
+ const entries = [];
280
295
  if (doMcp) {
281
296
  for (const target of jsonTargets(scope, agent)) {
282
- changes.push(await writeMcpEntry(target, mcpUrl, dryRun));
297
+ entries.push(await writeMcpEntry(target, mcpUrl, baseUrl, dryRun));
283
298
  }
299
+ changes.push(...entries);
284
300
  skipped.push(...manualFor(agent, mcpUrl));
285
301
  }
286
302
  if (doSkills) {
@@ -289,7 +305,8 @@ export async function init(argv, connection, mode) {
289
305
  changes.push(await writeSkill(target, body, argv.force === true, dryRun));
290
306
  }
291
307
  }
292
- if (!dryRun) {
308
+ const connected = !(entries.length > 0 && entries.every((entry) => entry.points_to));
309
+ if (!dryRun && connected) {
293
310
  const wrote = changes.filter((c) => c.action !== 'unchanged').map((c) => c.agent);
294
311
  const named = agent
295
312
  ? agent === 'claude-code' || agent === 'cursor' || agent === 'codex'
@@ -315,11 +332,13 @@ export async function init(argv, connection, mode) {
315
332
  }
316
333
  }
317
334
  }
318
- printResult(mode, { venue: 'cloud', scope, mcp_url: mcpUrl, dry_run: dryRun, changes, manual: skipped, ...(offerApp ? { desktop_app: GET_THE_APP } : {}) }, () => {
335
+ printResult(mode, { venue: 'cloud', scope, mcp_url: mcpUrl, dry_run: dryRun, connected, changes, manual: skipped, ...(offerApp ? { desktop_app: GET_THE_APP } : {}) }, () => {
319
336
  for (const change of changes) {
320
337
  line(`${change.action.padEnd(10)}${change.path}`);
321
338
  if (change.backup)
322
339
  note(` previous copy: ${change.backup}`);
340
+ if (change.points_to)
341
+ note(` its ${SERVER_KEY} entry points to ${change.points_to}, not ${mcpUrl}. Remove the entry and run init again to connect here.`);
323
342
  }
324
343
  for (const item of skipped) {
325
344
  line();
@@ -330,6 +349,10 @@ export async function init(argv, connection, mode) {
330
349
  line('Dry run. Nothing was written.');
331
350
  return;
332
351
  }
352
+ if (!connected) {
353
+ line(`Not connected to ${hostOf(baseUrl)}: the entry already there points elsewhere.`);
354
+ return;
355
+ }
333
356
  line(`Connected to ${hostOf(baseUrl)}. Restart any running agent to pick it up.`);
334
357
  note('The agent authorises its own MCP connection; it does not use the CLI credential.');
335
358
  if (offerApp)
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "eversince",
3
- "version": "0.2.2",
4
- "description": "Agent-native access to making content",
3
+ "version": "0.2.4",
4
+ "description": "The Eversince CLI. Eversince is the media workspace for agents: connect an agent, call any tool, move files and follow jobs from a shell.",
5
5
  "type": "module",
6
6
  "bin": {
7
7
  "eversince": "dist/index.js"