conare 0.30.0 → 0.34.0

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/cli/main.js CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- // The conare command: `conare sync` uploads Claude Code and Codex sessions, `conare sync
2
+ // The conare command: `conare sync` uploads Claude Code, Codex, Cursor and Pi sessions, `conare sync
3
3
  // github` issues, PRs and markdown docs, both through the SDK's own client. Node built-ins
4
4
  // only; runs under node (npx conare) and bun (bunx conare). The library entry never imports
5
5
  // this directory.
@@ -8,16 +8,22 @@ import { rmSync } from "node:fs";
8
8
  import { homedir } from "node:os";
9
9
  import { fileURLToPath } from "node:url";
10
10
  import { Conare, ConareError, VERSION } from "../index.js";
11
- import { HELP, parseArgs, repoNamespace } from "./args.js";
12
- import { readExcluded, readSavedKey, resolvePaths, saveKey } from "./config.js";
11
+ import { HELP, LEGACY_USAGE, parseArgs, repoNamespace } from "./args.js";
12
+ import { privateDir, readExcluded, readSavedKey, resolvePaths, saveKey } from "./config.js";
13
+ import { NAMESPACE } from "./documents.js";
13
14
  import { GitHub, GitHubError, githubToken } from "./github/api.js";
14
15
  import { loadGitHubState, saveGitHubState, syncRepo } from "./github/sync.js";
15
- import { PASSED_ENV, installCopy, installSchedule, installedSchedule, pruneVersions, stableRuntime, uninstallSchedule } from "./schedule.js";
16
+ import { retireLegacy } from "./legacy.js";
17
+ import { otherAgents, otherAgentsLine } from "./others.js";
18
+ import { PASSED_ENV, installCopy, installSchedule, installedSchedule, lingerWarning, olderVersion, pruneVersions, scheduleUnsupported, scheduledVersion, stableRuntime, uninstallSchedule, } from "./schedule.js";
16
19
  import { accountOf, acquireLock } from "./state.js";
17
20
  import { describeStatus, readStamps, readStatus, recordRun, unsyncedTranscripts } from "./status.js";
18
21
  import { findTranscripts, formatBytes, runSync } from "./sync.js";
19
22
  const MAX_RETRIES = 4;
20
- /** Exit code for a refused key; --install does not schedule a sync that cannot succeed. */
23
+ /**
24
+ * Exit code for a key that cannot do this: refused, not allowed to write the namespace, or
25
+ * acting for several organizations without --org. --install schedules nothing after it.
26
+ */
21
27
  const AUTH_FAILED = 3;
22
28
  /**
23
29
  * Exit code for a sync that ran but did not finish: documents refused, the API unreachable,
@@ -25,10 +31,13 @@ const AUTH_FAILED = 3;
25
31
  * but not after 1, which is what an unexpected exception exits with.
26
32
  */
27
33
  const INCOMPLETE = 4;
34
+ /** Exit code for out of credits or over a spend cap (402); --install schedules nothing after it. */
35
+ const BILLING = 5;
36
+ const KEYS_URL = "https://conare.ai/dashboard/keys";
28
37
  async function main(argv) {
29
38
  const args = parseArgs(argv);
30
39
  if ("error" in args) {
31
- process.stderr.write(`${args.error}\n\n${HELP}`);
40
+ process.stderr.write(args.error === LEGACY_USAGE ? `${args.error}\n` : `${args.error}\n\n${HELP}`);
32
41
  return 2;
33
42
  }
34
43
  if (args.help) {
@@ -46,16 +55,23 @@ async function main(argv) {
46
55
  };
47
56
  // Errors reach the log when run by the schedule, so they carry a time there.
48
57
  const fail = (line) => console.error(args.quiet ? `${new Date().toISOString()} ${line}` : line);
58
+ const org = args.org ?? (process.env.CONARE_ORG || undefined);
49
59
  if (args.command === "status") {
50
60
  const status = readStatus(paths.statusFile);
51
61
  const lastSuccess = status.lastSuccessAt ? Date.parse(status.lastSuccessAt) : NaN;
52
62
  const unsynced = Number.isFinite(lastSuccess)
53
- ? unsyncedTranscripts(findTranscripts(paths).map((f) => f.path), readStamps(paths.stateFile), lastSuccess)
63
+ ? unsyncedTranscripts(findTranscripts(paths), readStamps(paths.stateFile), lastSuccess)
54
64
  : [];
55
- const { text, ok } = describeStatus(status, Date.now(), installedSchedule({ platform: process.platform }), unsynced);
65
+ const host = { platform: process.platform };
66
+ const background = installedSchedule(host) ?? (scheduleUnsupported(host) ? "not available here (npx conare sync --install says how to schedule it yourself)" : undefined);
67
+ const { text, ok } = describeStatus(status, Date.now(), background, unsynced);
56
68
  process.stdout.write(text);
69
+ for (const line of notes(true))
70
+ console.log(line);
57
71
  return ok ? 0 : 1;
58
72
  }
73
+ if (!args.dryRun)
74
+ privateDir(paths.dir);
59
75
  if (args.key) {
60
76
  saveKey(paths.keyFile, args.key);
61
77
  say(`Saved the key to ${tilde(paths.keyFile)}.`);
@@ -68,41 +84,72 @@ async function main(argv) {
68
84
  }
69
85
  const envKey = process.env.CONARE_API_KEY || undefined;
70
86
  const apiKey = args.key ?? envKey ?? readSavedKey(paths.keyFile);
71
- if (!apiKey && !args.dryRun) {
72
- fail("No API key. Create one at https://conare.ai/console/keys, then run:\n npx conare sync --key sk-conare-…");
87
+ // --via supplies the key to the scheduled runs (and to install's check run).
88
+ if (!apiKey && !args.dryRun && !args.via) {
89
+ fail(`No API key. Create one at ${KEYS_URL} (access is by invitation: https://conare.ai/request-access), then run:\n npx conare sync --key sk-conare-…`);
73
90
  return 1;
74
91
  }
75
92
  if (args.command === "github")
76
- return syncGitHub(args, paths, apiKey, say, fail);
93
+ return syncGitHub(args, paths, apiKey, org, say, fail);
77
94
  if (args.install) {
95
+ const unsupported = scheduleUnsupported({ platform: process.platform });
96
+ if (unsupported) {
97
+ fail(unsupported); // before anything is copied or synced
98
+ return 1;
99
+ }
78
100
  if (!args.key && !args.via && envKey && readSavedKey(paths.keyFile) !== envKey) {
79
101
  // The schedule does not see this shell's environment; it reads the saved key.
80
102
  saveKey(paths.keyFile, envKey);
81
103
  say(`Saved the key from CONARE_API_KEY to ${tilde(paths.keyFile)} for the background sync.`);
82
104
  }
83
- return install(args, paths, say, fail);
105
+ return install(args, paths, apiKey, say, fail);
84
106
  }
85
- if (args.dryRun)
86
- return syncSessions(args, paths, apiKey, say, fail); // writes nothing: no lock, no record
87
- const release = acquireLock(paths.lockFile);
88
- if (!release) {
89
- if (!args.quiet)
90
- fail("Another sync is running.");
91
- return args.quiet ? 0 : INCOMPLETE;
107
+ let code;
108
+ if (args.dryRun) {
109
+ code = await syncSessions(args, paths, apiKey, org, say, fail); // writes nothing: no lock, no record
92
110
  }
93
- try {
94
- return await syncSessions(args, paths, apiKey, say, fail);
111
+ else {
112
+ const release = acquireLock(paths.lockFile);
113
+ if (!release) {
114
+ if (!args.quiet)
115
+ fail("Another sync is running.");
116
+ return args.quiet ? 0 : INCOMPLETE;
117
+ }
118
+ try {
119
+ code = await syncSessions(args, paths, apiKey, org, say, fail);
120
+ }
121
+ finally {
122
+ release();
123
+ }
95
124
  }
96
- finally {
97
- release();
125
+ if (!args.quiet)
126
+ for (const line of notes(!fileURLToPath(import.meta.url).startsWith(paths.installRoot)))
127
+ console.log(line);
128
+ return code;
129
+ }
130
+ /**
131
+ * What an interactive run says besides its own result: agents on this machine it does not
132
+ * sync, and an installed schedule running an older version (not said by an installed copy,
133
+ * which is the schedule itself or --install's first run).
134
+ */
135
+ function notes(version) {
136
+ const out = [];
137
+ const others = otherAgentsLine(otherAgents());
138
+ if (others)
139
+ out.push(others);
140
+ const scheduled = version ? scheduledVersion({ platform: process.platform }) : undefined;
141
+ if (scheduled && olderVersion(scheduled, VERSION)) {
142
+ out.push(`Background sync runs ${scheduled}; this is ${VERSION}: run npx conare sync --install to update.`);
98
143
  }
144
+ return out;
99
145
  }
100
146
  /**
101
147
  * Copy the package to ~/.conare/sync/<version>/, check the copy (files and sizes), run it once
102
- * (`--version`, then a real sync), and only then point the schedule at it. A copy that does
103
- * not start, or a refused key, leaves the schedule as it was.
148
+ * (`--version`, then a real sync with the key the schedule will use), and only then point the
149
+ * schedule at it. A copy that does not start, or a key that cannot write, leaves the schedule
150
+ * as it was.
104
151
  */
105
- function install(args, paths, say, fail) {
152
+ function install(args, paths, apiKey, say, fail) {
106
153
  let via;
107
154
  if (args.via) {
108
155
  via = args.via.startsWith("/") ? args.via : spawnSync("/bin/sh", ["-c", 'command -v "$0"', args.via], { encoding: "utf8" }).stdout.trim();
@@ -118,28 +165,52 @@ function install(args, paths, say, fail) {
118
165
  fail(`The installed copy ${script} did not start (${probe.error?.message ?? `exit ${probe.status}: ${probe.stderr.trim()}`}). The schedule is unchanged.`);
119
166
  return 1;
120
167
  }
121
- const run = spawnSync(runtime, [script, "sync", ...(args.quiet ? ["--quiet"] : [])], { stdio: "inherit" });
122
- if (run.status === AUTH_FAILED)
123
- return AUTH_FAILED;
168
+ // The first run checks what the schedule will run: through --via, which supplies the key,
169
+ // or with the key just saved (not another one in this shell's CONARE_API_KEY).
170
+ const env = { ...process.env };
171
+ if (via)
172
+ delete env.CONARE_API_KEY;
173
+ else if (apiKey)
174
+ env.CONARE_API_KEY = apiKey;
175
+ if (args.org)
176
+ env.CONARE_ORG = args.org;
177
+ const before = readStatus(paths.statusFile).lastRun?.at;
178
+ const run = spawnSync(via ?? runtime, [...(via ? [runtime] : []), script, "sync", ...(args.quiet ? ["--quiet"] : [])], { stdio: "inherit", env });
179
+ if (run.status === AUTH_FAILED || run.status === BILLING) {
180
+ fail("The schedule is unchanged.");
181
+ return run.status;
182
+ }
124
183
  if (run.status !== 0 && run.status !== INCOMPLETE) {
125
184
  fail(`The installed copy's first sync ended with ${run.signal ?? `exit ${run.status}`}. The schedule is unchanged.`);
126
185
  return 1;
127
186
  }
128
- const env = {};
187
+ // A run that found another sync holding the lock records nothing: it checked no key.
188
+ const unchecked = run.status === INCOMPLETE && readStatus(paths.statusFile).lastRun?.at === before;
189
+ const scheduleEnv = {};
129
190
  for (const name of PASSED_ENV)
130
191
  if (process.env[name])
131
- env[name] = process.env[name];
192
+ scheduleEnv[name] = process.env[name];
193
+ if (args.org)
194
+ scheduleEnv.CONARE_ORG = args.org;
132
195
  if (via && process.env.PATH)
133
- env.PATH = process.env.PATH; // the --via command finds its own tools
134
- const what = installSchedule({ node: runtime, script, logFile: paths.logFile, env, via }, { platform: process.platform });
196
+ scheduleEnv.PATH = process.env.PATH; // the --via command finds its own tools
197
+ const host = { platform: process.platform };
198
+ const what = installSchedule({ node: runtime, script, logFile: paths.logFile, env: scheduleEnv, via }, host);
135
199
  pruneVersions(paths.installRoot, VERSION); // only now: a failed install keeps the old schedule's script
136
200
  say(`Installed: sync every 10 minutes (${what}), running ${tilde(script)}.\nLog: ${tilde(paths.logFile)}. Check it with: npx conare sync status. Stop it with: npx conare sync --uninstall`);
201
+ if (unchecked)
202
+ say("Another sync was running, so the key was not checked; the background sync's first run checks it (npx conare sync status).");
203
+ const linger = lingerWarning(host);
204
+ if (linger)
205
+ say(linger);
206
+ for (const line of retireLegacy(runtime, script, host))
207
+ say(line);
137
208
  return run.status ?? 1;
138
209
  }
139
- async function syncSessions(args, paths, apiKey, say, fail) {
210
+ async function syncSessions(args, paths, apiKey, org, say, fail) {
140
211
  const started = Date.now();
141
- const client = apiKey ? new Conare({ apiKey, maxRetries: MAX_RETRIES }) : undefined;
142
- const files = findTranscripts(paths);
212
+ const client = apiKey ? new Conare({ apiKey, maxRetries: MAX_RETRIES, organization: org }) : undefined;
213
+ const files = findTranscripts(paths, { save: !args.dryRun, log: fail }); // fail: under --quiet a database that stays unreadable must reach the log
143
214
  say(`Found ${files.length} transcripts.`);
144
215
  let report;
145
216
  let error;
@@ -148,7 +219,8 @@ async function syncSessions(args, paths, apiKey, say, fail) {
148
219
  report = await runSync({
149
220
  files,
150
221
  stateFile: paths.stateFile,
151
- account: client ? accountOf(client.baseURL, apiKey) : "",
222
+ // No key (a dry run): counted against the saved state, whichever key wrote it.
223
+ account: client ? accountOf(client.baseURL, apiKey, org) : undefined,
152
224
  client: args.dryRun ? undefined : client,
153
225
  log: say,
154
226
  exclude: readExcluded(paths.excludeFile),
@@ -158,7 +230,7 @@ async function syncSessions(args, paths, apiKey, say, fail) {
158
230
  if (args.dryRun) {
159
231
  for (const p of report.planned)
160
232
  say(` ${p.id} ${formatBytes(p.bytes)}`);
161
- say(`Would upload ${report.documents} documents from ${report.sessions} sessions (${formatBytes(report.bytes)}). ${report.unchanged} unchanged.`);
233
+ say(`Would upload ${report.documents} documents from ${report.sessions} sessions (${formatBytes(report.bytes)}). ${report.unchanged} unchanged.${client ? "" : " No key: counted against this machine's last sync."}`);
162
234
  return 0;
163
235
  }
164
236
  for (const r of report.rejected)
@@ -167,7 +239,7 @@ async function syncSessions(args, paths, apiKey, say, fail) {
167
239
  ? `Synced ${report.sessions} sessions: ${report.documents} documents, ${formatBytes(report.bytes)}. ${report.unchanged} unchanged.`
168
240
  : `Up to date: ${report.unchanged} sessions.`);
169
241
  if (report.unread > 0)
170
- say(`${report.unread} transcripts hold no message this version can read; they are read again next run.`);
242
+ say(`${report.unread} transcripts hold no message this version can read; each is read again when it changes or by another version.`);
171
243
  for (const path of report.unreadable)
172
244
  fail(`Could not read, tried again next run: ${path}`);
173
245
  code = report.rejected.length > 0 || report.unreadable.length > 0 ? INCOMPLETE : 0;
@@ -175,16 +247,11 @@ async function syncSessions(args, paths, apiKey, say, fail) {
175
247
  error = `${report.rejected.length} documents not accepted, ${report.unreadable.length} transcripts not read`;
176
248
  }
177
249
  catch (err) {
178
- if (err instanceof ConareError && err.status === 401) {
179
- error = `The API key was refused (${err.status} ${err.code}).`;
180
- fail(`${error} Save a valid one: npx conare sync --key sk-conare-…`);
181
- code = AUTH_FAILED;
182
- }
183
- else if (err instanceof ConareError && err.status === 403) {
184
- // The key is valid but may not write here (a key scoped to other namespaces).
185
- error = `The API key may not do this: ${err.message} (403 ${err.code}).`;
186
- fail(error);
187
- code = INCOMPLETE;
250
+ const problem = keyProblem(err, NAMESPACE);
251
+ if (problem) {
252
+ error = problem.error;
253
+ fail(`${problem.error} ${problem.hint}`);
254
+ code = problem.code;
188
255
  }
189
256
  else {
190
257
  const detail = err instanceof ConareError ? apiDetail(err) : String(err);
@@ -205,20 +272,40 @@ async function syncSessions(args, paths, apiKey, say, fail) {
205
272
  }, report?.newest);
206
273
  return code;
207
274
  }
208
- async function syncGitHub(args, paths, apiKey, say, fail) {
275
+ /**
276
+ * An answer that no later run with the same key and options gets past: the key refused (401),
277
+ * not allowed to write `namespace` (403), the organization out of credits or over its cap
278
+ * (402), or a key of several organizations sent without one (400).
279
+ */
280
+ function keyProblem(err, namespace) {
281
+ if (!(err instanceof ConareError))
282
+ return undefined;
283
+ if (err.status === 401)
284
+ return { error: `The API key was refused (${err.status} ${err.code}).`, hint: "Save a valid one: npx conare sync --key sk-conare-…", code: AUTH_FAILED };
285
+ if (err.status === 403) {
286
+ return { error: `The API key may not write the namespace "${namespace}": ${err.message} (403 ${err.code}).`, hint: `Use a key with full access: ${KEYS_URL}`, code: AUTH_FAILED };
287
+ }
288
+ if (err.status === 402)
289
+ return { error: `${err.message} (402 ${err.code}).`, hint: "See https://conare.ai/dashboard/billing", code: BILLING };
290
+ if (err.status === 400 && /several organizations/.test(err.message)) {
291
+ return { error: `This key acts for several organizations (400 ${err.code}).`, hint: "Say which one to write to: --org org_… (or CONARE_ORG).", code: AUTH_FAILED };
292
+ }
293
+ return undefined;
294
+ }
295
+ async function syncGitHub(args, paths, apiKey, org, say, fail) {
209
296
  const token = githubToken();
210
297
  if (!token) {
211
298
  fail("No GitHub token: set GITHUB_TOKEN, or log in with `gh auth login`.");
212
299
  return 1;
213
300
  }
214
301
  const gh = new GitHub(token, { baseURL: process.env.GITHUB_API_URL || undefined, graphqlURL: process.env.GITHUB_GRAPHQL_URL || undefined });
215
- const client = apiKey ? new Conare({ apiKey, maxRetries: MAX_RETRIES }) : undefined;
216
- const account = client ? accountOf(client.baseURL, apiKey) : undefined;
302
+ const client = apiKey ? new Conare({ apiKey, maxRetries: MAX_RETRIES, organization: org }) : undefined;
303
+ const account = client ? accountOf(client.baseURL, apiKey, org) : undefined;
217
304
  const stateFile = args.state ?? paths.githubStateFile;
218
305
  const release = args.dryRun ? () => { } : acquireLock(`${stateFile}.lock`);
219
306
  if (!release) {
220
307
  fail(`Another github sync is using ${stateFile}.`);
221
- return 1;
308
+ return INCOMPLETE;
222
309
  }
223
310
  let code = 0;
224
311
  try {
@@ -255,13 +342,16 @@ async function syncGitHub(args, paths, apiKey, say, fail) {
255
342
  }
256
343
  }
257
344
  catch (err) {
258
- if (err instanceof ConareError && err.status === 401) {
259
- fail(`The API key was refused (${err.status} ${err.code}).`);
260
- return AUTH_FAILED;
345
+ const problem = keyProblem(err, `${name}-github`);
346
+ if (problem) {
347
+ fail(`${problem.error} ${problem.hint}`);
348
+ return problem.code; // the same for every repository
261
349
  }
262
350
  const detail = err instanceof ConareError ? apiDetail(err) : err instanceof Error ? err.message : String(err);
263
351
  fail(`${repo}: sync stopped: ${detail}. The state is unchanged; the next run tries again.`);
264
- code = err instanceof ConareError || err instanceof GitHubError ? (code === 1 ? 1 : INCOMPLETE) : 1;
352
+ // A token or repository GitHub refuses (401, 404) fails the same way next run.
353
+ const retry = err instanceof ConareError || (err instanceof GitHubError && err.status !== 401 && err.status !== 404);
354
+ code = retry && code !== 1 ? INCOMPLETE : 1;
265
355
  }
266
356
  }
267
357
  }
@@ -0,0 +1,46 @@
1
+ // Coding agents on this machine whose sessions this version does not sync, so a sync can say
2
+ // so instead of skipping them silently: OpenCode and Grok, and Cursor where the runtime has no
3
+ // node:sqlite to read it with. Only whether their stores exist, and a count where it is a
4
+ // directory listing away: no file is opened.
5
+ import { existsSync, readdirSync } from "node:fs";
6
+ import { homedir } from "node:os";
7
+ import { join } from "node:path";
8
+ import { cursorDbPath } from "./config.js";
9
+ import { loadSqlite } from "./sources/cursor.js";
10
+ /** "OpenCode", or "Grok (3 sessions)", for each agent found. `sqlite`: whether Cursor can be read here. */
11
+ export function otherAgents(home = homedir(), platform = process.platform, sqlite = loadSqlite() !== undefined) {
12
+ const found = [];
13
+ if (!sqlite && existsSync(cursorDbPath(home, platform)))
14
+ found.push("Cursor (needs Node 22.13 or newer)");
15
+ if (existsSync(join(home, ".local", "share", "opencode", "storage")))
16
+ found.push("OpenCode");
17
+ const grok = count(join(home, ".grok", "sessions"), () => true, 0);
18
+ if (grok !== undefined)
19
+ found.push(sessions("Grok", grok));
20
+ return found;
21
+ }
22
+ /** The line a sync prints when other agents are found; undefined when none is. */
23
+ export function otherAgentsLine(found) {
24
+ return found.length > 0 ? `Not synced (this version reads Claude Code, Codex, Cursor and Pi): ${found.join(", ")}.` : undefined;
25
+ }
26
+ function sessions(name, n) {
27
+ return n > 0 ? `${name} (${n} session${n === 1 ? "" : "s"})` : name;
28
+ }
29
+ /** Entries of dir (and of its subdirectories, `depth` levels down) that match; undefined when dir does not exist. */
30
+ function count(dir, match, depth) {
31
+ let entries;
32
+ try {
33
+ entries = readdirSync(dir, { withFileTypes: true });
34
+ }
35
+ catch {
36
+ return undefined;
37
+ }
38
+ let n = 0;
39
+ for (const e of entries) {
40
+ if (e.isDirectory() && depth > 0)
41
+ n += count(join(dir, e.name), match, depth - 1) ?? 0;
42
+ else if (match(e.name))
43
+ n++;
44
+ }
45
+ return n;
46
+ }
@@ -2,8 +2,8 @@
2
2
  // package under ~/.conare/sync/<version>/ so it does not depend on the npx cache.
3
3
  // macOS: a launchd agent. Linux: a systemd user timer.
4
4
  import { execFileSync } from "node:child_process";
5
- import { cpSync, existsSync, mkdirSync, readdirSync, realpathSync, renameSync, rmSync, statSync, unlinkSync, writeFileSync } from "node:fs";
6
- import { homedir } from "node:os";
5
+ import { cpSync, existsSync, mkdirSync, readFileSync, readdirSync, realpathSync, renameSync, rmSync, statSync, unlinkSync, writeFileSync } from "node:fs";
6
+ import { homedir, userInfo } from "node:os";
7
7
  import { basename, delimiter, join, resolve } from "node:path";
8
8
  export const LABEL = "ai.conare.sync";
9
9
  export const UNIT = "conare-sync";
@@ -12,7 +12,7 @@ function command(job) {
12
12
  return [...(job.via ? [job.via] : []), job.node, job.script, "sync", "--quiet"];
13
13
  }
14
14
  /** Variables passed on to the scheduled run when set at install time. */
15
- export const PASSED_ENV = ["CONARE_BASE_URL", "CLAUDE_CONFIG_DIR", "CODEX_HOME"];
15
+ export const PASSED_ENV = ["CONARE_BASE_URL", "CONARE_ORG", "CLAUDE_CONFIG_DIR", "CODEX_HOME", "PI_CODING_AGENT_DIR", "PI_CODING_AGENT_SESSION_DIR"];
16
16
  /**
17
17
  * Copy the built package (the directory holding index.js and cli/) to <root>/<version> and
18
18
  * return the installed script path. The copy is made beside the target, checked file by file
@@ -171,7 +171,7 @@ export function systemdService(job) {
171
171
  const exec = command(job).map(quoteArg).join(" ");
172
172
  const env = Object.entries(job.env).map(([k, v]) => `Environment=${quoteArg(`${k}=${v}`)}\n`).join("");
173
173
  return `[Unit]
174
- Description=Conare sync of Claude Code and Codex sessions
174
+ Description=Conare sync of coding agent sessions
175
175
 
176
176
  [Service]
177
177
  Type=oneshot
@@ -200,9 +200,7 @@ function quoteArg(s) {
200
200
  function unitPath(s) {
201
201
  return s.replace(/%/g, "%%");
202
202
  }
203
- const run = (cmd, args) => {
204
- execFileSync(cmd, args, { stdio: "ignore" });
205
- };
203
+ const run = (cmd, args) => execFileSync(cmd, args, { stdio: ["ignore", "pipe", "ignore"], encoding: "utf8" });
206
204
  function tryRun(r, cmd, args) {
207
205
  try {
208
206
  r(cmd, args);
@@ -212,6 +210,23 @@ function tryRun(r, cmd, args) {
212
210
  return false;
213
211
  }
214
212
  }
213
+ /**
214
+ * Why --install cannot schedule the sync here, with the line to schedule it by hand; undefined
215
+ * when it can (macOS, or Linux with a systemd user manager). Checked before anything is copied.
216
+ */
217
+ export function scheduleUnsupported(s) {
218
+ if (s.platform === "darwin")
219
+ return undefined;
220
+ if (s.platform === "linux") {
221
+ if (tryRun(s.run ?? run, "systemctl", ["--user", "show-environment"]))
222
+ return undefined;
223
+ return "--install needs a systemd user manager, and this machine has none (systemctl --user fails). Schedule the sync with cron instead (crontab -e):\n */10 * * * * npx -y conare sync --quiet >> ~/.conare/sync.log 2>&1";
224
+ }
225
+ if (s.platform === "win32") {
226
+ return '--install schedules the sync on macOS and Linux only. On Windows, schedule it yourself:\n schtasks /Create /SC MINUTE /MO 10 /TN conare-sync /TR "npx -y conare sync --quiet"';
227
+ }
228
+ return `--install schedules the sync on macOS and Linux only, not ${s.platform}. Run \`npx -y conare sync --quiet\` every 10 minutes with your own scheduler.`;
229
+ }
215
230
  /** Write and load the schedule. Returns a short description of what was installed. */
216
231
  export function installSchedule(job, s) {
217
232
  const r = s.run ?? run;
@@ -231,11 +246,20 @@ export function installSchedule(job, s) {
231
246
  mkdirSync(dir, { recursive: true });
232
247
  writeFileSync(join(dir, `${UNIT}.service`), systemdService(job));
233
248
  writeFileSync(join(dir, `${UNIT}.timer`), systemdTimer());
234
- r("systemctl", ["--user", "daemon-reload"]);
235
- r("systemctl", ["--user", "enable", "--now", `${UNIT}.timer`]);
249
+ try {
250
+ r("systemctl", ["--user", "daemon-reload"]);
251
+ r("systemctl", ["--user", "enable", "--now", `${UNIT}.timer`]);
252
+ }
253
+ catch (err) {
254
+ // Unit files no timer runs would read as an installed sync.
255
+ remove(join(dir, `${UNIT}.timer`));
256
+ remove(join(dir, `${UNIT}.service`));
257
+ tryRun(r, "systemctl", ["--user", "daemon-reload"]);
258
+ throw err;
259
+ }
236
260
  return `systemd user timer ${join(dir, `${UNIT}.timer`)}`;
237
261
  }
238
- throw new Error(`--install supports macOS and Linux. On ${s.platform}, run \`npx conare sync --quiet\` every 10 minutes with your scheduler.`);
262
+ throw new Error(scheduleUnsupported(s));
239
263
  }
240
264
  /** Stop and remove the schedule. Returns false when there was nothing to remove. */
241
265
  export function uninstallSchedule(s) {
@@ -257,6 +281,46 @@ export function uninstallSchedule(s) {
257
281
  }
258
282
  return false;
259
283
  }
284
+ /**
285
+ * Linux: a user timer runs only while the user is logged in, unless lingering is on. The line
286
+ * saying so after an install, or undefined (lingering on, or not known).
287
+ */
288
+ export function lingerWarning(s) {
289
+ if (s.platform !== "linux")
290
+ return undefined;
291
+ let out;
292
+ try {
293
+ out = (s.run ?? run)("loginctl", ["show-user", userInfo().username, "-p", "Linger"]);
294
+ }
295
+ catch {
296
+ return undefined;
297
+ }
298
+ return typeof out === "string" && out.trim() === "Linger=no"
299
+ ? "The timer stops when you log out; to keep it running, run: loginctl enable-linger"
300
+ : undefined;
301
+ }
302
+ /** The version the installed schedule runs, from its script path (~/.conare/sync/<version>/cli/main.js); undefined when none is installed. */
303
+ export function scheduledVersion(s) {
304
+ const home = s.home ?? homedir();
305
+ const file = s.platform === "darwin" ? launchdPlistPath(home) : s.platform === "linux" ? join(systemdDir(s.env, home), `${UNIT}.service`) : undefined;
306
+ if (!file)
307
+ return undefined;
308
+ try {
309
+ return /[/\\]sync[/\\]([^/\\"<]+)[/\\]cli[/\\]main\.js/.exec(readFileSync(file, "utf8"))?.[1];
310
+ }
311
+ catch {
312
+ return undefined;
313
+ }
314
+ }
315
+ /** True when version a is older than b (x.y.z; anything after a "-" is ignored). */
316
+ export function olderVersion(a, b) {
317
+ const parse = (v) => v.split("-")[0].split(".").map((n) => Number(n) || 0);
318
+ const [x, y] = [parse(a), parse(b)];
319
+ for (let i = 0; i < 3; i++)
320
+ if ((x[i] ?? 0) !== (y[i] ?? 0))
321
+ return (x[i] ?? 0) < (y[i] ?? 0);
322
+ return false;
323
+ }
260
324
  const NOT_LOADED = " (NOT LOADED: run npx conare sync --install again)";
261
325
  /** Where the schedule is installed, flagged when the scheduler has not loaded it; undefined when it is not installed. */
262
326
  export function installedSchedule(s) {
package/dist/cli/scrub.js CHANGED
@@ -10,13 +10,20 @@ const CODE = /[([]/; // readPassword(prompt), os.environ["TOKEN"]
10
10
  // ("SUPERSECRET") is a value like any other.
11
11
  const ENV_NAME = /^[A-Z][A-Z0-9]*(?:_[A-Z0-9]*)+$/;
12
12
  const TYPE_OR_LITERAL = /^(?:string|number|boolean|null|none|nil|undefined|true|false|required|optional)$/i;
13
+ // What a person types in an example config: xxxxxx, ******, changeme, "your password here".
14
+ const PLACEHOLDER = /^(?:(.)\1*|change[_-]?me|placeholder|your[\s_-].*)$/i;
13
15
  /**
14
16
  * The value of password=…, token: … and the like, unless it is code, a variable name or a
15
17
  * placeholder. Any other value counts, letters or digits alone included: a chosen password
16
18
  * ("supersecretpassword") or a numeric token is still a secret.
17
19
  */
18
20
  function assignedSecret(value) {
19
- return !(REFERENCE.test(value) || DOTTED.test(value) || CODE.test(value) || ENV_NAME.test(value) || TYPE_OR_LITERAL.test(value));
21
+ return !(REFERENCE.test(value) ||
22
+ DOTTED.test(value) ||
23
+ CODE.test(value) ||
24
+ ENV_NAME.test(value) ||
25
+ TYPE_OR_LITERAL.test(value) ||
26
+ PLACEHOLDER.test(value));
20
27
  }
21
28
  /** An Authorization value: anything but a reference, a dotted name or a short plain word. */
22
29
  function credentialLike(value) {
@@ -25,10 +32,11 @@ function credentialLike(value) {
25
32
  return !/^[A-Za-z]+$/.test(value) || value.length >= 24;
26
33
  }
27
34
  const RULES = [
28
- // PEM private keys: the whole block, or the base64 lines after a header whose END is missing.
35
+ // PEM private keys: the whole block, or the base64 lines after a header whose END is missing
36
+ // (indented: the renderer indents kept tool output under its call).
29
37
  {
30
38
  kind: "private_key",
31
- re: /-----BEGIN[A-Z0-9 ]{0,30} PRIVATE KEY(?: BLOCK)?-----(?:[A-Za-z0-9+/=\s\\:,.-]{0,16384}?-----END[A-Z0-9 ]{0,30} PRIVATE KEY(?: BLOCK)?-----|(?:(?:\r?\n|\\n)[A-Za-z0-9+/=]{16,})*)/g,
39
+ re: /-----BEGIN[A-Z0-9 ]{0,30} PRIVATE KEY(?: BLOCK)?-----(?:[A-Za-z0-9+/=\s\\:,.-]{0,16384}?-----END[A-Z0-9 ]{0,30} PRIVATE KEY(?: BLOCK)?-----|(?:(?:\r?\n|\\n)[ \t]*[A-Za-z0-9+/=]{16,})*)/g,
32
40
  },
33
41
  { kind: "conare_key", re: /\b(?:sk-conare-|cmem_)[A-Za-z0-9]{16,}/g },
34
42
  { kind: "anthropic_key", re: /\bsk-ant-[A-Za-z0-9_-]{20,}/g },
@@ -53,7 +61,16 @@ const RULES = [
53
61
  // A GCP service-account key file's private_key_id (40 hex); its private_key is a PEM block.
54
62
  { kind: "private_key_id", re: /(\bprivate_key_id["']?\s*[:=]\s*["']?)([a-f0-9]{40})\b/g, label: true },
55
63
  { kind: "aws_access_key", re: /\b(?:AKIA|ASIA)[A-Z0-9]{16}\b/g },
56
- { kind: "slack_token", re: /\bxox[abposr]-[A-Za-z0-9-]{10,}/g },
64
+ // Slack bot and user tokens (xoxb-, xoxp-, …), rotating ones (xoxe-, xoxe.xoxp-) and
65
+ // app-level tokens (xapp-1-…).
66
+ { kind: "slack_token", re: /\b(?:xox(?:[abposr]|e(?:\.xox[a-z])?)|xapp-\d)-[A-Za-z0-9-]{10,}/g },
67
+ // Incoming-webhook URLs: the last path segment is the credential; the ids before it stay.
68
+ { kind: "slack_webhook", re: /(\bhooks\.slack\.com\/services\/T[A-Z0-9]+\/B[A-Z0-9]+\/)([A-Za-z0-9]{16,})/g, label: true },
69
+ {
70
+ kind: "discord_webhook",
71
+ re: /(\bdiscord(?:app)?\.com\/api\/(?:v\d+\/)?webhooks\/\d{15,20}\/)([A-Za-z0-9_-]{40,})/g,
72
+ label: true,
73
+ },
57
74
  { kind: "google_api_key", re: /\bAIza[0-9A-Za-z_-]{35}/g },
58
75
  { kind: "huggingface_token", re: /\bhf_[A-Za-z0-9]{30,}/g },
59
76
  // 1Password service-account tokens: ops_ then base64 JSON (not a three-part JWT).
@@ -82,18 +99,20 @@ const RULES = [
82
99
  label: true,
83
100
  accept: (s) => !/^[$%{<[]/.test(s),
84
101
  },
85
- // password=…, secret: "…", api_key=…, token=…; the keyword ends the name, so
86
- // max_tokens=4096 and tokenizer=… are not matched. A password is chosen by a person and
87
- // can be short (6+); the other values are generated (12+).
102
+ // password=…, secret: "…", api_key=…, token=…, SECRET_KEY=…, "secretKey": "…"; the keyword
103
+ // ends the name, so max_tokens=4096, tokenizer=…, primaryKey and sort_key are not matched.
104
+ // A password is chosen by a person and can be short (6+); the other values are generated
105
+ // (12+). A quoted value runs to its closing quote: a passphrase has spaces, a generated
106
+ // value has none but may hold , ; ) and the like.
88
107
  {
89
108
  kind: "secret",
90
- re: /((?:password|passwd)["']?\s*[:=]\s*["']?)([^\s"'`,;)}\]]{6,})/gi,
109
+ re: /((?:password|passwd|_pwd)["']?\s*[:=]\s*["']?)((?<=")[^"\n]{6,}(?=")|(?<=')[^'\n]{6,}(?=')|[^\s"'`,;)}\]]{6,})/gi,
91
110
  label: true,
92
111
  accept: assignedSecret,
93
112
  },
94
113
  {
95
114
  kind: "secret",
96
- re: /((?:secret|token|api[_-]?key|access[_-]?key|private[_-]?key)["']?\s*[:=]\s*["']?)([^\s"'`,;)}\]]{12,})/gi,
115
+ re: /((?:secret|token|(?:api|access|private|secret|encryption|signing|master|app)[_-]?key|secret[_-]?key[_-]?base)["']?\s*[:=]\s*["']?)((?<=")[^"\s]{12,}(?=")|(?<=')[^'\s]{12,}(?=')|[^\s"'`,;)}\]]{12,})/gi,
97
116
  label: true,
98
117
  accept: assignedSecret,
99
118
  },