@jive-sh/skill-sync 0.11.0-latest-darwin-x64 → 0.11.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 (236) hide show
  1. package/README.md +346 -0
  2. package/bin/package.json +1 -0
  3. package/bin/skill-sync +34 -0
  4. package/bin/skill-sync-daemon +34 -0
  5. package/dist/daemons/skill-sync-daemon.js +664 -0
  6. package/dist/daemons/skill-sync-daemon.js.map +1 -0
  7. package/dist/entrypoints/skill-sync.js +7 -0
  8. package/dist/entrypoints/skill-sync.js.map +1 -0
  9. package/dist/index.js +10 -0
  10. package/dist/index.js.map +1 -0
  11. package/dist/internal/agents/agent-tool.js +102 -0
  12. package/dist/internal/agents/agent-tool.js.map +1 -0
  13. package/dist/internal/agents/claude.js +424 -0
  14. package/dist/internal/agents/claude.js.map +1 -0
  15. package/dist/internal/agents/codex.js +270 -0
  16. package/dist/internal/agents/codex.js.map +1 -0
  17. package/dist/internal/agents/command.js +219 -0
  18. package/dist/internal/agents/command.js.map +1 -0
  19. package/dist/internal/agents/grok.js +170 -0
  20. package/dist/internal/agents/grok.js.map +1 -0
  21. package/dist/internal/agents/index.js +70 -0
  22. package/dist/internal/agents/index.js.map +1 -0
  23. package/dist/internal/cli.js +218 -0
  24. package/dist/internal/cli.js.map +1 -0
  25. package/dist/internal/comment-watch/held.js +14 -0
  26. package/dist/internal/comment-watch/held.js.map +1 -0
  27. package/dist/internal/comment-watch/key.js +4 -0
  28. package/dist/internal/comment-watch/key.js.map +1 -0
  29. package/dist/internal/comment-watch/message.js +37 -0
  30. package/dist/internal/comment-watch/message.js.map +1 -0
  31. package/dist/internal/comment-watch/paths.js +16 -0
  32. package/dist/internal/comment-watch/paths.js.map +1 -0
  33. package/dist/internal/comment-watch/platform.js +66 -0
  34. package/dist/internal/comment-watch/platform.js.map +1 -0
  35. package/dist/internal/comment-watch/protocol.js +124 -0
  36. package/dist/internal/comment-watch/protocol.js.map +1 -0
  37. package/dist/internal/comment-watch/recent.js +27 -0
  38. package/dist/internal/comment-watch/recent.js.map +1 -0
  39. package/dist/internal/comment-watch/replies.js +28 -0
  40. package/dist/internal/comment-watch/replies.js.map +1 -0
  41. package/dist/internal/comment-watch/service.js +174 -0
  42. package/dist/internal/comment-watch/service.js.map +1 -0
  43. package/dist/internal/comment-watch/settings.js +66 -0
  44. package/dist/internal/comment-watch/settings.js.map +1 -0
  45. package/dist/internal/comment-watch/source/github-pull-requests/conversations.js +85 -0
  46. package/dist/internal/comment-watch/source/github-pull-requests/conversations.js.map +1 -0
  47. package/dist/internal/comment-watch/source/github-pull-requests/impl.js +276 -0
  48. package/dist/internal/comment-watch/source/github-pull-requests/impl.js.map +1 -0
  49. package/dist/internal/comment-watch/source/github-pull-requests/queries.js +97 -0
  50. package/dist/internal/comment-watch/source/github-pull-requests/queries.js.map +1 -0
  51. package/dist/internal/comment-watch/source/google-doc/doc.js +57 -0
  52. package/dist/internal/comment-watch/source/google-doc/doc.js.map +1 -0
  53. package/dist/internal/comment-watch/source/google-doc/impl.js +190 -0
  54. package/dist/internal/comment-watch/source/google-doc/impl.js.map +1 -0
  55. package/dist/internal/comment-watch/source/http-api.js +74 -0
  56. package/dist/internal/comment-watch/source/http-api.js.map +1 -0
  57. package/dist/internal/comment-watch/source/interface.js +48 -0
  58. package/dist/internal/comment-watch/source/interface.js.map +1 -0
  59. package/dist/internal/comment-watch/source/sign-in.js +40 -0
  60. package/dist/internal/comment-watch/source/sign-in.js.map +1 -0
  61. package/dist/internal/comment-watch/source/sources.js +15 -0
  62. package/dist/internal/comment-watch/source/sources.js.map +1 -0
  63. package/dist/internal/comment-watch/store/impl.js +242 -0
  64. package/dist/internal/comment-watch/store/impl.js.map +1 -0
  65. package/dist/internal/comment-watch/store/interface.js +10 -0
  66. package/dist/internal/comment-watch/store/interface.js.map +1 -0
  67. package/dist/internal/comment-watch/t3.js +49 -0
  68. package/dist/internal/comment-watch/t3.js.map +1 -0
  69. package/dist/internal/comment-watch/watching.js +65 -0
  70. package/dist/internal/comment-watch/watching.js.map +1 -0
  71. package/dist/internal/comment-watch/workflow/comment-watch.js +19 -0
  72. package/dist/internal/comment-watch/workflow/comment-watch.js.map +1 -0
  73. package/dist/internal/comment-watch/workflow/deliver.js +104 -0
  74. package/dist/internal/comment-watch/workflow/deliver.js.map +1 -0
  75. package/dist/internal/comment-watch/workflow/find.js +67 -0
  76. package/dist/internal/comment-watch/workflow/find.js.map +1 -0
  77. package/dist/internal/comment-watch/workflow/post-once.js +66 -0
  78. package/dist/internal/comment-watch/workflow/post-once.js.map +1 -0
  79. package/dist/internal/comment-watch/workflow/post.js +40 -0
  80. package/dist/internal/comment-watch/workflow/post.js.map +1 -0
  81. package/dist/internal/config.js +131 -0
  82. package/dist/internal/config.js.map +1 -0
  83. package/dist/internal/control.js +113 -0
  84. package/dist/internal/control.js.map +1 -0
  85. package/dist/internal/daemon-control/impl.js +80 -0
  86. package/dist/internal/daemon-control/impl.js.map +1 -0
  87. package/dist/internal/daemon-control/interface.js +4 -0
  88. package/dist/internal/daemon-control/interface.js.map +1 -0
  89. package/dist/internal/folders.js +47 -0
  90. package/dist/internal/folders.js.map +1 -0
  91. package/dist/internal/local-skills.js +43 -0
  92. package/dist/internal/local-skills.js.map +1 -0
  93. package/dist/internal/path.js +36 -0
  94. package/dist/internal/path.js.map +1 -0
  95. package/dist/internal/server.js +80 -0
  96. package/dist/internal/server.js.map +1 -0
  97. package/dist/internal/skill-check.js +83 -0
  98. package/dist/internal/skill-check.js.map +1 -0
  99. package/dist/internal/skill-refinement/evals/cases.js +143 -0
  100. package/dist/internal/skill-refinement/evals/cases.js.map +1 -0
  101. package/dist/internal/skill-refinement/evals/opus-action-judge-original.json +350 -0
  102. package/dist/internal/skill-refinement/evals/opus-judge-original.json +165 -0
  103. package/dist/internal/skill-refinement/feedback/import-legacy.js +13 -0
  104. package/dist/internal/skill-refinement/feedback/import-legacy.js.map +1 -0
  105. package/dist/internal/skill-refinement/feedback/intake.js +52 -0
  106. package/dist/internal/skill-refinement/feedback/intake.js.map +1 -0
  107. package/dist/internal/skill-refinement/feedback/managed-intake.js +19 -0
  108. package/dist/internal/skill-refinement/feedback/managed-intake.js.map +1 -0
  109. package/dist/internal/skill-refinement/feedback/outbox.js +44 -0
  110. package/dist/internal/skill-refinement/feedback/outbox.js.map +1 -0
  111. package/dist/internal/skill-refinement/jev/impl.js +63 -0
  112. package/dist/internal/skill-refinement/jev/impl.js.map +1 -0
  113. package/dist/internal/skill-refinement/jev/interface.js +6 -0
  114. package/dist/internal/skill-refinement/jev/interface.js.map +1 -0
  115. package/dist/internal/skill-refinement/managed-daemon.js +30 -0
  116. package/dist/internal/skill-refinement/managed-daemon.js.map +1 -0
  117. package/dist/internal/skill-refinement/managed-worker-credentials.js +60 -0
  118. package/dist/internal/skill-refinement/managed-worker-credentials.js.map +1 -0
  119. package/dist/internal/skill-refinement/managed-worker-files.js +25 -0
  120. package/dist/internal/skill-refinement/managed-worker-files.js.map +1 -0
  121. package/dist/internal/skill-refinement/managed-worker-loop.js +36 -0
  122. package/dist/internal/skill-refinement/managed-worker-loop.js.map +1 -0
  123. package/dist/internal/skill-refinement/organization-site.js +13 -0
  124. package/dist/internal/skill-refinement/organization-site.js.map +1 -0
  125. package/dist/internal/skill-refinement/paths.js +62 -0
  126. package/dist/internal/skill-refinement/paths.js.map +1 -0
  127. package/dist/internal/skill-refinement/platform.js +67 -0
  128. package/dist/internal/skill-refinement/platform.js.map +1 -0
  129. package/dist/internal/skill-refinement/service.js +365 -0
  130. package/dist/internal/skill-refinement/service.js.map +1 -0
  131. package/dist/internal/skill-refinement/skills/skill-text.js +219 -0
  132. package/dist/internal/skill-refinement/skills/skill-text.js.map +1 -0
  133. package/dist/internal/skill-refinement/workflow/retry.js +44 -0
  134. package/dist/internal/skill-refinement/workflow/retry.js.map +1 -0
  135. package/dist/internal/skill-refinement/workflow/skill-refinement.js +690 -0
  136. package/dist/internal/skill-refinement/workflow/skill-refinement.js.map +1 -0
  137. package/dist/internal/skill-refinement/writer/impl.js +2 -0
  138. package/dist/internal/skill-refinement/writer/impl.js.map +1 -0
  139. package/dist/internal/skill-refinement/writer/interface.js +2 -0
  140. package/dist/internal/skill-refinement/writer/interface.js.map +1 -0
  141. package/dist/internal/sync.js +182 -0
  142. package/dist/internal/sync.js.map +1 -0
  143. package/dist/internal/wire.js +31 -0
  144. package/dist/internal/wire.js.map +1 -0
  145. package/dist/internal/writer/claude.js +84 -0
  146. package/dist/internal/writer/claude.js.map +1 -0
  147. package/dist/internal/writer/codex.js +102 -0
  148. package/dist/internal/writer/codex.js.map +1 -0
  149. package/dist/internal/writer/interface.js +6 -0
  150. package/dist/internal/writer/interface.js.map +1 -0
  151. package/dist/internal/writer/live.js +13 -0
  152. package/dist/internal/writer/live.js.map +1 -0
  153. package/dist/internal/writer/reset.js +38 -0
  154. package/dist/internal/writer/reset.js.map +1 -0
  155. package/dist/internal/writer/selection.js +79 -0
  156. package/dist/internal/writer/selection.js.map +1 -0
  157. package/package.json +45 -11
  158. package/postinstall.cjs +663 -0
  159. package/src/daemons/skill-sync-daemon.ts +677 -0
  160. package/src/entrypoints/skill-sync.ts +12 -0
  161. package/src/index.ts +15 -0
  162. package/src/internal/agents/agent-tool.ts +149 -0
  163. package/src/internal/agents/claude.ts +442 -0
  164. package/src/internal/agents/codex.ts +288 -0
  165. package/src/internal/agents/command.ts +257 -0
  166. package/src/internal/agents/grok.ts +174 -0
  167. package/src/internal/agents/index.ts +74 -0
  168. package/src/internal/cli.ts +249 -0
  169. package/src/internal/comment-watch/held.ts +20 -0
  170. package/src/internal/comment-watch/key.ts +5 -0
  171. package/src/internal/comment-watch/message.ts +39 -0
  172. package/src/internal/comment-watch/paths.ts +17 -0
  173. package/src/internal/comment-watch/platform.ts +69 -0
  174. package/src/internal/comment-watch/protocol.ts +140 -0
  175. package/src/internal/comment-watch/recent.ts +26 -0
  176. package/src/internal/comment-watch/replies.ts +28 -0
  177. package/src/internal/comment-watch/service.ts +198 -0
  178. package/src/internal/comment-watch/settings.ts +82 -0
  179. package/src/internal/comment-watch/source/github-pull-requests/conversations.ts +111 -0
  180. package/src/internal/comment-watch/source/github-pull-requests/impl.ts +291 -0
  181. package/src/internal/comment-watch/source/github-pull-requests/queries.ts +113 -0
  182. package/src/internal/comment-watch/source/google-doc/doc.ts +76 -0
  183. package/src/internal/comment-watch/source/google-doc/impl.ts +198 -0
  184. package/src/internal/comment-watch/source/http-api.ts +93 -0
  185. package/src/internal/comment-watch/source/interface.ts +116 -0
  186. package/src/internal/comment-watch/source/sign-in.ts +45 -0
  187. package/src/internal/comment-watch/source/sources.ts +20 -0
  188. package/src/internal/comment-watch/store/impl.ts +268 -0
  189. package/src/internal/comment-watch/store/interface.ts +83 -0
  190. package/src/internal/comment-watch/t3.ts +68 -0
  191. package/src/internal/comment-watch/watching.ts +122 -0
  192. package/src/internal/comment-watch/workflow/comment-watch.ts +34 -0
  193. package/src/internal/comment-watch/workflow/deliver.ts +115 -0
  194. package/src/internal/comment-watch/workflow/find.ts +78 -0
  195. package/src/internal/comment-watch/workflow/post-once.ts +72 -0
  196. package/src/internal/comment-watch/workflow/post.ts +56 -0
  197. package/src/internal/config.ts +172 -0
  198. package/src/internal/control.ts +165 -0
  199. package/src/internal/daemon-control/impl.ts +94 -0
  200. package/src/internal/daemon-control/interface.ts +46 -0
  201. package/src/internal/folders.ts +50 -0
  202. package/src/internal/local-skills.ts +58 -0
  203. package/src/internal/path.ts +32 -0
  204. package/src/internal/server.ts +76 -0
  205. package/src/internal/skill-check.ts +97 -0
  206. package/src/internal/skill-refinement/evals/cases.ts +167 -0
  207. package/src/internal/skill-refinement/evals/opus-action-judge-original.json +350 -0
  208. package/src/internal/skill-refinement/evals/opus-judge-original.json +165 -0
  209. package/src/internal/skill-refinement/feedback/import-legacy.ts +16 -0
  210. package/src/internal/skill-refinement/feedback/intake.ts +66 -0
  211. package/src/internal/skill-refinement/feedback/managed-intake.ts +19 -0
  212. package/src/internal/skill-refinement/feedback/outbox.ts +50 -0
  213. package/src/internal/skill-refinement/jev/impl.ts +76 -0
  214. package/src/internal/skill-refinement/jev/interface.ts +56 -0
  215. package/src/internal/skill-refinement/managed-daemon.ts +38 -0
  216. package/src/internal/skill-refinement/managed-worker-credentials.ts +59 -0
  217. package/src/internal/skill-refinement/managed-worker-files.ts +24 -0
  218. package/src/internal/skill-refinement/managed-worker-loop.ts +46 -0
  219. package/src/internal/skill-refinement/organization-site.ts +15 -0
  220. package/src/internal/skill-refinement/paths.ts +87 -0
  221. package/src/internal/skill-refinement/platform.ts +71 -0
  222. package/src/internal/skill-refinement/service.ts +418 -0
  223. package/src/internal/skill-refinement/skills/skill-text.ts +292 -0
  224. package/src/internal/skill-refinement/workflow/retry.ts +61 -0
  225. package/src/internal/skill-refinement/workflow/skill-refinement.ts +777 -0
  226. package/src/internal/skill-refinement/writer/impl.ts +1 -0
  227. package/src/internal/skill-refinement/writer/interface.ts +1 -0
  228. package/src/internal/sync.ts +216 -0
  229. package/src/internal/wire.ts +439 -0
  230. package/src/internal/writer/claude.ts +98 -0
  231. package/src/internal/writer/codex.ts +93 -0
  232. package/src/internal/writer/interface.ts +48 -0
  233. package/src/internal/writer/live.ts +19 -0
  234. package/src/internal/writer/reset.ts +34 -0
  235. package/src/internal/writer/selection.ts +84 -0
  236. package/multi-call-binary +0 -4
@@ -0,0 +1,174 @@
1
+ import { existsSync, readdirSync, statSync } from "node:fs";
2
+ import { spawnSync } from "node:child_process";
3
+ import { join } from "node:path";
4
+ import { Result, Schema } from "effect";
5
+ import type { AccountLimits, LocalUse } from "../wire";
6
+ import { CLI_TIMEOUT_MS, DAY_MS, PERIOD_DAYS, USD_MICROS, homesNamed, inSessionOrder, isDirectory, parseJson, unknownShape, windowName, type AgentTool } from "./agent-tool";
7
+ import { askJsonRpc, type RpcResponse } from "./command";
8
+
9
+ /**
10
+ * Grok. Each account is a `GROK_HOME` (`~/.grok`, `~/.grok-<name>`), and Grok's docs name its `skills`
11
+ * folder as where it reads a user's skills. Grok also reads `~/.agents/skills`, undocumented; a skill in
12
+ * both loads once, from the Grok home (checked with `grok inspect`, Grok 1.0.70).
13
+ *
14
+ * - Account: the plan allowance comes from `grok agent stdio`, the same way Grok's `/usage` screen gets it
15
+ * (`readGrokLimits`). `grok` has no command that says who is signed in, so no account is shown.
16
+ * - This machine: what `grok usage <session-id>` prints, the command Grok's docs say to use instead of
17
+ * reading session files: each session's token and cost totals (`costUsdTicks`, 10^10 per US dollar),
18
+ * summed over sessions active in the last `PERIOD_DAYS` days. A session's totals include history it
19
+ * inherited by resume or fork, so a fork counts that part twice.
20
+ */
21
+ export const grok: AgentTool = {
22
+ tool: "grok",
23
+ skillsFolders: (home) => homesNamed(home, "grok").map((account) => join(account, "skills")),
24
+ accounts: (home) => homesNamed(home, "grok"),
25
+ readAccount: async (account, { home, now }) => ({ identity: null, limits: await readGrokLimits({ account, home, now }) }),
26
+ readLocalUse: (account, _home, now) => readGrok(account, now),
27
+ };
28
+
29
+ // ── The account ─────────────────────────────────────────────────────────────────────────────────────
30
+
31
+ const REQUEST_BILLING = 2;
32
+
33
+ /**
34
+ * `_x.ai/billing`'s answer, as Grok 1.0.70 gives it (its `extensions/billing.rs`): the share of the plan's
35
+ * allowance used in the current period, which is a week on SuperGrok plans.
36
+ */
37
+ const BillingAnswer = Schema.Struct({
38
+ config: Schema.Struct({
39
+ creditUsagePercent: Schema.Finite,
40
+ currentPeriod: Schema.Struct({ start: Schema.String, end: Schema.String }),
41
+ }),
42
+ });
43
+
44
+ /**
45
+ * The plan allowance, as Grok's `/usage` screen shows it: that screen asks the agent `_x.ai/billing` over the
46
+ * Agent Client Protocol, so this asks the same of `grok agent stdio`, which fetches it from grok.com with the
47
+ * account's own sign-in. Undocumented, so a changed answer reads as unknown rather than as a guess.
48
+ */
49
+ async function readGrokLimits(input: { readonly account: string; readonly home: string; readonly now: number }): Promise<AccountLimits> {
50
+ const command = join(input.account, "bin", "grok");
51
+ if (!existsSync(command)) return { state: "unknown", reason: `Grok's command is not at ${command}` };
52
+ const asked = await askJsonRpc({
53
+ name: "grok agent stdio",
54
+ command,
55
+ args: ["agent", "--no-leader", "stdio"],
56
+ env: { ...process.env, GROK_HOME: input.account },
57
+ cwd: input.home,
58
+ timeoutMs: CLI_TIMEOUT_MS,
59
+ messages: [
60
+ { id: 1, method: "initialize", params: { protocolVersion: 1, clientCapabilities: {} } },
61
+ { id: REQUEST_BILLING, method: "_x.ai/billing", params: {} },
62
+ ],
63
+ });
64
+ if (asked.kind === "failed") return { state: "unknown", reason: asked.reason };
65
+ return parseBillingAnswer(asked.answers.get(REQUEST_BILLING)!, input.now);
66
+ }
67
+
68
+ export function parseBillingAnswer(answer: RpcResponse, now: number): AccountLimits {
69
+ if (answer.error !== undefined) return { state: "unknown", reason: `\`_x.ai/billing\` failed: ${answer.error.message.slice(0, 160)}` };
70
+ const decoded = Schema.decodeUnknownResult(BillingAnswer)(answer.result);
71
+ if (Result.isFailure(decoded)) return unknownShape("Grok's `_x.ai/billing` answer", decoded.failure.issue);
72
+ const { creditUsagePercent, currentPeriod } = decoded.success.config;
73
+ const start = Date.parse(currentPeriod.start);
74
+ const end = Date.parse(currentPeriod.end);
75
+ if (!Number.isFinite(start) || !Number.isFinite(end)) {
76
+ return { state: "unknown", reason: "Grok's `_x.ai/billing` answer changed shape: its period's start or end is not a time" };
77
+ }
78
+ const minutes = Math.round((end - start) / 60_000);
79
+ return {
80
+ state: "reading",
81
+ asOf: now,
82
+ source: "account",
83
+ windows: [{ name: windowName(minutes), minutes, usedPercent: creditUsagePercent, resetsAt: end }],
84
+ };
85
+ }
86
+
87
+ // ── This machine ────────────────────────────────────────────────────────────────────────────────────
88
+
89
+ const GrokUsage = Schema.Struct({
90
+ sessionId: Schema.String,
91
+ updatedAt: Schema.String,
92
+ session: Schema.Struct({ costUsdTicks: Schema.Finite, totalTokens: Schema.Finite }),
93
+ });
94
+ const TICKS_PER_USD = 1e10;
95
+ /** `grok usage` reads one session's file and exits; this bounds a hung one. */
96
+ const COMMAND_TIMEOUT_MS = 10_000;
97
+
98
+ export type SessionTotals =
99
+ | { readonly kind: "totals"; readonly usd: number; readonly updatedAt: number }
100
+ /** A session with no turn yet: `grok usage` exits 1 saying "No usage recorded". */
101
+ | { readonly kind: "empty" }
102
+ | { readonly kind: "failed"; readonly reason: string };
103
+
104
+ /** A session's totals are fetched again only when its directory changed: each `grok usage` run takes most of a second. */
105
+ const sessionCache = new Map<string, { readonly modifiedAt: number; readonly totals: SessionTotals }>();
106
+
107
+ function readGrok(account: string, now: number): LocalUse {
108
+ const command = join(account, "bin", "grok");
109
+ const sessions = sessionDirs(join(account, "sessions"), now - PERIOD_DAYS * DAY_MS);
110
+ if (sessions.length === 0) return { state: "none" };
111
+ if (!existsSync(command)) return { state: "unknown", reason: `Grok's command is not at ${command}` };
112
+
113
+ const totals: (Extract<SessionTotals, { kind: "totals" }> & { readonly id: string })[] = [];
114
+ for (const session of sessions) {
115
+ const cached = sessionCache.get(session.path);
116
+ const result = cached !== undefined && cached.modifiedAt === session.modifiedAt
117
+ ? cached.totals
118
+ : runGrokUsage(command, account, session.id);
119
+ // A failure is asked again next time rather than kept until the session changes.
120
+ if (result.kind !== "failed") sessionCache.set(session.path, { modifiedAt: session.modifiedAt, totals: result });
121
+ if (result.kind === "failed") return { state: "unknown", reason: result.reason };
122
+ if (result.kind === "totals") totals.push({ ...result, id: session.id });
123
+ }
124
+ if (totals.length === 0) return { state: "none" };
125
+ return {
126
+ state: "spend",
127
+ periodDays: PERIOD_DAYS,
128
+ ...USD_MICROS,
129
+ sessions: inSessionOrder(totals.map((session) => ({ id: session.id, amount: Math.round(session.usd * 10 ** USD_MICROS.exponent), lastActiveAt: session.updatedAt }))),
130
+ partial: false,
131
+ provider: null,
132
+ };
133
+ }
134
+
135
+ /**
136
+ * Sessions active since `since`: `sessions/<encoded working directory>/<session id>/`, whose modification
137
+ * time moves whenever Grok writes the session's files.
138
+ */
139
+ function sessionDirs(dir: string, since: number): { readonly id: string; readonly path: string; readonly modifiedAt: number }[] {
140
+ if (!isDirectory(dir)) return [];
141
+ return readdirSync(dir).flatMap((project) => {
142
+ const projectDir = join(dir, project);
143
+ if (!isDirectory(projectDir)) return [];
144
+ return readdirSync(projectDir).flatMap((id) => {
145
+ const path = join(projectDir, id);
146
+ if (!/^[0-9a-f-]{36}$/i.test(id) || !isDirectory(path)) return [];
147
+ const modifiedAt = statSync(path).mtimeMs;
148
+ return modifiedAt >= since ? [{ id, path, modifiedAt }] : [];
149
+ });
150
+ });
151
+ }
152
+
153
+ export function runGrokUsage(command: string, account: string, sessionId: string): SessionTotals {
154
+ const run = spawnSync(command, ["usage", sessionId], {
155
+ env: { ...process.env, GROK_HOME: account },
156
+ encoding: "utf-8",
157
+ timeout: COMMAND_TIMEOUT_MS,
158
+ });
159
+ if (run.status === 0) return parseGrokUsage(run.stdout);
160
+ const stderr = (run.stderr ?? "").trim();
161
+ if (stderr.includes("No usage recorded")) return { kind: "empty" };
162
+ return { kind: "failed", reason: `\`grok usage\` failed: ${run.error?.message ?? (stderr.slice(0, 160) || `exit ${run.status}`)}` };
163
+ }
164
+
165
+ export function parseGrokUsage(stdout: string): SessionTotals {
166
+ const decoded = Schema.decodeUnknownResult(GrokUsage)(parseJson(stdout));
167
+ if (Result.isFailure(decoded)) {
168
+ const reading = unknownShape("`grok usage` output", decoded.failure.issue);
169
+ return { kind: "failed", reason: reading.state === "unknown" ? reading.reason : "" };
170
+ }
171
+ const updatedAt = Date.parse(decoded.success.updatedAt);
172
+ if (!Number.isFinite(updatedAt)) return { kind: "failed", reason: "`grok usage` output changed shape: updatedAt is not a time" };
173
+ return { kind: "totals", usd: decoded.success.session.costUsdTicks / TICKS_PER_USD, updatedAt };
174
+ }
@@ -0,0 +1,74 @@
1
+ import { homedir } from "node:os";
2
+ import type { AccountUsage, LocalUse } from "../wire";
3
+ import type { AccountContext, AccountReading, AgentTool } from "./agent-tool";
4
+ import { findCommand } from "./command";
5
+ import { claude } from "./claude";
6
+ import { codex } from "./codex";
7
+ import { grok } from "./grok";
8
+
9
+ /** Every coding agent skill-sync syncs skills for and reads usage of. */
10
+ export const AGENT_TOOLS: ReadonlyArray<AgentTool> = [claude, codex, grok];
11
+
12
+ /**
13
+ * Every skills folder any agent tool reads on this machine. Every one is a candidate, whether or not it
14
+ * exists yet, so an account added later joins without anyone listing it. Which of them actually sync is
15
+ * the user's choice on the dashboard; a folder that is synced and missing is created.
16
+ */
17
+ export function detectFolders(home: string = homedir()): string[] {
18
+ return [...new Set(AGENT_TOOLS.flatMap((tool) => tool.skillsFolders(home)))].sort();
19
+ }
20
+
21
+ /**
22
+ * How long an account reading is kept before its CLI is asked again. Each ask starts the tool's CLI
23
+ * (about two seconds of CPU for `claude`) and calls its service, so it happens at most this often per
24
+ * account, while this machine's use, read from local files, is read on every call.
25
+ */
26
+ export const ACCOUNT_READ_MS = 5 * 60_000;
27
+
28
+ const accountCache = new Map<string, { readonly readAt: number; readonly reading: AccountReading }>();
29
+
30
+ /**
31
+ * Every account of every agent tool on this machine: who it is and its plan limits (from the tool's CLI,
32
+ * at most every `ACCOUNT_READ_MS`), and this machine's use of it. One account's failure never hides another's.
33
+ */
34
+ export async function readUsage(input: Partial<AccountContext> = {}): Promise<AccountUsage[]> {
35
+ const home = input.home ?? homedir();
36
+ const context: AccountContext = {
37
+ home,
38
+ now: input.now ?? Date.now(),
39
+ findCommand: input.findCommand ?? ((command) => findCommand({ ...command, home })),
40
+ };
41
+ const now = context.now;
42
+ const accounts = AGENT_TOOLS
43
+ .flatMap((tool) => tool.accounts(home).map((account) => ({ tool, account })))
44
+ .sort((a, b) => a.account.localeCompare(b.account));
45
+ for (const account of accountCache.keys()) {
46
+ if (!accounts.some((entry) => entry.account === account)) accountCache.delete(account);
47
+ }
48
+ return Promise.all(accounts.map(async ({ tool, account }): Promise<AccountUsage> => {
49
+ const reading = await cachedAccount(tool, account, context);
50
+ let local: LocalUse;
51
+ try {
52
+ local = tool.readLocalUse(account, home, now);
53
+ } catch (cause) {
54
+ local = { state: "unknown", reason: `could not read: ${describe(cause)}` };
55
+ }
56
+ return { tool: tool.tool, home: account.slice(home.length).replace(/^[\\/]/, ""), ...reading, local };
57
+ }));
58
+ }
59
+
60
+ async function cachedAccount(tool: AgentTool, account: string, context: AccountContext): Promise<AccountReading> {
61
+ const now = context.now;
62
+ const cached = accountCache.get(account);
63
+ if (cached !== undefined && now - cached.readAt < ACCOUNT_READ_MS) return cached.reading;
64
+ let reading: AccountReading;
65
+ try {
66
+ reading = await tool.readAccount(account, context);
67
+ } catch (cause) {
68
+ reading = { identity: null, limits: { state: "unknown", reason: `could not read: ${describe(cause)}` } };
69
+ }
70
+ accountCache.set(account, { readAt: now, reading });
71
+ return reading;
72
+ }
73
+
74
+ const describe = (cause: unknown): string => cause instanceof Error ? cause.message : String(cause);
@@ -0,0 +1,249 @@
1
+ import { spawn } from "node:child_process";
2
+ import { readFileSync } from "node:fs";
3
+ import { Data, Effect, Schedule, Stdio, Stream, pipe } from "effect";
4
+ import { Cli, upgrade } from "jive-abstract-library";
5
+ import { name, version } from "../../package.json";
6
+ import { detectFolders } from "./agents";
7
+ import { loadSettings } from "./config";
8
+ import { DaemonFailed } from "./control";
9
+ import { DaemonControl, type DaemonError, type IDaemonControl } from "./daemon-control/interface";
10
+ import { watchingLines } from "./comment-watch/watching";
11
+ import { addableSkills, formatSkillCopies, skillCopies } from "./local-skills";
12
+
13
+ /**
14
+ * The CLI that accompanies the daemon: `login`, `logout`, `list`, `add`, `show`, `feedback`, `watching`, `reply`, `upgrade` and `version`. Which
15
+ * folders sync is chosen on the dashboard; skills are ticked there too, or added with `add` by the agent that
16
+ * wrote one.
17
+ *
18
+ * The daemon owns the sync token and keeps it in `~/.jive/skill-sync-token.json`. `login`, `logout`, `list`,
19
+ * `add`, `feedback`, `watching` and `reply` are requests to it over the control socket; the daemon claims the token from the server itself, so it
20
+ * never passes through here. Tab after `show` lists the synced skills and Tab after `add` the skills that could be
21
+ * added, both asked of the daemon when Tab is pressed.
22
+ */
23
+
24
+ const DASHBOARD = "https://skill-sync.jive.sh/";
25
+
26
+ /** How long Tab waits for the daemon before showing that it did not answer; it never starts one. */
27
+ const TAB_TIME_LIMIT_SECONDS = 3;
28
+
29
+ /** How often a command asks again after starting the daemon, and how many times. */
30
+ const RETRY_INTERVAL = "500 millis";
31
+ const RETRIES = 20;
32
+
33
+ class SkillNotOnThisMachine extends Data.TaggedError("SkillNotOnThisMachine")<{ readonly message: string }> {}
34
+ class FeedbackNotRead extends Data.TaggedError("FeedbackNotRead")<{ readonly message: string }> {}
35
+ class ReplyNotPosted extends Data.TaggedError("ReplyNotPosted")<{ readonly message: string }> {}
36
+ class UpgradeFailed extends Data.TaggedError("UpgradeFailed")<{ readonly message: string }> {}
37
+
38
+ export const skillSync = Cli.make("skill-sync", {
39
+ login: Cli.command({
40
+ description: "sign this machine in with your passkey, approved in a browser on this computer or any other; it stays signed in until you log out",
41
+ *run() {
42
+ const machine = yield* withDaemon((daemon) => daemon.login((url) => pipe(
43
+ Effect.log(`Approve this sign-in with your passkey at ${url} (in a browser on this computer or any other, such as your phone). Waiting…`),
44
+ Effect.andThen(Effect.sync(() => openBrowser(url))),
45
+ )));
46
+ yield* Effect.log(`Signed in. ${machine} is syncing; choose what syncs at ${DASHBOARD}`);
47
+ },
48
+ }),
49
+
50
+ logout: Cli.command({
51
+ description: "revoke this machine's token and stop syncing until the next login",
52
+ *run() {
53
+ const revoked = yield* withDaemon((daemon) => daemon.logout());
54
+ yield* Effect.log(revoked ? "Signed out; the token is revoked." : "Signed out locally; the server could not be reached to revoke the token.");
55
+ },
56
+ }),
57
+
58
+ list: Cli.command({
59
+ description: "list the skills that sync, as the server holds them; needs this machine signed in",
60
+ *run() {
61
+ const skills = yield* withDaemon((daemon) => daemon.listSyncedSkills());
62
+ if (skills.length === 0) {
63
+ yield* Effect.log(`No skills sync yet; tick them at ${DASHBOARD}`);
64
+ return;
65
+ }
66
+ const width = Math.max(...skills.map((skill) => skill.name.length));
67
+ for (const skill of skills) {
68
+ const detail = skill.editedAt === null
69
+ ? "no files yet"
70
+ : `${skill.files} ${skill.files === 1 ? "file" : "files"}, last edited ${new Date(skill.editedAt).toLocaleString()} on ${skill.editedBy}`;
71
+ yield* Effect.log(`${skill.name.padEnd(width)} ${detail}`);
72
+ }
73
+ },
74
+ }),
75
+
76
+ add: Cli.choose({
77
+ description: "put a skill meant for every project on the synced list; give its folder name, which must match the name in its SKILL.md. It must be in a folder skill-sync syncs, with a valid SKILL.md. Repeating it changes nothing",
78
+ *choices() {
79
+ const synced = (yield* listForTab).map((skill) => skill.name);
80
+ return addableSkills({ folders: detectFolders(), exclude: loadSettings()?.exclude ?? [], synced });
81
+ },
82
+ next: (skill) => Cli.command({
83
+ description: `put ${skill} on the synced list`,
84
+ *run() {
85
+ const result = yield* withDaemon((daemon) => daemon.addSkill(skill));
86
+ yield* Effect.log(result.added ? `Added ${skill} to the synced list.` : `${skill} was already on the synced list.`);
87
+ if (result.syncingFolders.length === 0) {
88
+ yield* Effect.log(`None of the folders holding it on this machine (${result.folders.join(", ")}) is ticked at ${DASHBOARD}, so its files upload once one is.`);
89
+ }
90
+ },
91
+ }),
92
+ }),
93
+
94
+ show: Cli.choose({
95
+ description: "print a synced skill's description and where its copies are on this machine",
96
+ *choices() {
97
+ return (yield* listForTab).map((skill) => skill.name);
98
+ },
99
+ next: (skill) => Cli.command({
100
+ description: `print ${skill}'s description and where its copies are on this machine`,
101
+ *run() {
102
+ const folders = detectFolders();
103
+ const copies = skillCopies({ skill, folders });
104
+ if (copies.length === 0) {
105
+ return yield* new SkillNotOnThisMachine({
106
+ message: `no skills folder skill-sync syncs has a "${skill}" folder; it looked in ${folders.join(", ") || "no folders"}`,
107
+ });
108
+ }
109
+ yield* Effect.log(formatSkillCopies(copies));
110
+ },
111
+ }),
112
+ }),
113
+
114
+ feedback: Cli.command({
115
+ description: "hand one feedback item to this machine's skill refinement workflow: `skill-sync feedback <slug> <file>`, a few words naming it and a file holding his exact words and what drew them",
116
+ *run({ args }) {
117
+ const [slug, file] = args;
118
+ if (slug === undefined || file === undefined || args.length > 2) {
119
+ return yield* new FeedbackNotRead({ message: "usage: skill-sync feedback <slug> <file>, a few words naming the item and the file holding it" });
120
+ }
121
+ const text = yield* Effect.try({
122
+ try: () => readFileSync(file, "utf-8"),
123
+ catch: (cause) => new FeedbackNotRead({ message: `could not read ${file}: ${cause instanceof Error ? cause.message : String(cause)}` }),
124
+ });
125
+ if (text.trim() === "") return yield* new FeedbackNotRead({ message: `${file} is empty` });
126
+ const id = yield* withDaemon((daemon) => daemon.addFeedback({ slug, text }));
127
+ yield* Effect.log(`Added ${id} to the skill refinement queue; see it at ${DASHBOARD}#refinement`);
128
+ },
129
+ }),
130
+
131
+ watching: Cli.command({
132
+ description: "list the Google Docs subtabs and GitHub pull requests this machine's daemon is watching for comments, and when each was last read",
133
+ flags: { json: Cli.flag.boolean({ description: "print the same as JSON" }) },
134
+ *run({ flags }) {
135
+ // Never starts a daemon: one just started would show what it is about to read, not what was being watched.
136
+ const watching = yield* pipe(
137
+ Effect.gen(function* () { return yield* (yield* DaemonControl).watching(); }),
138
+ Effect.catchTag("DaemonNotRunning", () => Effect.fail(new DaemonFailed({ message: "the skill-sync daemon is not running" }))),
139
+ );
140
+ if (flags.json) yield* Effect.log(JSON.stringify(watching, null, 2));
141
+ else for (const line of watchingLines(watching, (time) => new Date(time).toLocaleString())) yield* Effect.log(line);
142
+ },
143
+ }),
144
+
145
+ reply: Cli.command({
146
+ description: "post an agent's words, held in a file, in the conversation of a comment it was told of: `skill-sync reply <comment> <file>`. Run again with the same words, it posts nothing more",
147
+ *run({ args }) {
148
+ const [key, file] = args;
149
+ if (key === undefined || file === undefined || args.length > 2) return yield* new ReplyNotPosted({ message: "usage: skill-sync reply <comment> <file>, the comment as it was named to you and the file holding your words" });
150
+ const text = yield* Effect.try({
151
+ try: () => readFileSync(file, "utf-8"),
152
+ catch: (cause) => new ReplyNotPosted({ message: `could not read ${file}: ${cause instanceof Error ? cause.message : String(cause)}` }),
153
+ });
154
+ const replied = yield* withDaemon((daemon) => daemon.reply({ key, text }));
155
+ if ("refused" in replied) return yield* new ReplyNotPosted({ message: `not posted: ${replied.refused}` });
156
+ yield* Effect.log("posted" in replied ? `Posted: ${replied.posted}` : `Not posted yet: ${replied.waiting}.`);
157
+ },
158
+ }),
159
+
160
+ upgrade: Cli.command({
161
+ description: "upgrade skill-sync to the latest version with the package manager that installed it",
162
+ *run() {
163
+ yield* pipe(upgrade({ packageName: name }), Effect.mapError((message) => new UpgradeFailed({ message: `Upgrade failed: ${message}` })));
164
+ },
165
+ }),
166
+
167
+ version: Cli.command({
168
+ description: "print the version of skill-sync installed here",
169
+ *run() {
170
+ yield* Effect.log(version);
171
+ },
172
+ }),
173
+ });
174
+
175
+ /**
176
+ * Runs the CLI on the process's arguments. A command that fails prints why on stderr, alone, and exits 1; usage
177
+ * errors are the library's (`Cli.CliError`, exit 2).
178
+ */
179
+ export function runSkillSync() {
180
+ return pipe(
181
+ Cli.run(skillSync, { version }),
182
+ Effect.catchTags({
183
+ DaemonFailed: report,
184
+ SkillNotOnThisMachine: report,
185
+ FeedbackNotRead: report,
186
+ ReplyNotPosted: report,
187
+ UpgradeFailed: report,
188
+ }),
189
+ );
190
+ }
191
+
192
+
193
+ function report(error: { readonly message: string }): Effect.Effect<never, Cli.CliError, Stdio.Stdio> {
194
+ return Effect.gen(function* () {
195
+ const stdio = yield* Stdio.Stdio;
196
+ yield* Effect.orDie(Stream.run(Stream.make(`${error.message}\n`), stdio.stderr()));
197
+ return yield* new Cli.CliError({ message: error.message, exitCode: 1 });
198
+ });
199
+ }
200
+
201
+ /**
202
+ * Runs `use` against the daemon. If none is listening (stopped, or never started since the install) this
203
+ * package's registered daemon is started and `use` is tried again for about ten seconds. Tab never comes here.
204
+ */
205
+ function withDaemon<A>(use: (daemon: IDaemonControl) => Effect.fn.Return<A, DaemonError>): Effect.Effect<A, DaemonFailed, DaemonControl> {
206
+ return Effect.gen(function* () {
207
+ const daemon = yield* DaemonControl;
208
+ const attempt = Effect.gen(() => use(daemon));
209
+ return yield* pipe(
210
+ attempt,
211
+ Effect.catchTag("DaemonNotRunning", () => pipe(
212
+ Effect.gen(() => daemon.startDaemon()),
213
+ Effect.andThen(Effect.sleep(RETRY_INTERVAL)),
214
+ Effect.andThen(Effect.retry(attempt, {
215
+ schedule: Schedule.spaced(RETRY_INTERVAL),
216
+ times: RETRIES,
217
+ while: (error) => error._tag === "DaemonNotRunning",
218
+ })),
219
+ Effect.catchTag("DaemonNotRunning", (error) =>
220
+ Effect.fail(new DaemonFailed({ message: `${error.message}. Reinstall skill-sync to register its daemon.` }))),
221
+ )),
222
+ );
223
+ });
224
+ }
225
+
226
+ /**
227
+ * The synced list for Tab: asked of the daemon, which must already be running, within a time limit, so Tab shows
228
+ * why it has nothing to offer rather than hanging.
229
+ */
230
+ const listForTab = pipe(
231
+ Effect.gen(function* () {
232
+ return yield* (yield* DaemonControl).listSyncedSkills();
233
+ }),
234
+ Effect.timeoutOrElse({
235
+ duration: `${TAB_TIME_LIMIT_SECONDS} seconds`,
236
+ orElse: () => Effect.fail(new DaemonFailed({ message: `the skill-sync daemon did not answer within ${TAB_TIME_LIMIT_SECONDS} seconds` })),
237
+ }),
238
+ );
239
+
240
+ function openBrowser(url: string): void {
241
+ const command = process.platform === "darwin" ? "open"
242
+ : process.platform === "win32" ? "cmd"
243
+ : "xdg-open";
244
+ const args = process.platform === "win32" ? ["/c", "start", "", url] : [url];
245
+ // A machine with no desktop has no opener: the address printed above is how it signs in.
246
+ const opener = spawn(command, args, { stdio: "ignore", detached: true });
247
+ opener.on("error", () => undefined);
248
+ opener.unref();
249
+ }
@@ -0,0 +1,20 @@
1
+ /** Texts kept only until they are done with, one file each by name: the words of what is waiting to be delivered or posted. */
2
+ import fs from 'node:fs';
3
+ import path from 'node:path';
4
+
5
+ export interface IHeld {
6
+ readonly write: (input: { readonly name: string; readonly text: string }) => void;
7
+ readonly read: (name: string) => string;
8
+ readonly remove: (name: string) => void;
9
+ }
10
+
11
+ export const heldIn = (folder: string): IHeld => ({
12
+ write: ({ name, text }) => {
13
+ fs.mkdirSync(folder, { recursive: true, mode: 0o700 });
14
+ const file = path.join(folder, name);
15
+ fs.writeFileSync(`${file}.new`, text);
16
+ fs.renameSync(`${file}.new`, file);
17
+ },
18
+ read: (name) => fs.readFileSync(path.join(folder, name), 'utf8'),
19
+ remove: (name) => { fs.rmSync(path.join(folder, name), { force: true }); },
20
+ });
@@ -0,0 +1,5 @@
1
+ import { createHash } from 'node:crypto';
2
+
3
+ /** The key of something found or made: safe to compare in any case (the platform matches a task's item so, and Google's ids are case-sensitive). Pure. */
4
+ export const keyOf = (input: { readonly of: string; readonly id: string }): string =>
5
+ createHash('sha256').update(`${input.of}\n${input.id}`).digest('hex').slice(0, 24);
@@ -0,0 +1,39 @@
1
+ /** WHAT AN ANSWERING THREAD IS TOLD: each thing left for it, its conversation, the protocol, and the command that replies there. Pure. */
2
+ import { ACKNOWLEDGEMENT, AGENT_PREFIX, PLAN, withoutTag } from './protocol';
3
+ import { isOrderKind, type SourceEvent } from './source/interface';
4
+
5
+ const quoted = (text: string) => (text.trim() === '' ? '> (no text)' : text.trim().split('\n').map((line) => `> ${line}`).join('\n'));
6
+
7
+ const item = (event: SourceEvent, i: number): string => {
8
+ const earlier = (event.conversation ?? []).slice(0, -1);
9
+ return [
10
+ `${i + 1}. ${event.kind}${event.where === null ? '' : ` on ${event.where.split('\n').join(' ')}`}: ${event.url}`,
11
+ ...(earlier.length === 0 ? [] : ['Its conversation so far:', ...earlier.map((p) => quoted(`${p.author}: ${p.text}`)), 'And now:']),
12
+ quoted(event.text),
13
+ event.kind === 'plan rejected' ? 'Post nothing for this one.' : `${event.kind === 'plan approved' ? 'When it is done, edit the acknowledgement' : 'Reply'} with: skill-sync reply ${event.key} <file holding your words>`,
14
+ ].join('\n');
15
+ };
16
+
17
+ /** One target's message for what was found for it, oldest first. It never holds the bare tag. */
18
+ export const deliveryMessage = (input: { readonly events: ReadonlyArray<SourceEvent>; readonly tag: string }): string => {
19
+ const { events, tag } = input;
20
+ const [first] = events;
21
+ const onPulls = first!.target.kind === 'pull request';
22
+ const kinds = new Set(events.map((e) => e.kind));
23
+ return withoutTag({ tag, text: [
24
+ `New comments for you on "${first!.title}"${onPulls && first!.target.kind === 'pull request' ? ` (${first!.target.url})` : ''}, from skill-sync's comment watch.`,
25
+ `Each item is one conversation, and several can go on at once.${onPulls ? " Read the item's whole conversation on GitHub first, with your earlier replies in it." : ''} Then:`,
26
+ ...(events.some((e) => isOrderKind(e.kind)) ? [
27
+ '- One that asks a question: reply with the answer.',
28
+ `- One that asks for a change: don't make it yet. Reply with your plan, starting ${PLAN}, and stop. ${onPulls ? 'They react 👍 to approve it or 👎 to reject it' : 'They reply "yes" to approve it'}, and you are told which.`,
29
+ `- A plan is always a reply of its own. Where you have an answer and a plan, post two replies, the answer first.`,
30
+ ] : []),
31
+ ...(kinds.has('plan approved') ? [
32
+ `- plan approved: "${AGENT_PREFIX} ${ACKNOWLEDGEMENT}" is already posted there. Make the change your plan describes and push it. Then edit that acknowledgement with the command under the item, so it reads "Done in <commit link>" and one sentence on what changed. Post no other reply.`,
33
+ ] : []),
34
+ ...(kinds.has('plan rejected') ? ['- plan rejected: change nothing and post nothing. Their next comment in that conversation is their feedback.'] : []),
35
+ `Write only your words in the file: the command starts them with "${AGENT_PREFIX}", links what they answer where that is needed, and posts them once however often you run it. It prints the link to your reply, or why it was refused. Post nothing there any other way.`,
36
+ '',
37
+ ...events.map(item),
38
+ ].join('\n') });
39
+ };
@@ -0,0 +1,17 @@
1
+ /** WHERE ONE MACHINE KEEPS THE COMMENT WATCH'S FILES: its own folder, so its database and engine share nothing with skill refinement's. */
2
+ import path from 'node:path';
3
+
4
+ /** The workflow's code, which step records link their definitions to. */
5
+ export const CODE_ROOT = import.meta.dir;
6
+
7
+ export const watchFolder = (home: string) => path.join(home, '.jive', 'comment-watch');
8
+ /** The platform's database, which also holds the watch's own tables (`store/`). */
9
+ export const watchDatabase = (folder: string) => path.join(folder, 'comment-watch.db');
10
+ /** The workflow engine's own database. */
11
+ export const watchEngineDatabase = (folder: string) => path.join(folder, 'comment-watch-engine.db');
12
+ /** The platform's texts, by content hash. */
13
+ export const watchTexts = (folder: string) => path.join(folder, 'texts');
14
+ /** What is held until it is delivered or posted: an event, a delivery, a reply, one file each, then deleted. */
15
+ export const watchHeld = (folder: string) => path.join(folder, 'held');
16
+ /** Where T3 is told of what was found: webhook addresses, each its own credential, apart from the settings. */
17
+ export const t3File = (home: string) => path.join(home, '.jive', 'comment-watch-t3.json');
@@ -0,0 +1,69 @@
1
+ /**
2
+ * THE COMMENT WATCH ON THE WORKFLOW PLATFORM: the facts the platform cannot know about it, and where its records live, a
3
+ * database and an engine of its own beside skill refinement's.
4
+ */
5
+ import { createWorkflowPlatform, sqliteStorage, type ProcessIdentity, type RunLightNow, type TextStore } from '@jive-sh/workflow-platform';
6
+ import fs from 'node:fs';
7
+ import os from 'node:os';
8
+ import path from 'node:path';
9
+ import { CODE_ROOT, watchDatabase, watchEngineDatabase, watchTexts } from './paths';
10
+
11
+ const runLightNow: RunLightNow = (command, options) => {
12
+ const r = Bun.spawnSync([...command], { stdout: 'pipe', stderr: 'pipe', ...(options?.env === undefined ? {} : { env: { ...process.env, ...options.env } }) });
13
+ return { code: r.exitCode, stdout: r.stdout.toString(), stdoutBytes: new Uint8Array(r.stdout), stderr: r.stderr.toString() };
14
+ };
15
+
16
+ /** When a process started, in unix seconds, as `ps` reports it; none for a process that is gone. */
17
+ const startedAtOf = (pid: number): number | null => {
18
+ const r = runLightNow(['ps', '-o', 'lstart=', '-p', String(pid)]);
19
+ const at = Date.parse(r.stdout.trim());
20
+ return r.code === 0 && !Number.isNaN(at) ? Math.floor(at / 1000) : null;
21
+ };
22
+
23
+ let self: ProcessIdentity | null = null;
24
+ const thisProcess = (): ProcessIdentity => {
25
+ self ??= { pid: process.pid, startedAt: startedAtOf(process.pid) ?? Math.floor(Date.now() / 1000) };
26
+ return self;
27
+ };
28
+ const isAlive = (p: ProcessIdentity): boolean => startedAtOf(p.pid) === p.startedAt;
29
+
30
+ /** Texts by content hash, one file each: each reply's. */
31
+ export const textStore = (folder: string): TextStore => ({
32
+ write: (text) => {
33
+ const sha = new Bun.CryptoHasher('sha256').update(text).digest('hex');
34
+ fs.mkdirSync(folder, { recursive: true });
35
+ const file = path.join(folder, sha);
36
+ if (!fs.existsSync(file)) {
37
+ fs.writeFileSync(`${file}.new`, text);
38
+ fs.renameSync(`${file}.new`, file);
39
+ }
40
+ return sha;
41
+ },
42
+ read: (sha) => {
43
+ const text = fs.readFileSync(path.join(folder, sha), 'utf8');
44
+ if (new Bun.CryptoHasher('sha256').update(text).digest('hex') !== sha) throw new Error(`text ${sha} does not match its hash`);
45
+ return text;
46
+ },
47
+ });
48
+
49
+ export const commentWatchPlatform = (folder: string) => {
50
+ fs.mkdirSync(folder, { recursive: true });
51
+ return createWorkflowPlatform<never>({
52
+ project: {
53
+ sourceRoot: CODE_ROOT,
54
+ tree: { root: folder, snapshots: path.join(folder, 'step-files'), notTree: [] },
55
+ texts: textStore(watchTexts(folder)),
56
+ runLightNow,
57
+ processes: { thisProcess, isAlive },
58
+ stepRecordVariable: 'COMMENT_WATCH_STEP_RECORD',
59
+ isTransientFailure: (e) => String(e).includes('database is locked'),
60
+ cpu: { limit: () => os.cpus().length, newestUse: () => null },
61
+ },
62
+ storage: sqliteStorage({
63
+ stepRecordsFile: () => watchDatabase(folder),
64
+ engineFile: () => watchEngineDatabase(folder),
65
+ budgetsFile: () => watchDatabase(folder),
66
+ processes: { thisProcess, isAlive },
67
+ }),
68
+ });
69
+ };