agentsofmine 0.0.0-stage → 0.1.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.
Files changed (102) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +297 -2
  3. package/dist/adapters/adapter.d.ts +14 -0
  4. package/dist/adapters/adapter.js +2 -0
  5. package/dist/adapters/claude-code/accumulator.d.ts +34 -0
  6. package/dist/adapters/claude-code/accumulator.js +129 -0
  7. package/dist/adapters/claude-code/content-blocks.d.ts +40 -0
  8. package/dist/adapters/claude-code/content-blocks.js +93 -0
  9. package/dist/adapters/claude-code/index.d.ts +20 -0
  10. package/dist/adapters/claude-code/index.js +92 -0
  11. package/dist/adapters/claude-code/jsonl-reader.d.ts +14 -0
  12. package/dist/adapters/claude-code/jsonl-reader.js +31 -0
  13. package/dist/adapters/claude-code/mapper.d.ts +6 -0
  14. package/dist/adapters/claude-code/mapper.js +23 -0
  15. package/dist/adapters/codex/index.d.ts +8 -0
  16. package/dist/adapters/codex/index.js +42 -0
  17. package/dist/adapters/codex/log-reader.d.ts +14 -0
  18. package/dist/adapters/codex/log-reader.js +182 -0
  19. package/dist/adapters/codex/shell-parser.d.ts +6 -0
  20. package/dist/adapters/codex/shell-parser.js +72 -0
  21. package/dist/adapters/opencode/file-changes.d.ts +8 -0
  22. package/dist/adapters/opencode/file-changes.js +38 -0
  23. package/dist/adapters/opencode/index.d.ts +13 -0
  24. package/dist/adapters/opencode/index.js +58 -0
  25. package/dist/adapters/opencode/mapper.d.ts +4 -0
  26. package/dist/adapters/opencode/mapper.js +56 -0
  27. package/dist/adapters/opencode/sqlite-reader.d.ts +19 -0
  28. package/dist/adapters/opencode/sqlite-reader.js +109 -0
  29. package/dist/adapters/pi/index.d.ts +8 -0
  30. package/dist/adapters/pi/index.js +76 -0
  31. package/dist/adapters/pi/jsonl-reader.d.ts +2 -0
  32. package/dist/adapters/pi/jsonl-reader.js +2 -0
  33. package/dist/adapters/pi/mapper.d.ts +22 -0
  34. package/dist/adapters/pi/mapper.js +230 -0
  35. package/dist/api/pairing-client.d.ts +41 -0
  36. package/dist/api/pairing-client.js +77 -0
  37. package/dist/bin/aom.d.ts +13 -0
  38. package/dist/bin/aom.js +73 -0
  39. package/dist/cli/pair.d.ts +28 -0
  40. package/dist/cli/pair.js +114 -0
  41. package/dist/cli/start.d.ts +22 -0
  42. package/dist/cli/start.js +78 -0
  43. package/dist/cli/status.d.ts +19 -0
  44. package/dist/cli/status.js +108 -0
  45. package/dist/cli/sync.d.ts +16 -0
  46. package/dist/cli/sync.js +50 -0
  47. package/dist/cli/unpair.d.ts +18 -0
  48. package/dist/cli/unpair.js +49 -0
  49. package/dist/config.d.ts +15 -0
  50. package/dist/config.js +33 -0
  51. package/dist/core/canonical.d.ts +957 -0
  52. package/dist/core/canonical.js +80 -0
  53. package/dist/core/cursor-store.d.ts +18 -0
  54. package/dist/core/cursor-store.js +50 -0
  55. package/dist/core/debug-log.d.ts +12 -0
  56. package/dist/core/debug-log.js +17 -0
  57. package/dist/core/git-identity.d.ts +23 -0
  58. package/dist/core/git-identity.js +127 -0
  59. package/dist/core/http-client.d.ts +7 -0
  60. package/dist/core/http-client.js +63 -0
  61. package/dist/core/last-sync-store.d.ts +9 -0
  62. package/dist/core/last-sync-store.js +31 -0
  63. package/dist/core/message-truncation.d.ts +10 -0
  64. package/dist/core/message-truncation.js +13 -0
  65. package/dist/core/perform-sync.d.ts +23 -0
  66. package/dist/core/perform-sync.js +57 -0
  67. package/dist/core/project-identity.d.ts +40 -0
  68. package/dist/core/project-identity.js +67 -0
  69. package/dist/core/providers.d.ts +26 -0
  70. package/dist/core/providers.js +25 -0
  71. package/dist/core/providers.json +4 -0
  72. package/dist/core/redact.d.ts +44 -0
  73. package/dist/core/redact.js +177 -0
  74. package/dist/core/safe-json.d.ts +7 -0
  75. package/dist/core/safe-json.js +14 -0
  76. package/dist/core/sync-engine.d.ts +17 -0
  77. package/dist/core/sync-engine.js +64 -0
  78. package/dist/daemon/state.d.ts +22 -0
  79. package/dist/daemon/state.js +32 -0
  80. package/dist/daemon/sync-runner.d.ts +52 -0
  81. package/dist/daemon/sync-runner.js +104 -0
  82. package/dist/index.d.ts +2 -0
  83. package/dist/index.js +68 -0
  84. package/dist/infrastructure/config-repository.d.ts +34 -0
  85. package/dist/infrastructure/config-repository.js +102 -0
  86. package/dist/keychain/index.d.ts +31 -0
  87. package/dist/keychain/index.js +62 -0
  88. package/dist/mcp/json-rpc.d.ts +39 -0
  89. package/dist/mcp/json-rpc.js +46 -0
  90. package/dist/mcp/server.d.ts +33 -0
  91. package/dist/mcp/server.js +110 -0
  92. package/dist/mcp-tools/status.d.ts +17 -0
  93. package/dist/mcp-tools/status.js +24 -0
  94. package/dist/mcp-tools/sync-now.d.ts +9 -0
  95. package/dist/mcp-tools/sync-now.js +8 -0
  96. package/dist/services/pairing-service.d.ts +58 -0
  97. package/dist/services/pairing-service.js +102 -0
  98. package/dist/watchers/directory-watcher.d.ts +26 -0
  99. package/dist/watchers/directory-watcher.js +47 -0
  100. package/dist/watchers/opencode.d.ts +27 -0
  101. package/dist/watchers/opencode.js +58 -0
  102. package/package.json +64 -4
@@ -0,0 +1,80 @@
1
+ import { z } from "zod";
2
+ import { KNOWN_PROVIDERS, isKnownProvider } from "./providers.js";
3
+ export const ProjectIdentitySchema = z.object({
4
+ kind: z.enum(["git", "path-legacy"]),
5
+ canonical: z.string(),
6
+ displayName: z.string(),
7
+ git: z
8
+ .object({
9
+ root: z.string(),
10
+ remoteName: z.string(),
11
+ remoteUrl: z.string(),
12
+ branch: z.string().nullable(),
13
+ headCommit: z.string().nullable(),
14
+ })
15
+ .optional(),
16
+ local: z.object({
17
+ path: z.string(),
18
+ basename: z.string(),
19
+ }),
20
+ });
21
+ export const CanonicalSessionSchema = z.object({
22
+ sessionId: z.string(),
23
+ // Allowlist is data-driven via providers.json (see ./providers.ts), not a hardcoded enum.
24
+ provider: z.string().refine(isKnownProvider, {
25
+ message: `provider must be one of: ${KNOWN_PROVIDERS.join(", ")}`,
26
+ }),
27
+ projectId: z.string(),
28
+ projectPath: z.string(),
29
+ projectIdentity: ProjectIdentitySchema.optional(),
30
+ agentName: z.string(),
31
+ title: z.string().nullable(),
32
+ modelLine: z.string().nullable(),
33
+ startedAt: z.string(),
34
+ endedAt: z.string().nullable(),
35
+ messageCount: z.number().int().nullable(),
36
+ fileCount: z.number().int().nullable(),
37
+ linesAdded: z.number().int().nullable(),
38
+ linesRemoved: z.number().int().nullable(),
39
+ filesChanged: z.array(z.string()).nullable(),
40
+ filesChangedApproximate: z.boolean(),
41
+ extensions: z.record(z.unknown()),
42
+ });
43
+ export const CanonicalPartSchema = z.object({
44
+ type: z.string(),
45
+ // text / reasoning / thinking blocks
46
+ text: z.string().optional(),
47
+ // tool_use / tool_result blocks
48
+ tool: z.string().optional(),
49
+ callId: z.string().optional(),
50
+ input: z.unknown().optional(),
51
+ output: z.string().optional(),
52
+ // image blocks (type === "image_url")
53
+ imageUrl: z.string().optional(),
54
+ mediaType: z.string().optional(),
55
+ });
56
+ export const CanonicalMessageSchema = z.object({
57
+ messageId: z.string(),
58
+ sessionId: z.string(),
59
+ role: z.enum(["user", "assistant"]),
60
+ senderName: z.string().optional(),
61
+ createdAt: z.string(),
62
+ parts: z.array(CanonicalPartSchema),
63
+ });
64
+ export const SessionWithMessagesSchema = CanonicalSessionSchema.extend({
65
+ messages: z.array(CanonicalMessageSchema).optional(),
66
+ });
67
+ export const SyncRequestSchema = z.object({
68
+ deviceId: z.string(),
69
+ collectorVersion: z.string(),
70
+ sentAt: z.string(),
71
+ sessions: z.array(SessionWithMessagesSchema),
72
+ });
73
+ export const SyncResponseSchema = z.object({
74
+ accepted: z.array(z.string()),
75
+ rejected: z.array(z.object({ sessionId: z.string(), reason: z.string() })),
76
+ });
77
+ export function validateSession(raw) {
78
+ return CanonicalSessionSchema.parse(raw);
79
+ }
80
+ //# sourceMappingURL=canonical.js.map
@@ -0,0 +1,18 @@
1
+ export interface CursorStore {
2
+ get(adapterName: string): string | null;
3
+ set(adapterName: string, value: string): void;
4
+ flush(): void;
5
+ }
6
+ export declare class FileCursorStore implements CursorStore {
7
+ private cache;
8
+ private readonly cursorsFile;
9
+ constructor(baseDir?: string);
10
+ get(adapterName: string): string | null;
11
+ set(adapterName: string, value: string): void;
12
+ flush(): void;
13
+ private getCache;
14
+ private loadFromDisk;
15
+ private saveToDisk;
16
+ }
17
+ export declare const cursorStore: CursorStore;
18
+ //# sourceMappingURL=cursor-store.d.ts.map
@@ -0,0 +1,50 @@
1
+ import { readFileSync, writeFileSync, mkdirSync, renameSync } from "node:fs";
2
+ import { join } from "node:path";
3
+ import { homedir } from "node:os";
4
+ export class FileCursorStore {
5
+ cache = null;
6
+ cursorsFile;
7
+ constructor(baseDir = join(homedir(), ".agentsofmine")) {
8
+ this.cursorsFile = join(baseDir, "cursors.json");
9
+ }
10
+ get(adapterName) {
11
+ return this.getCache()[adapterName] ?? null;
12
+ }
13
+ set(adapterName, value) {
14
+ const data = this.getCache();
15
+ data[adapterName] = value;
16
+ this.saveToDisk(data);
17
+ }
18
+ flush() {
19
+ if (this.cache !== null) {
20
+ this.saveToDisk(this.cache);
21
+ }
22
+ }
23
+ getCache() {
24
+ if (this.cache === null) {
25
+ this.cache = this.loadFromDisk();
26
+ }
27
+ return this.cache;
28
+ }
29
+ loadFromDisk() {
30
+ try {
31
+ const raw = readFileSync(this.cursorsFile, "utf8");
32
+ const parsed = JSON.parse(raw);
33
+ if (typeof parsed === "object" && parsed !== null && !Array.isArray(parsed)) {
34
+ return parsed;
35
+ }
36
+ }
37
+ catch {
38
+ // file missing or unparseable — start fresh
39
+ }
40
+ return {};
41
+ }
42
+ saveToDisk(data) {
43
+ mkdirSync(join(this.cursorsFile, ".."), { recursive: true });
44
+ const tmp = this.cursorsFile + ".tmp";
45
+ writeFileSync(tmp, JSON.stringify(data, null, 2), "utf8");
46
+ renameSync(tmp, this.cursorsFile);
47
+ }
48
+ }
49
+ export const cursorStore = new FileCursorStore();
50
+ //# sourceMappingURL=cursor-store.js.map
@@ -0,0 +1,12 @@
1
+ /**
2
+ * Best-effort debug logging for silent degradation paths.
3
+ *
4
+ * Writes to STDERR only — never stdout — because the collector runs as an MCP
5
+ * stdio server where stdout carries the JSON-RPC protocol stream; a stray
6
+ * stdout write would corrupt it. Output is gated behind the AOM_DEBUG env var
7
+ * so normal operation stays completely silent and the "never fail sync"
8
+ * degradation behaviour is preserved; setting AOM_DEBUG makes otherwise-swallowed
9
+ * errors (corrupt DB, permission failures, unparseable sessions) observable.
10
+ */
11
+ export declare function debugLog(context: string, err: unknown): void;
12
+ //# sourceMappingURL=debug-log.d.ts.map
@@ -0,0 +1,17 @@
1
+ /**
2
+ * Best-effort debug logging for silent degradation paths.
3
+ *
4
+ * Writes to STDERR only — never stdout — because the collector runs as an MCP
5
+ * stdio server where stdout carries the JSON-RPC protocol stream; a stray
6
+ * stdout write would corrupt it. Output is gated behind the AOM_DEBUG env var
7
+ * so normal operation stays completely silent and the "never fail sync"
8
+ * degradation behaviour is preserved; setting AOM_DEBUG makes otherwise-swallowed
9
+ * errors (corrupt DB, permission failures, unparseable sessions) observable.
10
+ */
11
+ export function debugLog(context, err) {
12
+ if (!process.env["AOM_DEBUG"])
13
+ return;
14
+ const message = err instanceof Error ? err.message : String(err);
15
+ console.error(`[aom] ${context}: ${message}`);
16
+ }
17
+ //# sourceMappingURL=debug-log.js.map
@@ -0,0 +1,23 @@
1
+ export interface GitIdentity {
2
+ canonical: string;
3
+ remoteUrl: string;
4
+ remoteName: string;
5
+ root: string;
6
+ branch: string | null;
7
+ headCommit: string | null;
8
+ }
9
+ type GitRunner = (cmd: string, args: string[]) => string | null;
10
+ /**
11
+ * Canonicalize a git remote to the form `git:<host>/<owner>/<repo>`.
12
+ * Host is lowercased; owner/repo casing is preserved. Credentials are
13
+ * always stripped. Returns null for empty or unparseable input. Never throws.
14
+ */
15
+ export declare function normalizeGitRemote(remoteUrl: string): string | null;
16
+ /**
17
+ * Discover the git identity for a local path using injectable git commands.
18
+ * Never throws — any git failure degrades to null. The returned remoteUrl is
19
+ * always credential-stripped so a token can never leak into stored data.
20
+ */
21
+ export declare function discoverGitIdentity(path: string, run?: GitRunner): GitIdentity | null;
22
+ export {};
23
+ //# sourceMappingURL=git-identity.d.ts.map
@@ -0,0 +1,127 @@
1
+ import { execFileSync } from "node:child_process";
2
+ const defaultRun = (cmd, args) => {
3
+ try {
4
+ const out = execFileSync(cmd, args, { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] });
5
+ const trimmed = out.trim();
6
+ return trimmed.length > 0 ? trimmed : null;
7
+ }
8
+ catch {
9
+ return null;
10
+ }
11
+ };
12
+ /**
13
+ * Strip userinfo (credentials) from a URL-like remote without throwing.
14
+ * Returns the input unchanged when there is no userinfo to strip.
15
+ */
16
+ function stripUserinfo(remoteUrl) {
17
+ // Matches scheme://userinfo@rest — drop the userinfo segment.
18
+ return remoteUrl.replace(/^([a-zA-Z][a-zA-Z0-9+.-]*:\/\/)[^/@]*@/, "$1");
19
+ }
20
+ /**
21
+ * Canonicalize a git remote to the form `git:<host>/<owner>/<repo>`.
22
+ * Host is lowercased; owner/repo casing is preserved. Credentials are
23
+ * always stripped. Returns null for empty or unparseable input. Never throws.
24
+ */
25
+ export function normalizeGitRemote(remoteUrl) {
26
+ if (typeof remoteUrl !== "string")
27
+ return null;
28
+ const raw = remoteUrl.trim();
29
+ if (raw.length === 0)
30
+ return null;
31
+ let host = null;
32
+ let path = null;
33
+ // SCP-like SSH syntax: git@github.com:Owner/Repo.git
34
+ const scpMatch = raw.match(/^(?:[^@/]+@)?([^/:]+):(.+)$/);
35
+ const hasScheme = /^[a-zA-Z][a-zA-Z0-9+.-]*:\/\//.test(raw);
36
+ if (!hasScheme && scpMatch) {
37
+ host = scpMatch[1] ?? null;
38
+ path = scpMatch[2] ?? null;
39
+ }
40
+ else {
41
+ let parsed;
42
+ try {
43
+ parsed = new URL(raw);
44
+ }
45
+ catch {
46
+ return null;
47
+ }
48
+ host = parsed.hostname;
49
+ path = parsed.pathname;
50
+ }
51
+ if (!host || !path)
52
+ return null;
53
+ // Normalize the path portion: strip leading slashes, trailing slashes, trailing .git
54
+ let normalizedPath = path.replace(/^\/+/, "").replace(/\/+$/, "");
55
+ normalizedPath = normalizedPath.replace(/\.git$/, "");
56
+ normalizedPath = normalizedPath.replace(/\/+$/, "");
57
+ if (normalizedPath.length === 0)
58
+ return null;
59
+ const normalizedHost = host.toLowerCase();
60
+ if (normalizedHost.length === 0)
61
+ return null;
62
+ return `git:${normalizedHost}/${normalizedPath}`;
63
+ }
64
+ /**
65
+ * Discover the git identity for a local path using injectable git commands.
66
+ * Never throws — any git failure degrades to null. The returned remoteUrl is
67
+ * always credential-stripped so a token can never leak into stored data.
68
+ */
69
+ export function discoverGitIdentity(path, run = defaultRun) {
70
+ if (typeof path !== "string" || path.length === 0)
71
+ return null;
72
+ const root = safeRun(run, "git", ["-C", path, "rev-parse", "--show-toplevel"]);
73
+ if (root === null)
74
+ return null;
75
+ const remote = resolveRemote(run, root);
76
+ if (remote === null)
77
+ return null;
78
+ const canonical = normalizeGitRemote(remote.url);
79
+ if (canonical === null)
80
+ return null;
81
+ const branch = safeRun(run, "git", ["-C", root, "rev-parse", "--abbrev-ref", "HEAD"]);
82
+ const headCommit = safeRun(run, "git", ["-C", root, "rev-parse", "HEAD"]);
83
+ return {
84
+ canonical,
85
+ remoteUrl: stripUserinfo(remote.url),
86
+ remoteName: remote.name,
87
+ root,
88
+ branch,
89
+ headCommit,
90
+ };
91
+ }
92
+ function resolveRemote(run, root) {
93
+ const originUrl = safeRun(run, "git", ["-C", root, "remote", "get-url", "origin"]);
94
+ if (originUrl !== null) {
95
+ return { name: "origin", url: originUrl };
96
+ }
97
+ const remoteList = safeRun(run, "git", ["-C", root, "remote"]);
98
+ if (remoteList === null)
99
+ return null;
100
+ const names = remoteList
101
+ .split("\n")
102
+ .map((n) => n.trim())
103
+ .filter((n) => n.length > 0)
104
+ .sort();
105
+ if (names.length === 0)
106
+ return null;
107
+ const firstName = names[0];
108
+ if (firstName === undefined)
109
+ return null;
110
+ const url = safeRun(run, "git", ["-C", root, "remote", "get-url", firstName]);
111
+ if (url === null)
112
+ return null;
113
+ return { name: firstName, url };
114
+ }
115
+ function safeRun(run, cmd, args) {
116
+ try {
117
+ const out = run(cmd, args);
118
+ if (out === null)
119
+ return null;
120
+ const trimmed = out.trim();
121
+ return trimmed.length > 0 ? trimmed : null;
122
+ }
123
+ catch {
124
+ return null;
125
+ }
126
+ }
127
+ //# sourceMappingURL=git-identity.js.map
@@ -0,0 +1,7 @@
1
+ import type { SyncResponse } from "./canonical.js";
2
+ export declare class HttpError extends Error {
3
+ readonly status: number;
4
+ constructor(status: number, message: string);
5
+ }
6
+ export declare function post(url: string, body: unknown, token: string): Promise<SyncResponse>;
7
+ //# sourceMappingURL=http-client.d.ts.map
@@ -0,0 +1,63 @@
1
+ const RETRYABLE_STATUS = [429, 500, 502, 503, 504];
2
+ const RETRY_DELAYS_MS = [100, 200, 400];
3
+ export class HttpError extends Error {
4
+ status;
5
+ constructor(status, message) {
6
+ super(message);
7
+ this.status = status;
8
+ this.name = "HttpError";
9
+ }
10
+ }
11
+ async function delay(ms) {
12
+ return new Promise((resolve) => setTimeout(resolve, ms));
13
+ }
14
+ export async function post(url, body, token) {
15
+ let lastError;
16
+ for (let attempt = 0; attempt <= RETRY_DELAYS_MS.length; attempt++) {
17
+ try {
18
+ const response = await fetch(url, {
19
+ method: "POST",
20
+ headers: {
21
+ "Content-Type": "application/json",
22
+ Authorization: `Bearer ${token}`,
23
+ },
24
+ body: JSON.stringify(body),
25
+ });
26
+ if (response.ok) {
27
+ const json = await response.json();
28
+ return json;
29
+ }
30
+ // 4xx — do not retry
31
+ if (response.status >= 400 && response.status < 500) {
32
+ throw new HttpError(response.status, `HTTP ${response.status}: ${response.statusText}`);
33
+ }
34
+ // 5xx — retry
35
+ if (RETRYABLE_STATUS.includes(response.status)) {
36
+ lastError = new HttpError(response.status, `HTTP ${response.status}: ${response.statusText}`);
37
+ if (attempt < RETRY_DELAYS_MS.length) {
38
+ await delay(RETRY_DELAYS_MS[attempt] ?? 0);
39
+ continue;
40
+ }
41
+ throw lastError;
42
+ }
43
+ throw new HttpError(response.status, `HTTP ${response.status}: ${response.statusText}`);
44
+ }
45
+ catch (err) {
46
+ if (err instanceof HttpError) {
47
+ // 4xx — propagate immediately, no retry
48
+ if (err.status >= 400 && err.status < 500)
49
+ throw err;
50
+ lastError = err;
51
+ }
52
+ else {
53
+ // Network error — retry
54
+ lastError = err instanceof Error ? err : new Error(String(err));
55
+ }
56
+ if (attempt < RETRY_DELAYS_MS.length) {
57
+ await delay(RETRY_DELAYS_MS[attempt] ?? 0);
58
+ }
59
+ }
60
+ }
61
+ throw lastError ?? new Error("Unknown error in http-client");
62
+ }
63
+ //# sourceMappingURL=http-client.js.map
@@ -0,0 +1,9 @@
1
+ export type LastSyncMap = Record<string, string>;
2
+ export declare function readLastSync(): LastSyncMap;
3
+ /**
4
+ * Stamp `source` with the current time in last-sync.json. Read-merge-write so
5
+ * concurrent writers (the daemon and a one-shot `aom sync`) don't clobber each
6
+ * other's entries.
7
+ */
8
+ export declare function recordLastSync(source: string): void;
9
+ //# sourceMappingURL=last-sync-store.d.ts.map
@@ -0,0 +1,31 @@
1
+ import { readFileSync, writeFileSync, mkdirSync, renameSync } from "node:fs";
2
+ import { homedir } from "node:os";
3
+ import { join } from "node:path";
4
+ const STATE_DIR = join(homedir(), ".agentsofmine");
5
+ const LAST_SYNC_FILE = join(STATE_DIR, "last-sync.json");
6
+ export function readLastSync() {
7
+ try {
8
+ const parsed = JSON.parse(readFileSync(LAST_SYNC_FILE, "utf8"));
9
+ if (typeof parsed === "object" && parsed !== null && !Array.isArray(parsed)) {
10
+ return parsed;
11
+ }
12
+ }
13
+ catch {
14
+ // missing or unparseable — treat as empty
15
+ }
16
+ return {};
17
+ }
18
+ /**
19
+ * Stamp `source` with the current time in last-sync.json. Read-merge-write so
20
+ * concurrent writers (the daemon and a one-shot `aom sync`) don't clobber each
21
+ * other's entries.
22
+ */
23
+ export function recordLastSync(source) {
24
+ mkdirSync(STATE_DIR, { recursive: true });
25
+ const data = readLastSync();
26
+ data[source] = new Date().toISOString();
27
+ const tmp = LAST_SYNC_FILE + ".tmp";
28
+ writeFileSync(tmp, JSON.stringify(data, null, 2), "utf8");
29
+ renameSync(tmp, LAST_SYNC_FILE);
30
+ }
31
+ //# sourceMappingURL=last-sync-store.js.map
@@ -0,0 +1,10 @@
1
+ import type { CanonicalMessage } from "./canonical.js";
2
+ /** Maximum messages kept per session before truncation. */
3
+ export declare const MAX_MESSAGES_PER_SESSION = 150;
4
+ /**
5
+ * Cap a session's messages: keep the first message plus the most recent
6
+ * (MAX_MESSAGES_PER_SESSION - 1) when the count exceeds the limit, so the
7
+ * opening context and the latest activity are both preserved.
8
+ */
9
+ export declare function truncateMessages(messages: CanonicalMessage[]): CanonicalMessage[];
10
+ //# sourceMappingURL=message-truncation.d.ts.map
@@ -0,0 +1,13 @@
1
+ /** Maximum messages kept per session before truncation. */
2
+ export const MAX_MESSAGES_PER_SESSION = 150;
3
+ /**
4
+ * Cap a session's messages: keep the first message plus the most recent
5
+ * (MAX_MESSAGES_PER_SESSION - 1) when the count exceeds the limit, so the
6
+ * opening context and the latest activity are both preserved.
7
+ */
8
+ export function truncateMessages(messages) {
9
+ if (messages.length <= MAX_MESSAGES_PER_SESSION)
10
+ return messages;
11
+ return [...messages.slice(0, 1), ...messages.slice(-(MAX_MESSAGES_PER_SESSION - 1))];
12
+ }
13
+ //# sourceMappingURL=message-truncation.js.map
@@ -0,0 +1,23 @@
1
+ /**
2
+ * Shared sync orchestration — the single place that wires config, adapters,
3
+ * cursor store, and the core `runSync()` engine together.
4
+ *
5
+ * Both the manual `aom sync` command and the background daemon
6
+ * (file watcher + MCP server) call this, so there is exactly one code path
7
+ * that actually uploads sessions.
8
+ */
9
+ import { type SyncSummary } from "./sync-engine.js";
10
+ export declare class NotPairedError extends Error {
11
+ constructor();
12
+ }
13
+ /**
14
+ * Run a single sync pass across all provider adapters.
15
+ *
16
+ * Resolves config from the environment / keychain, builds the three adapters,
17
+ * and delegates to the core engine. The cursor store is flushed before
18
+ * returning so progress is durable even if the process is killed afterwards.
19
+ *
20
+ * @throws {NotPairedError} when no device token is available.
21
+ */
22
+ export declare function performSync(): Promise<SyncSummary>;
23
+ //# sourceMappingURL=perform-sync.d.ts.map
@@ -0,0 +1,57 @@
1
+ /**
2
+ * Shared sync orchestration — the single place that wires config, adapters,
3
+ * cursor store, and the core `runSync()` engine together.
4
+ *
5
+ * Both the manual `aom sync` command and the background daemon
6
+ * (file watcher + MCP server) call this, so there is exactly one code path
7
+ * that actually uploads sessions.
8
+ */
9
+ import { loadConfig } from "../config.js";
10
+ import { runSync } from "./sync-engine.js";
11
+ import { FileCursorStore } from "./cursor-store.js";
12
+ import { OpenCodeAdapter } from "../adapters/opencode/index.js";
13
+ import { ClaudeCodeAdapter } from "../adapters/claude-code/index.js";
14
+ import { CodexAdapter } from "../adapters/codex/index.js";
15
+ import { PiAdapter } from "../adapters/pi/index.js";
16
+ import { setLastSyncResult } from "../mcp-tools/status.js";
17
+ import { recordLastSync } from "./last-sync-store.js";
18
+ export class NotPairedError extends Error {
19
+ constructor() {
20
+ super("Device token missing — run `aom pair`.");
21
+ this.name = "NotPairedError";
22
+ }
23
+ }
24
+ /**
25
+ * Run a single sync pass across all provider adapters.
26
+ *
27
+ * Resolves config from the environment / keychain, builds the three adapters,
28
+ * and delegates to the core engine. The cursor store is flushed before
29
+ * returning so progress is durable even if the process is killed afterwards.
30
+ *
31
+ * @throws {NotPairedError} when no device token is available.
32
+ */
33
+ export async function performSync() {
34
+ const config = await loadConfig();
35
+ if (!config.deviceToken) {
36
+ throw new NotPairedError();
37
+ }
38
+ const syncConfig = {
39
+ syncUrl: config.syncUrl,
40
+ deviceId: config.deviceId,
41
+ deviceToken: config.deviceToken,
42
+ collectorVersion: config.collectorVersion,
43
+ };
44
+ const adapters = [
45
+ new OpenCodeAdapter(config.opencodeDbPath),
46
+ new ClaudeCodeAdapter(config.claudeProjectsGlob),
47
+ new CodexAdapter(config.codexSessionsDir),
48
+ new PiAdapter(config.piSessionsDir),
49
+ ];
50
+ const cursorStore = new FileCursorStore();
51
+ const summary = await runSync(adapters, syncConfig, cursorStore);
52
+ cursorStore.flush();
53
+ setLastSyncResult(summary);
54
+ recordLastSync("sync");
55
+ return summary;
56
+ }
57
+ //# sourceMappingURL=perform-sync.js.map
@@ -0,0 +1,40 @@
1
+ type GitRunner = (cmd: string, args: string[]) => string | null;
2
+ export interface ProjectIdentity {
3
+ kind: "git" | "path-legacy";
4
+ canonical: string;
5
+ displayName: string;
6
+ git?: {
7
+ root: string;
8
+ remoteName: string;
9
+ remoteUrl: string;
10
+ branch: string | null;
11
+ headCommit: string | null;
12
+ };
13
+ local: {
14
+ path: string;
15
+ basename: string;
16
+ };
17
+ }
18
+ /**
19
+ * The historical path-derived project id: first 16 hex chars of the SHA-256 of
20
+ * the path. Shared by all adapters so the legacy `projectId` stays stable.
21
+ */
22
+ export declare function legacyProjectId(path: string): string;
23
+ /**
24
+ * Resolve a logical project identity for a local path. Tries Git remote
25
+ * identity first; falls back to a path-legacy identity when no Git remote is
26
+ * available. Never throws — failures degrade to path-legacy.
27
+ */
28
+ export declare function resolveProjectIdentity(projectPath: string, run?: GitRunner): ProjectIdentity;
29
+ /**
30
+ * The project-scoped fields every adapter attaches to a CanonicalSession.
31
+ * `projectId` stays the legacy path hash; `projectIdentity` is the richer
32
+ * resolution. Centralizes the pairing so adapters do not repeat it.
33
+ */
34
+ export declare function projectFields(projectPath: string): {
35
+ projectId: string;
36
+ projectPath: string;
37
+ projectIdentity: ProjectIdentity;
38
+ };
39
+ export {};
40
+ //# sourceMappingURL=project-identity.d.ts.map
@@ -0,0 +1,67 @@
1
+ import { createHash } from "node:crypto";
2
+ import { basename } from "node:path";
3
+ import { discoverGitIdentity } from "./git-identity.js";
4
+ /**
5
+ * The historical path-derived project id: first 16 hex chars of the SHA-256 of
6
+ * the path. Shared by all adapters so the legacy `projectId` stays stable.
7
+ */
8
+ export function legacyProjectId(path) {
9
+ return createHash("sha256").update(path).digest("hex").slice(0, 16);
10
+ }
11
+ /**
12
+ * Resolve a logical project identity for a local path. Tries Git remote
13
+ * identity first; falls back to a path-legacy identity when no Git remote is
14
+ * available. Never throws — failures degrade to path-legacy.
15
+ */
16
+ export function resolveProjectIdentity(projectPath, run) {
17
+ const local = { path: projectPath, basename: basename(projectPath) };
18
+ const git = discoverGitIdentity(projectPath, run);
19
+ if (git !== null) {
20
+ return {
21
+ kind: "git",
22
+ canonical: git.canonical,
23
+ displayName: repoNameFromCanonical(git.canonical) ?? displayNameForPath(projectPath, local.basename),
24
+ git: {
25
+ root: git.root,
26
+ remoteName: git.remoteName,
27
+ remoteUrl: git.remoteUrl,
28
+ branch: git.branch,
29
+ headCommit: git.headCommit,
30
+ },
31
+ local,
32
+ };
33
+ }
34
+ return {
35
+ kind: "path-legacy",
36
+ canonical: `path:${legacyProjectId(projectPath)}`,
37
+ displayName: displayNameForPath(projectPath, local.basename),
38
+ local,
39
+ };
40
+ }
41
+ /**
42
+ * basename("/") is "" — an empty name surfaces as a raw hash in the UI.
43
+ * OpenCode records `/` for sessions run outside any project, so label it "Global".
44
+ */
45
+ function displayNameForPath(projectPath, base) {
46
+ if (base.length > 0)
47
+ return base;
48
+ return projectPath === "/" ? "Global" : projectPath;
49
+ }
50
+ /**
51
+ * The project-scoped fields every adapter attaches to a CanonicalSession.
52
+ * `projectId` stays the legacy path hash; `projectIdentity` is the richer
53
+ * resolution. Centralizes the pairing so adapters do not repeat it.
54
+ */
55
+ export function projectFields(projectPath) {
56
+ return {
57
+ projectId: legacyProjectId(projectPath),
58
+ projectPath,
59
+ projectIdentity: resolveProjectIdentity(projectPath),
60
+ };
61
+ }
62
+ function repoNameFromCanonical(canonical) {
63
+ const segments = canonical.split("/");
64
+ const last = segments[segments.length - 1];
65
+ return last !== undefined && last.length > 0 ? last : null;
66
+ }
67
+ //# sourceMappingURL=project-identity.js.map