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,34 @@
1
+ /**
2
+ * ConfigRepository — all local config I/O in one place.
3
+ *
4
+ * Knows about:
5
+ * - ~/.agentsofmine/device-id (plain text, UUID)
6
+ * - ~/.agentsofmine/config.json (JSON with deviceId, deviceToken, pairedAt)
7
+ *
8
+ * Does NOT touch env vars or the OS keychain — callers (loadConfig, PairingService)
9
+ * are responsible for that.
10
+ */
11
+ export interface PairingConfig {
12
+ deviceId: string;
13
+ deviceToken: string;
14
+ pairedAt: string;
15
+ }
16
+ export declare class ConfigRepository {
17
+ private readonly configDir;
18
+ private readonly configFile;
19
+ private readonly deviceIdFile;
20
+ constructor(baseDir?: string);
21
+ readDeviceId(): string | null;
22
+ writeDeviceId(id: string): void;
23
+ readPairingConfig(): PairingConfig | null;
24
+ readDeviceToken(): string | null;
25
+ writePairingConfig(config: PairingConfig): void;
26
+ clearPairingConfig(): void;
27
+ /**
28
+ * Delete config.json + device-id from disk (idempotent).
29
+ * Does NOT touch the OS keychain — the caller owns the device token.
30
+ */
31
+ clearLocalState(): void;
32
+ private readRawConfigFile;
33
+ }
34
+ //# sourceMappingURL=config-repository.d.ts.map
@@ -0,0 +1,102 @@
1
+ /**
2
+ * ConfigRepository — all local config I/O in one place.
3
+ *
4
+ * Knows about:
5
+ * - ~/.agentsofmine/device-id (plain text, UUID)
6
+ * - ~/.agentsofmine/config.json (JSON with deviceId, deviceToken, pairedAt)
7
+ *
8
+ * Does NOT touch env vars or the OS keychain — callers (loadConfig, PairingService)
9
+ * are responsible for that.
10
+ */
11
+ import { existsSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync, } from "node:fs";
12
+ import { homedir } from "node:os";
13
+ import { join } from "node:path";
14
+ export class ConfigRepository {
15
+ configDir;
16
+ configFile;
17
+ deviceIdFile;
18
+ constructor(baseDir = join(homedir(), ".agentsofmine")) {
19
+ this.configDir = baseDir;
20
+ this.configFile = join(baseDir, "config.json");
21
+ this.deviceIdFile = join(baseDir, "device-id");
22
+ }
23
+ readDeviceId() {
24
+ try {
25
+ if (existsSync(this.deviceIdFile)) {
26
+ const id = readFileSync(this.deviceIdFile, "utf8").trim();
27
+ return id.length > 0 ? id : null;
28
+ }
29
+ }
30
+ catch {
31
+ // unreadable — treat as absent
32
+ }
33
+ return null;
34
+ }
35
+ writeDeviceId(id) {
36
+ mkdirSync(this.configDir, { recursive: true });
37
+ writeFileSync(this.deviceIdFile, id, { encoding: "utf8", mode: 0o600 });
38
+ }
39
+ readPairingConfig() {
40
+ const raw = this.readRawConfigFile();
41
+ if (typeof raw.deviceId === "string" &&
42
+ typeof raw.deviceToken === "string" &&
43
+ typeof raw.pairedAt === "string") {
44
+ return {
45
+ deviceId: raw.deviceId,
46
+ deviceToken: raw.deviceToken,
47
+ pairedAt: raw.pairedAt,
48
+ };
49
+ }
50
+ return null;
51
+ }
52
+ readDeviceToken() {
53
+ const raw = this.readRawConfigFile();
54
+ return typeof raw.deviceToken === "string" && raw.deviceToken.length > 0
55
+ ? raw.deviceToken
56
+ : null;
57
+ }
58
+ writePairingConfig(config) {
59
+ mkdirSync(this.configDir, { recursive: true });
60
+ const tmp = this.configFile + ".tmp";
61
+ writeFileSync(tmp, JSON.stringify(config, null, 2), { encoding: "utf8", mode: 0o600 });
62
+ renameSync(tmp, this.configFile);
63
+ }
64
+ clearPairingConfig() {
65
+ try {
66
+ mkdirSync(this.configDir, { recursive: true });
67
+ writeFileSync(this.configFile, "{}", "utf8");
68
+ }
69
+ catch {
70
+ // ignore — file already gone or unwritable
71
+ }
72
+ }
73
+ /**
74
+ * Delete config.json + device-id from disk (idempotent).
75
+ * Does NOT touch the OS keychain — the caller owns the device token.
76
+ */
77
+ clearLocalState() {
78
+ for (const file of [this.configFile, this.deviceIdFile]) {
79
+ try {
80
+ if (existsSync(file))
81
+ rmSync(file);
82
+ }
83
+ catch {
84
+ // ignore — already gone or unwritable
85
+ }
86
+ }
87
+ }
88
+ readRawConfigFile() {
89
+ try {
90
+ const content = readFileSync(this.configFile, "utf8");
91
+ const parsed = JSON.parse(content);
92
+ if (typeof parsed === "object" && parsed !== null && !Array.isArray(parsed)) {
93
+ return parsed;
94
+ }
95
+ }
96
+ catch {
97
+ // missing or malformed — return empty
98
+ }
99
+ return {};
100
+ }
101
+ }
102
+ //# sourceMappingURL=config-repository.js.map
@@ -0,0 +1,31 @@
1
+ /**
2
+ * OS keychain abstraction for the AgentsOfMine device token.
3
+ *
4
+ * Wraps `keytar` (macOS Keychain / Windows Credential Manager / Linux
5
+ * libsecret) with a thin typed interface so callers never import keytar
6
+ * directly. All methods throw `KeychainError` on failure.
7
+ */
8
+ export declare class KeychainError extends Error {
9
+ readonly cause?: unknown | undefined;
10
+ constructor(message: string, cause?: unknown | undefined);
11
+ }
12
+ /**
13
+ * Store the device token in the OS keychain.
14
+ * Overwrites any existing value for the same service+account.
15
+ */
16
+ export declare function storeDeviceToken(token: string): Promise<void>;
17
+ /**
18
+ * Retrieve the device token from the OS keychain.
19
+ * Returns `null` if not paired yet.
20
+ */
21
+ export declare function getDeviceToken(): Promise<string | null>;
22
+ /**
23
+ * Delete the device token from the OS keychain.
24
+ * Returns `true` if a token was found and deleted, `false` if not found.
25
+ */
26
+ export declare function deleteDeviceToken(): Promise<boolean>;
27
+ /**
28
+ * Returns `true` if a device token is stored (machine is paired).
29
+ */
30
+ export declare function isPaired(): Promise<boolean>;
31
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1,62 @@
1
+ /**
2
+ * OS keychain abstraction for the AgentsOfMine device token.
3
+ *
4
+ * Wraps `keytar` (macOS Keychain / Windows Credential Manager / Linux
5
+ * libsecret) with a thin typed interface so callers never import keytar
6
+ * directly. All methods throw `KeychainError` on failure.
7
+ */
8
+ import keytar from "keytar";
9
+ const SERVICE = "agentsofmine-collector";
10
+ const ACCOUNT = "device-token";
11
+ export class KeychainError extends Error {
12
+ cause;
13
+ constructor(message, cause) {
14
+ super(message);
15
+ this.cause = cause;
16
+ this.name = "KeychainError";
17
+ }
18
+ }
19
+ /**
20
+ * Store the device token in the OS keychain.
21
+ * Overwrites any existing value for the same service+account.
22
+ */
23
+ export async function storeDeviceToken(token) {
24
+ try {
25
+ await keytar.setPassword(SERVICE, ACCOUNT, token);
26
+ }
27
+ catch (err) {
28
+ throw new KeychainError("Failed to store device token in keychain", err);
29
+ }
30
+ }
31
+ /**
32
+ * Retrieve the device token from the OS keychain.
33
+ * Returns `null` if not paired yet.
34
+ */
35
+ export async function getDeviceToken() {
36
+ try {
37
+ return await keytar.getPassword(SERVICE, ACCOUNT);
38
+ }
39
+ catch (err) {
40
+ throw new KeychainError("Failed to read device token from keychain", err);
41
+ }
42
+ }
43
+ /**
44
+ * Delete the device token from the OS keychain.
45
+ * Returns `true` if a token was found and deleted, `false` if not found.
46
+ */
47
+ export async function deleteDeviceToken() {
48
+ try {
49
+ return await keytar.deletePassword(SERVICE, ACCOUNT);
50
+ }
51
+ catch (err) {
52
+ throw new KeychainError("Failed to delete device token from keychain", err);
53
+ }
54
+ }
55
+ /**
56
+ * Returns `true` if a device token is stored (machine is paired).
57
+ */
58
+ export async function isPaired() {
59
+ const token = await getDeviceToken();
60
+ return token !== null;
61
+ }
62
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1,39 @@
1
+ /**
2
+ * JSON-RPC 2.0 helpers for the MCP stdio transport.
3
+ *
4
+ * Keeps protocol framing separate from handler dispatch logic.
5
+ */
6
+ export interface JsonRpcRequest {
7
+ jsonrpc: "2.0";
8
+ id?: string | number | null;
9
+ method: string;
10
+ params?: unknown;
11
+ }
12
+ export interface JsonRpcResponse {
13
+ jsonrpc: "2.0";
14
+ id?: string | number | null;
15
+ result?: unknown;
16
+ error?: JsonRpcError;
17
+ }
18
+ export interface JsonRpcError {
19
+ code: number;
20
+ message: string;
21
+ data?: unknown;
22
+ }
23
+ export declare const RPC_ERRORS: {
24
+ readonly PARSE_ERROR: -32700;
25
+ readonly INVALID_REQUEST: -32600;
26
+ readonly METHOD_NOT_FOUND: -32601;
27
+ readonly INVALID_PARAMS: -32602;
28
+ readonly INTERNAL_ERROR: -32603;
29
+ };
30
+ /**
31
+ * Parse a raw JSON string into a JsonRpcRequest.
32
+ * Returns null (and logs) if the line is not valid JSON-RPC.
33
+ */
34
+ export declare function parseRequest(line: string): JsonRpcRequest | null;
35
+ /** Write a successful JSON-RPC response to stdout. */
36
+ export declare function writeResponse(id: string | number | null | undefined, result: unknown): void;
37
+ /** Write a JSON-RPC error response to stdout. */
38
+ export declare function writeError(id: string | number | null | undefined, code: number, message: string): void;
39
+ //# sourceMappingURL=json-rpc.d.ts.map
@@ -0,0 +1,46 @@
1
+ /**
2
+ * JSON-RPC 2.0 helpers for the MCP stdio transport.
3
+ *
4
+ * Keeps protocol framing separate from handler dispatch logic.
5
+ */
6
+ // Standard JSON-RPC error codes
7
+ export const RPC_ERRORS = {
8
+ PARSE_ERROR: -32700,
9
+ INVALID_REQUEST: -32600,
10
+ METHOD_NOT_FOUND: -32601,
11
+ INVALID_PARAMS: -32602,
12
+ INTERNAL_ERROR: -32603,
13
+ };
14
+ /**
15
+ * Parse a raw JSON string into a JsonRpcRequest.
16
+ * Returns null (and logs) if the line is not valid JSON-RPC.
17
+ */
18
+ export function parseRequest(line) {
19
+ let msg;
20
+ try {
21
+ msg = JSON.parse(line);
22
+ }
23
+ catch {
24
+ return null;
25
+ }
26
+ if (typeof msg["method"] !== "string")
27
+ return null;
28
+ return {
29
+ jsonrpc: "2.0",
30
+ id: msg["id"],
31
+ method: msg["method"],
32
+ params: msg["params"],
33
+ };
34
+ }
35
+ /** Write a successful JSON-RPC response to stdout. */
36
+ export function writeResponse(id, result) {
37
+ writeRaw({ jsonrpc: "2.0", id, result });
38
+ }
39
+ /** Write a JSON-RPC error response to stdout. */
40
+ export function writeError(id, code, message) {
41
+ writeRaw({ jsonrpc: "2.0", id, error: { code, message } });
42
+ }
43
+ function writeRaw(msg) {
44
+ process.stdout.write(JSON.stringify(msg) + "\n");
45
+ }
46
+ //# sourceMappingURL=json-rpc.js.map
@@ -0,0 +1,33 @@
1
+ /**
2
+ * MCP server entrypoint — stdio transport.
3
+ *
4
+ * Exposes a `session_event` tool so MCP-aware agents (opencode, claude-code)
5
+ * can push session events directly without file polling.
6
+ *
7
+ * This is a minimal stub for Phase 1. The full event schema is defined in
8
+ * schemas/session-event.json (to be finalised alongside POST /sync).
9
+ *
10
+ * Transport: stdio (agents connect via their mcp config block).
11
+ *
12
+ * Example opencode mcp config:
13
+ * [mcp.agentsofmine]
14
+ * command = "aom"
15
+ * args = ["start"]
16
+ */
17
+ import { DaemonState } from "../daemon/state.js";
18
+ export interface SessionEventParams {
19
+ sessionId: string;
20
+ agentType: "opencode" | "claude-code" | "codex" | (string & {});
21
+ eventType: "session_start" | "session_end" | "message" | "tool_call" | (string & {});
22
+ payload: Record<string, unknown>;
23
+ timestamp?: string;
24
+ }
25
+ /**
26
+ * Start the MCP server on stdio.
27
+ *
28
+ * NOTE: Full MCP SDK integration (e.g. @modelcontextprotocol/sdk) will replace
29
+ * this stub once the session-event schema is finalised with the backend team.
30
+ * For now we read JSON-RPC lines from stdin and ack them so agents don't block.
31
+ */
32
+ export declare function startMcpServer(state: DaemonState): Promise<void>;
33
+ //# sourceMappingURL=server.d.ts.map
@@ -0,0 +1,110 @@
1
+ /**
2
+ * MCP server entrypoint — stdio transport.
3
+ *
4
+ * Exposes a `session_event` tool so MCP-aware agents (opencode, claude-code)
5
+ * can push session events directly without file polling.
6
+ *
7
+ * This is a minimal stub for Phase 1. The full event schema is defined in
8
+ * schemas/session-event.json (to be finalised alongside POST /sync).
9
+ *
10
+ * Transport: stdio (agents connect via their mcp config block).
11
+ *
12
+ * Example opencode mcp config:
13
+ * [mcp.agentsofmine]
14
+ * command = "aom"
15
+ * args = ["start"]
16
+ */
17
+ import { parseRequest, writeResponse, writeError, RPC_ERRORS } from "./json-rpc.js";
18
+ /**
19
+ * Start the MCP server on stdio.
20
+ *
21
+ * NOTE: Full MCP SDK integration (e.g. @modelcontextprotocol/sdk) will replace
22
+ * this stub once the session-event schema is finalised with the backend team.
23
+ * For now we read JSON-RPC lines from stdin and ack them so agents don't block.
24
+ */
25
+ export async function startMcpServer(state) {
26
+ process.stdin.setEncoding("utf8");
27
+ let buffer = "";
28
+ process.stdin.on("data", (chunk) => {
29
+ buffer += chunk;
30
+ const lines = buffer.split("\n");
31
+ // Keep the last (possibly incomplete) line in the buffer
32
+ buffer = lines.pop() ?? "";
33
+ for (const line of lines) {
34
+ const trimmed = line.trim();
35
+ if (!trimmed)
36
+ continue;
37
+ dispatch(trimmed, state);
38
+ }
39
+ });
40
+ // stdio MCP is fire-and-forget from the server side — no explicit listen() needed
41
+ }
42
+ function dispatch(line, state) {
43
+ const req = parseRequest(line);
44
+ if (!req) {
45
+ state.log(`MCP: invalid JSON-RPC line: ${line.slice(0, 80)}`);
46
+ return;
47
+ }
48
+ const { id, method, params } = req;
49
+ switch (method) {
50
+ case "initialize":
51
+ handleInitialize(id);
52
+ return;
53
+ case "tools/list":
54
+ handleToolsList(id);
55
+ return;
56
+ case "tools/call":
57
+ handleToolsCall(id, params, state);
58
+ return;
59
+ default:
60
+ // Silently ack notifications (no id) and return method-not-found for requests
61
+ if (id !== undefined && id !== null) {
62
+ writeError(id, RPC_ERRORS.METHOD_NOT_FOUND, `Method not found: ${method}`);
63
+ }
64
+ }
65
+ }
66
+ function handleInitialize(id) {
67
+ writeResponse(id, {
68
+ protocolVersion: "2024-11-05",
69
+ capabilities: { tools: {} },
70
+ serverInfo: { name: "agentsofmine-collector", version: "0.1.0" },
71
+ });
72
+ }
73
+ function handleToolsList(id) {
74
+ writeResponse(id, {
75
+ tools: [
76
+ {
77
+ name: "session_event",
78
+ description: "Push a session event to AgentsOfMine. Called automatically by supported agents.",
79
+ inputSchema: {
80
+ type: "object",
81
+ required: ["sessionId", "agentType", "eventType", "payload"],
82
+ properties: {
83
+ sessionId: { type: "string" },
84
+ agentType: { type: "string" },
85
+ eventType: { type: "string" },
86
+ payload: { type: "object" },
87
+ timestamp: { type: "string", format: "date-time" },
88
+ },
89
+ },
90
+ },
91
+ ],
92
+ });
93
+ }
94
+ function handleToolsCall(id, params, state) {
95
+ const toolName = params?.["name"];
96
+ const args = params?.["arguments"];
97
+ if (toolName === "session_event" && args) {
98
+ state.log(`MCP event: ${args.agentType} / ${args.eventType} / session=${args.sessionId}`);
99
+ if (state.syncRunner) {
100
+ state.syncRunner.trigger(`mcp session_event: ${args.agentType}/${args.eventType}`);
101
+ }
102
+ else {
103
+ state.markSynced("mcp");
104
+ }
105
+ writeResponse(id, { content: [{ type: "text", text: "ok" }] });
106
+ return;
107
+ }
108
+ writeError(id, RPC_ERRORS.METHOD_NOT_FOUND, `Unknown tool: ${String(toolName)}`);
109
+ }
110
+ //# sourceMappingURL=server.js.map
@@ -0,0 +1,17 @@
1
+ import type { SyncSummary } from "../core/sync-engine.js";
2
+ export interface SyncStatus {
3
+ lastSyncAt: string | null;
4
+ synced: number;
5
+ failed: number;
6
+ errors: string[];
7
+ }
8
+ export declare class SyncStatusStore {
9
+ private lastSummary;
10
+ private lastSyncAt;
11
+ record(summary: SyncSummary): void;
12
+ get(): SyncStatus;
13
+ }
14
+ export declare const syncStatusStore: SyncStatusStore;
15
+ export declare function setLastSyncResult(summary: SyncSummary): void;
16
+ export declare function getStatusPayload(): SyncStatus;
17
+ //# sourceMappingURL=status.d.ts.map
@@ -0,0 +1,24 @@
1
+ export class SyncStatusStore {
2
+ lastSummary = null;
3
+ lastSyncAt = null;
4
+ record(summary) {
5
+ this.lastSummary = summary;
6
+ this.lastSyncAt = new Date().toISOString();
7
+ }
8
+ get() {
9
+ return {
10
+ lastSyncAt: this.lastSyncAt,
11
+ synced: this.lastSummary?.synced ?? 0,
12
+ failed: this.lastSummary?.failed ?? 0,
13
+ errors: this.lastSummary?.errors ?? [],
14
+ };
15
+ }
16
+ }
17
+ export const syncStatusStore = new SyncStatusStore();
18
+ export function setLastSyncResult(summary) {
19
+ syncStatusStore.record(summary);
20
+ }
21
+ export function getStatusPayload() {
22
+ return syncStatusStore.get();
23
+ }
24
+ //# sourceMappingURL=status.js.map
@@ -0,0 +1,9 @@
1
+ import type { Adapter } from "../adapters/adapter.js";
2
+ import type { SyncConfig } from "../core/sync-engine.js";
3
+ import type { CursorStore } from "../core/cursor-store.js";
4
+ export declare function syncNow(adapters: Adapter[], config: SyncConfig, cursorStore: CursorStore): Promise<{
5
+ synced: number;
6
+ failed: number;
7
+ errors: string[];
8
+ }>;
9
+ //# sourceMappingURL=sync-now.d.ts.map
@@ -0,0 +1,8 @@
1
+ import { runSync } from "../core/sync-engine.js";
2
+ import { setLastSyncResult } from "./status.js";
3
+ export async function syncNow(adapters, config, cursorStore) {
4
+ const summary = await runSync(adapters, config, cursorStore);
5
+ setLastSyncResult(summary);
6
+ return summary;
7
+ }
8
+ //# sourceMappingURL=sync-now.js.map
@@ -0,0 +1,58 @@
1
+ /**
2
+ * PairingService — orchestrates the full device-pairing flow.
3
+ *
4
+ * Responsibilities:
5
+ * 1. Persist/read the device ID via ConfigRepository.
6
+ * 2. Call PairingClient.initPairing() and PairingClient.pollStatus().
7
+ * 3. Store the received device token via the keychain module.
8
+ * 4. Persist the full PairingConfig on success.
9
+ *
10
+ * Terminal rendering (QR code, spinner, status messages) intentionally stays
11
+ * in src/cli/pair.ts — this class only handles orchestration and I/O.
12
+ */
13
+ import { PairingClient } from "../api/pairing-client.js";
14
+ import type { ConfigRepository } from "../infrastructure/config-repository.js";
15
+ export interface PairFlowOptions {
16
+ /**
17
+ * If true, clear existing pairing config before starting.
18
+ * Caller (cli/pair.ts) gates on `--force` / `--reset`.
19
+ */
20
+ reset?: boolean;
21
+ /**
22
+ * Called after init succeeds with the pairing code + QR URL + expiry.
23
+ * Use this to render the terminal UI.
24
+ */
25
+ onInitSuccess: (params: {
26
+ pairingCode: string;
27
+ qrUrl: string;
28
+ expiresInMinutes: number;
29
+ pollIntervalMs: number;
30
+ }) => void;
31
+ /**
32
+ * Called on each poll tick (before the HTTP request).
33
+ * Use this to animate a spinner or progress indicator.
34
+ */
35
+ onPollTick?: (tick: number) => void;
36
+ }
37
+ export type PairFlowResult = {
38
+ status: "approved";
39
+ deviceId: string;
40
+ } | {
41
+ status: "denied";
42
+ } | {
43
+ status: "expired";
44
+ };
45
+ export declare class PairingService {
46
+ private readonly client;
47
+ private readonly configRepo;
48
+ constructor(client: PairingClient, configRepo: ConfigRepository);
49
+ /**
50
+ * Run the full pairing flow from init → poll → store.
51
+ *
52
+ * Does NOT call process.exit() — throws or returns PairFlowResult.
53
+ * The caller (cli/pair.ts) decides how to surface errors to the user.
54
+ */
55
+ runPairFlow(opts: PairFlowOptions): Promise<PairFlowResult>;
56
+ private getOrCreateDeviceId;
57
+ }
58
+ //# sourceMappingURL=pairing-service.d.ts.map
@@ -0,0 +1,102 @@
1
+ /**
2
+ * PairingService — orchestrates the full device-pairing flow.
3
+ *
4
+ * Responsibilities:
5
+ * 1. Persist/read the device ID via ConfigRepository.
6
+ * 2. Call PairingClient.initPairing() and PairingClient.pollStatus().
7
+ * 3. Store the received device token via the keychain module.
8
+ * 4. Persist the full PairingConfig on success.
9
+ *
10
+ * Terminal rendering (QR code, spinner, status messages) intentionally stays
11
+ * in src/cli/pair.ts — this class only handles orchestration and I/O.
12
+ */
13
+ import { randomUUID } from "node:crypto";
14
+ import { PairingApiError } from "../api/pairing-client.js";
15
+ import { storeDeviceToken } from "../keychain/index.js";
16
+ export class PairingService {
17
+ client;
18
+ configRepo;
19
+ constructor(client, configRepo) {
20
+ this.client = client;
21
+ this.configRepo = configRepo;
22
+ }
23
+ /**
24
+ * Run the full pairing flow from init → poll → store.
25
+ *
26
+ * Does NOT call process.exit() — throws or returns PairFlowResult.
27
+ * The caller (cli/pair.ts) decides how to surface errors to the user.
28
+ */
29
+ async runPairFlow(opts) {
30
+ if (opts.reset) {
31
+ this.configRepo.clearPairingConfig();
32
+ }
33
+ const deviceId = this.getOrCreateDeviceId();
34
+ // Step 1 — POST /pair/init
35
+ const initResp = await this.client.initPairing(deviceId);
36
+ const expiresInMinutes = Math.max(1, Math.round((initResp.expiresAt - Date.now() / 1000) / 60));
37
+ const pollIntervalMs = initResp.pollInterval * 1000;
38
+ opts.onInitSuccess({
39
+ pairingCode: initResp.pairingCode,
40
+ qrUrl: initResp.qrUrl,
41
+ expiresInMinutes,
42
+ pollIntervalMs,
43
+ });
44
+ // Step 2 — Poll until resolved
45
+ let tick = 0;
46
+ while (true) {
47
+ await sleep(pollIntervalMs);
48
+ opts.onPollTick?.(tick++);
49
+ let statusResp;
50
+ try {
51
+ statusResp = await this.client.pollStatus(deviceId);
52
+ }
53
+ catch (err) {
54
+ if (err instanceof PairingApiError && err.statusCode >= 500) {
55
+ // Transient server error — keep polling
56
+ continue;
57
+ }
58
+ throw err;
59
+ }
60
+ switch (statusResp.status) {
61
+ case "pending":
62
+ continue;
63
+ case "approved": {
64
+ if (!statusResp.deviceToken) {
65
+ throw new Error("Server returned approved but no deviceToken");
66
+ }
67
+ // Store token in keychain
68
+ await storeDeviceToken(statusResp.deviceToken);
69
+ // Persist full pairing config to disk
70
+ this.configRepo.writePairingConfig({
71
+ deviceId,
72
+ deviceToken: statusResp.deviceToken,
73
+ pairedAt: new Date().toISOString(),
74
+ });
75
+ return { status: "approved", deviceId };
76
+ }
77
+ case "denied":
78
+ return { status: "denied" };
79
+ case "expired":
80
+ return { status: "expired" };
81
+ default:
82
+ // Unknown status — keep polling conservatively
83
+ continue;
84
+ }
85
+ }
86
+ }
87
+ // ---------------------------------------------------------------------------
88
+ // Private helpers
89
+ // ---------------------------------------------------------------------------
90
+ getOrCreateDeviceId() {
91
+ const existing = this.configRepo.readDeviceId();
92
+ if (existing)
93
+ return existing;
94
+ const id = randomUUID();
95
+ this.configRepo.writeDeviceId(id);
96
+ return id;
97
+ }
98
+ }
99
+ function sleep(ms) {
100
+ return new Promise((resolve) => setTimeout(resolve, ms));
101
+ }
102
+ //# sourceMappingURL=pairing-service.js.map