@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,115 @@
1
+ /**
2
+ * DELIVER COMMENTS: one run a target (a pull request's T3 thread, a project's command thread), in code. What was found for it
3
+ * since goes as one message. Where a plan was approved, code first posts the acknowledgement the agent later edits into its
4
+ * "Done in". An approval goes once its acknowledgement is there: one that could not be posted yet waits for it, and nothing
5
+ * else does; one the place refused is recorded so, and is never delivered.
6
+ *
7
+ * Exactly once: a delivery is recorded with what is in it before T3 is told, and as told after. One cut off between is told
8
+ * again under the same id, which T3 drops if it has it.
9
+ */
10
+ import { describeFailure, OutsideServiceUnavailable, RUN_ENDS, RUN_STARTS, A_STEP_FAILS, type WorkflowPlatform } from '@jive-sh/workflow-platform';
11
+ import { Effect, Option, pipe, Result, Schema } from 'effect';
12
+ import { deliveryMessage } from '../message';
13
+ import { ACKNOWLEDGEMENT, asAgents } from '../protocol';
14
+ import type { ICommentSource, SourceEvent } from '../source/interface';
15
+ import type { ICommentStore } from '../store/interface';
16
+ import type { ITold } from '../t3';
17
+ import { FIND_WORKFLOW } from './find';
18
+ import { postOnce } from './post-once';
19
+
20
+ export const DELIVER_WORKFLOW = 'Deliver comments';
21
+
22
+ const Prepared = Schema.Struct({ delivery: Schema.NullOr(Schema.String), events: Schema.Finite, waiting: Schema.Array(Schema.String) });
23
+ const DeliverOutcome = Schema.Struct({ item: Schema.NullOr(Schema.String), outcome: Schema.String, finished: Schema.Boolean });
24
+
25
+ /** What an acknowledgement says: its words, and where the place can hide one, the line it is known by. */
26
+ export const acknowledgementText = (input: { readonly event: Pick<SourceEvent, 'opening' | 'acknowledgementLine'>; readonly text: string; readonly tag: string }): string =>
27
+ [asAgents({ text: input.text, opening: input.event.opening, tag: input.tag }), ...(input.event.acknowledgementLine === null ? [] : [input.event.acknowledgementLine])].join('\n\n');
28
+
29
+ export const defineDeliver = (deps: {
30
+ readonly platform: WorkflowPlatform<never>;
31
+ readonly sources: ReadonlyArray<ICommentSource>;
32
+ readonly store: ICommentStore;
33
+ readonly told: ITold;
34
+ readonly tag: string;
35
+ /** A target could not be told now: it rests until the next turn, so a service that is down is not asked again at once. */
36
+ readonly rests: (target: string) => void;
37
+ /** Unix seconds. */
38
+ readonly now: () => number;
39
+ }) => {
40
+ const { defineStep, defineWorkflow, queueNow } = deps.platform.steps;
41
+ const { store, tag, now } = deps;
42
+ const at = import.meta.path;
43
+
44
+ const PICK = defineStep({ name: 'Pick', runs: 'deterministic', at, description: 'Takes the head of the queue of targets with something to deliver.', success: Schema.Option(Schema.String), subject: (o) => Option.getOrNull(o) });
45
+ const PREPARE = defineStep({ name: 'Prepare', runs: 'deterministic', at, description: 'Acknowledges each approved plan, and puts what the target has not been told in one delivery.', success: Prepared, reason: (p) => [`${p.events} in the delivery`, ...p.waiting].join('; ') });
46
+ const TELL = defineStep({ name: 'Tell', runs: 'deterministic', at, description: 'Tells T3, by its webhook, and records it.', success: Schema.String, reason: (id) => `delivered ${id}` });
47
+
48
+ const pick = (run: string) => Effect.map(queueNow({ workflow: DELIVER_WORKFLOW, run }), (queue) => Option.fromNullishOr(queue[0]?.ref.item));
49
+
50
+ const acknowledged = (event: SourceEvent) => Effect.gen(function* () {
51
+ const id = yield* store.addPost({ key: event.key, purpose: 'acknowledgement', text: acknowledgementText({ event, text: ACKNOWLEDGEMENT, tag }), at: now() });
52
+ return yield* postOnce(deps)(id);
53
+ });
54
+
55
+ const prepare = (target: string) => Effect.gen(function* () {
56
+ // One prepared before and not told is told first: what is in it is in no other.
57
+ const before = yield* store.untold(target);
58
+ if (Option.isSome(before)) return { delivery: before.value.id, events: 0, waiting: [] };
59
+ const ready: SourceEvent[] = [];
60
+ const waiting: string[] = [];
61
+ for (const { event } of yield* store.undelivered(target)) {
62
+ if (event.kind !== 'plan approved') { ready.push(event); continue; }
63
+ const result = yield* Effect.result(acknowledged(event));
64
+ if (Result.isSuccess(result) && (result.success.outcome === 'posted' || result.success.outcome === 'already there')) { ready.push(event); continue; }
65
+ // Refused, it is recorded with its post, and `undelivered` gives it no more.
66
+ if (Result.isSuccess(result) && result.success.outcome === 'refused') waiting.push(`an approval is not delivered: its acknowledgement was refused: ${result.success.why}`);
67
+ else waiting.push(`an approval waits for its acknowledgement: ${Result.isSuccess(result) ? result.success.why : describeFailure(result.failure)}`);
68
+ }
69
+ if (ready.length === 0) return { delivery: null, events: 0, waiting };
70
+ const delivery = yield* store.prepare({ target: ready[0]!.target, events: ready.map((e) => e.key), message: deliveryMessage({ events: ready, tag }), at: now() });
71
+ return { delivery: delivery.id, events: ready.length, waiting };
72
+ });
73
+
74
+ const tell = (target: string) => Effect.gen(function* () {
75
+ const delivery = yield* store.untold(target);
76
+ if (Option.isNone(delivery)) return 'nothing: it was told';
77
+ yield* pipe(Effect.gen(() => deps.told.tell(delivery.value)), Effect.catchTag('ServiceUnavailable', (e) => Effect.fail(new OutsideServiceUnavailable({ service: e.service, reason: e.reason }))));
78
+ yield* store.recordTold({ id: delivery.value.id, at: now() });
79
+ console.log(`[comment watch] delivered ${delivery.value.id}`);
80
+ return delivery.value.id;
81
+ });
82
+
83
+ const workflow = defineWorkflow<typeof DeliverOutcome.Type>({
84
+ at, item: 'target', finishedWord: 'told', description: 'Tells the T3 thread that answers in a place what was found for it.',
85
+ steps: () => [PICK, PREPARE, TELL],
86
+ fedBy: [FIND_WORKFLOW],
87
+ picksQueueHead: true,
88
+ pending: () => Effect.orElseSucceed(Effect.gen(function* () { return { lines: [{ label: 'targets to tell', items: yield* store.toDeliver() }], waits: [] }; }), () => ({ lines: [], waits: [] })),
89
+ outcomes: (o) => (o.item === null ? [] : [{ subject: o.item, outcome: o.outcome, finished: o.finished }]),
90
+ graph: () => [
91
+ { from: RUN_STARTS, to: PICK.name, when: 'something was found' },
92
+ { from: PICK.name, to: PREPARE.name, when: 'a target picked' },
93
+ { from: PICK.name, to: RUN_ENDS, when: 'none left' },
94
+ { from: PREPARE.name, to: TELL.name, when: 'there is a delivery' },
95
+ { from: PREPARE.name, to: RUN_ENDS, when: 'everything waits for its acknowledgement' },
96
+ { from: TELL.name, to: RUN_ENDS, when: 'always' },
97
+ { from: A_STEP_FAILS, to: RUN_ENDS, when: 'a step fails' },
98
+ ],
99
+ })(DELIVER_WORKFLOW, { payload: { run: Schema.String }, idempotencyKey: ({ run }) => run, success: DeliverOutcome, error: Schema.String });
100
+
101
+ const layer = workflow.toLayer((payload) => Effect.gen(function* () {
102
+ const { run } = payload as { readonly run: string };
103
+ const picked = yield* PICK.run(pick(run));
104
+ if (Option.isNone(picked)) return { item: null, outcome: 'nothing to deliver', finished: false };
105
+ const orRest = <A, R>(step: Effect.Effect<A, string, R>) => Effect.tapCause(step, () => Effect.sync(() => deps.rests(picked.value)));
106
+ const prepared = yield* orRest(PREPARE.run(prepare(picked.value)));
107
+ if (prepared.delivery === null) deps.rests(picked.value);
108
+ // Not a failed try: what it waits for is tried again by the next run.
109
+ if (prepared.delivery === null) return { item: picked.value, outcome: prepared.waiting.join('; '), finished: true };
110
+ const id = yield* orRest(TELL.run(tell(picked.value)));
111
+ return { item: picked.value, outcome: `delivered ${id}`, finished: true };
112
+ }));
113
+
114
+ return { workflow, layer };
115
+ };
@@ -0,0 +1,78 @@
1
+ /**
2
+ * FIND COMMENTS: one step in code, each turn of its schedule and as the daemon starts. It reads every source the settings
3
+ * name, queues each new comment for an agent once, and at once shows 👀 on it, before anything waits on a thread or an agent.
4
+ *
5
+ * Exactly once rests on two records made together (`ICommentStore.take`): the event, under a key of its own, and the source's
6
+ * cursor. A listing that fails moves neither, so the next turn reads the same stretch again; a listing that gives an event
7
+ * twice adds nothing. What an agent wrote is never queued.
8
+ */
9
+ import { describeFailure, RUN_ENDS, RUN_STARTS, A_STEP_FAILS, type WorkflowPlatform } from '@jive-sh/workflow-platform';
10
+ import { Cause, Effect, Exit, Schema } from 'effect';
11
+ import { isOrderKind, Refused, ServiceUnavailable, SignInExpired, type ICommentSource, type Listed } from '../source/interface';
12
+ import type { Found, ICommentStore } from '../store/interface';
13
+
14
+ export const FIND_WORKFLOW = 'Find comments';
15
+
16
+ const Read = Schema.Struct({ queued: Schema.Finite, notes: Schema.Array(Schema.String) });
17
+
18
+ /** Why something found is or is not queued. A post this machine made is an agent's even if a person has since edited its 🤖: away. */
19
+ export const classify = (input: { readonly source: ICommentSource; readonly store: ICommentStore }) => ({ event, before }: Listed): Found =>
20
+ (isOrderKind(event.kind) && input.store.postedHere({ source: input.source.id, post: event.post }) ? 'agent' : before ? 'before' : 'queued');
21
+
22
+ export const defineFind = (deps: {
23
+ readonly platform: WorkflowPlatform<never>;
24
+ readonly sources: ReadonlyArray<ICommentSource>;
25
+ readonly store: ICommentStore;
26
+ /** Unix seconds. */
27
+ readonly now: () => number;
28
+ /** Something was queued: it can be delivered now, whatever becomes of the rest of the run. */
29
+ readonly onQueued: () => void;
30
+ }) => {
31
+ const { defineStep, defineWorkflow } = deps.platform.steps;
32
+ const at = import.meta.path;
33
+
34
+ /** One source read and taken, and 👀 shown for what it holds. */
35
+ const readSource = (source: ICommentSource) => Effect.gen(function* () {
36
+ const listing = yield* source.newSince(yield* deps.store.cursorOf(source.id));
37
+ const taken = yield* deps.store.take({ source: source.id, listing, classify: classify({ source, store: deps.store }), at: deps.now() });
38
+ // 👀 is asked for first, and the delivery starts without its answer: a service that gives none holds nothing up.
39
+ const { shown } = yield* Effect.all({
40
+ shown: Effect.gen(() => source.showReceived({ isQueued: (key) => deps.store.isQueued(key), isAnswered: (key) => deps.store.isAnswered(key) })),
41
+ delivering: Effect.sync(() => { if (taken.length > 0) deps.onQueued(); }),
42
+ }, { concurrency: 'unbounded' });
43
+ return { queued: taken.length, notes: [...listing.notes, ...(shown.changed === 0 ? [] : [`${shown.changed} 👀 changed`]), ...shown.failed].map((n) => `${source.id}: ${n}`) };
44
+ });
45
+
46
+ /** Every source, each whatever becomes of the others; the step fails, once they are all done, naming the ones that did. */
47
+ const find = Effect.gen(function* () {
48
+ const read = yield* Effect.forEach(deps.sources, (source) => Effect.map(Effect.exit(readSource(source)), (exit) => ({ source, exit })), { concurrency: 4 });
49
+ const failed: string[] = [];
50
+ for (const { source, exit } of read) {
51
+ if (Exit.isSuccess(exit)) continue;
52
+ if (Cause.hasInterrupts(exit.cause)) return yield* Effect.interrupt;
53
+ const failure = Cause.squash(exit.cause);
54
+ const why = describeFailure(failure);
55
+ const plain = failure instanceof SignInExpired || failure instanceof ServiceUnavailable || failure instanceof Refused ? failure.plain : 'the daemon hit a fault of its own; its log says which';
56
+ failed.push(`${source.id}: ${why}`);
57
+ const wasWorking = yield* deps.store.listingFailed({ source, why, plain, at: deps.now() });
58
+ if (wasWorking) console.error(`[comment watch] ${source.id} could not be read, and is tried again each turn: ${why}`);
59
+ }
60
+ const done = read.flatMap(({ exit }) => (Exit.isSuccess(exit) ? [exit.value] : []));
61
+ const queued = done.reduce((n, d) => n + d.queued, 0);
62
+ if (queued > 0) console.log(`[comment watch] queued ${queued} new comment${queued === 1 ? '' : 's'}`);
63
+ if (failed.length > 0) return yield* Effect.fail(`${queued} queued; not read: ${failed.join('; ')}`);
64
+ return { queued, notes: done.flatMap((d) => d.notes) };
65
+ });
66
+
67
+ const FIND = defineStep({ name: 'Find', runs: 'deterministic', shared: true, at, description: 'Reads every source the settings name, queues each new comment for an agent once, and shows 👀 on it until it is answered.', success: Read, reason: (r) => [`${r.queued} queued`, ...r.notes].join('; ') });
68
+ const workflow = defineWorkflow({
69
+ at, item: null, description: 'Reads every place this machine watches and queues each new comment for an agent.', steps: () => [FIND],
70
+ graph: () => [
71
+ { from: RUN_STARTS, to: FIND.name, when: 'each turn' },
72
+ { from: FIND.name, to: RUN_ENDS, when: 'every source was read' },
73
+ { from: A_STEP_FAILS, to: RUN_ENDS, when: 'a source could not be read: the next turn reads it from where it was' },
74
+ ],
75
+ })(FIND_WORKFLOW, { payload: { turn: Schema.Finite }, idempotencyKey: ({ turn }) => String(turn), success: Read, error: Schema.String });
76
+
77
+ return { workflow, layer: workflow.toLayer(() => FIND.run(find)) };
78
+ };
@@ -0,0 +1,72 @@
1
+ /**
2
+ * POSTING ONCE, whatever is lost on the way. Neither service takes a key that would make a post idempotent, so the
3
+ * conversation is the record of what landed: before a post is made, the posts there with the same words are noted, and one
4
+ * that was not there then is it. A try whose answer was lost is not looked for until the conversation is sure to show it.
5
+ *
6
+ * An acknowledgement that ends with a hidden line is known by that line instead, through the agent's edit of it and without
7
+ * any record here.
8
+ */
9
+ import { OutsideServiceUnavailable } from '@jive-sh/workflow-platform';
10
+ import { Effect, Option, pipe, Schema } from 'effect';
11
+ import { holdsAcknowledgementLine, sameWords } from '../protocol';
12
+ import { ServiceUnavailable, type ICommentSource, type Refused, type SignInExpired } from '../source/interface';
13
+ import type { ICommentStore, WatchStoreError } from '../store/interface';
14
+
15
+ export const Made = Schema.Struct({ outcome: Schema.Literals(['posted', 'already there', 'refused', 'held']), post: Schema.String, url: Schema.String, why: Schema.String });
16
+ export type Made = typeof Made.Type;
17
+
18
+ const held = (why: string): Made => ({ outcome: 'held', post: '', url: '', why });
19
+
20
+ /** Makes a post, or finds it made. */
21
+ export const postOnce = (deps: { readonly sources: ReadonlyArray<ICommentSource>; readonly store: ICommentStore; readonly now: () => number }) => (id: string): Effect.Effect<Made, OutsideServiceUnavailable | WatchStoreError> => {
22
+ const { store, now } = deps;
23
+ const refused = (why: string) => Effect.as(Effect.gen(() => store.recordRefused({ id, why })), { outcome: 'refused' as const, post: '', url: '', why });
24
+
25
+ const make = Effect.gen(function* (): Effect.fn.Return<Made, SignInExpired | ServiceUnavailable | Refused | WatchStoreError> {
26
+ const post = yield* store.post({ id, now: now() });
27
+ if (Option.isSome(post.posted)) return { outcome: 'already there', ...post.posted.value, why: 'it was recorded as posted' };
28
+ if (post.refused !== null) return { outcome: 'refused', post: '', url: '', why: post.refused };
29
+ const source = deps.sources.find((s) => s.id === post.event.source);
30
+ if (source === undefined) return yield* refused(`this machine no longer watches ${post.event.url}`);
31
+ const bytes = Buffer.byteLength(post.text);
32
+ if (Option.isSome(source.maxPostBytes) && bytes > source.maxPostBytes.value) return yield* refused(`it is ${bytes} bytes as posted, and no more than ${source.maxPostBytes.value} can be`);
33
+
34
+ if (post.purpose === 'edit') {
35
+ // Edited again to the same words, it reads the same: there is nothing to find.
36
+ const acknowledgement = yield* store.acknowledgementOf(post.event.key);
37
+ if (Option.isNone(acknowledgement)) return yield* refused('the plan has no acknowledgement to edit');
38
+ yield* source.edit(post.event, acknowledgement.value, post.text);
39
+ yield* store.recordPosted({ id, post: acknowledgement.value, url: post.event.url, at: now() });
40
+ return { outcome: 'posted', post: acknowledgement.value, url: post.event.url, why: '' };
41
+ }
42
+ if (post.mayHaveJustLanded) return held('it was tried a moment ago, and its conversation may not show it yet');
43
+ const line = post.event.acknowledgementLine;
44
+ const hidden = post.purpose === 'acknowledgement' ? line : null;
45
+ const posts = yield* source.thread(post.event);
46
+ const same = posts.filter((p) => p.mine && (hidden === null ? sameWords(p.text, post.text) : holdsAcknowledgementLine({ text: p.text, line: hidden })));
47
+ const landed = hidden !== null ? same[0] : post.thereBefore === null ? undefined : same.find((p) => !post.thereBefore!.includes(p.post) && !store.postedHere({ source: source.id, post: p.post }));
48
+ if (landed !== undefined) {
49
+ yield* store.recordPosted({ id, post: landed.post, url: landed.url, at: now() });
50
+ return { outcome: 'already there', post: landed.post, url: landed.url, why: 'an earlier try posted it' };
51
+ }
52
+ yield* store.recordPosting({ id, thereBefore: same.map((p) => p.post), at: now() });
53
+ const made = yield* pipe(
54
+ Effect.gen(() => source.reply(post.event, post.text)),
55
+ // It was not made: nothing to look for.
56
+ Effect.tapErrorTag(['Refused', 'SignInExpired'], () => Effect.gen(() => store.recordNotPosted(id))),
57
+ );
58
+ yield* store.recordPosted({ id, post: made.post, url: made.url, at: now() });
59
+ console.log(`[comment watch] posted: ${made.url}`);
60
+ return { outcome: 'posted', post: made.post, url: made.url, why: '' };
61
+ });
62
+
63
+ return pipe(
64
+ make,
65
+ Effect.catchTags({
66
+ Refused: (e) => refused(e.plain === e.reason ? e.plain : `${e.plain} (${e.reason})`),
67
+ // A service that cannot now is no try of the post: the platform counts none, and it is tried again.
68
+ SignInExpired: (e) => Effect.fail(new OutsideServiceUnavailable({ service: e.service, reason: `its sign-in expired: ${e.reason}` })),
69
+ ServiceUnavailable: (e) => Effect.fail(new OutsideServiceUnavailable({ service: e.service, reason: e.reason })),
70
+ }),
71
+ );
72
+ };
@@ -0,0 +1,56 @@
1
+ /** POST REPLY: one run a post an agent handed over, in code: its reply in a conversation, or its edit of an acknowledgement (`post-once.ts`). */
2
+ import { RUN_ENDS, RUN_STARTS, A_STEP_FAILS, type WorkflowPlatform } from '@jive-sh/workflow-platform';
3
+ import { Effect, Option, Schema } from 'effect';
4
+ import type { ICommentSource } from '../source/interface';
5
+ import type { ICommentStore } from '../store/interface';
6
+ import { Made, postOnce } from './post-once';
7
+
8
+ export const POST_WORKFLOW = 'Post reply';
9
+
10
+ const PostOutcome = Schema.Struct({ item: Schema.NullOr(Schema.String), outcome: Schema.String, finished: Schema.Boolean, blocked: Schema.NullOr(Schema.String) });
11
+
12
+ export const definePost = (deps: {
13
+ readonly platform: WorkflowPlatform<never>;
14
+ readonly sources: ReadonlyArray<ICommentSource>;
15
+ readonly store: ICommentStore;
16
+ /** A post could not be made now: it rests until the next turn, so a service that is down is not asked again at once. */
17
+ readonly rests: (post: string) => void;
18
+ /** Unix seconds. */
19
+ readonly now: () => number;
20
+ }) => {
21
+ const { defineStep, defineWorkflow, queueNow } = deps.platform.steps;
22
+ const at = import.meta.path;
23
+
24
+ const PICK = defineStep({ name: 'Pick', runs: 'deterministic', at, description: 'Takes the head of the queue of posts to make.', success: Schema.Option(Schema.String), subject: (o) => Option.getOrNull(o) });
25
+ const POST = defineStep({ name: 'Post', runs: 'deterministic', at, description: "Makes the post in its comment's conversation, unless it is there already, and records it.", success: Made, reason: (p) => `${p.outcome}${p.why === '' ? '' : `: ${p.why}`}` });
26
+
27
+ const pick = (run: string) => Effect.map(queueNow({ workflow: POST_WORKFLOW, run }), (queue) => Option.fromNullishOr(queue[0]?.ref.item));
28
+
29
+ const workflow = defineWorkflow<typeof PostOutcome.Type>({
30
+ at, item: 'post', finishedWord: 'posted', description: "Makes each post an agent hands over, once, in its comment's conversation.",
31
+ steps: () => [PICK, POST],
32
+ picksQueueHead: true,
33
+ pending: () => Effect.orElseSucceed(Effect.gen(function* () {
34
+ return { lines: [{ label: 'posts to make', items: yield* deps.store.toPost(deps.now()) }], waits: [] };
35
+ }), () => ({ lines: [], waits: [] })),
36
+ outcomes: (o) => (o.item === null ? [] : [{ subject: o.item, outcome: o.outcome, finished: o.finished, ...(o.blocked === null ? {} : { blocked: o.blocked }) }]),
37
+ graph: () => [
38
+ { from: RUN_STARTS, to: PICK.name, when: 'a post is handed over' },
39
+ { from: PICK.name, to: POST.name, when: 'a post picked' },
40
+ { from: PICK.name, to: RUN_ENDS, when: 'none left to make' },
41
+ { from: POST.name, to: RUN_ENDS, when: 'always' },
42
+ { from: A_STEP_FAILS, to: RUN_ENDS, when: 'a step fails' },
43
+ ],
44
+ })(POST_WORKFLOW, { payload: { run: Schema.String }, idempotencyKey: ({ run }) => run, success: PostOutcome, error: Schema.String });
45
+
46
+ const layer = workflow.toLayer((payload) => Effect.gen(function* () {
47
+ const { run } = payload as { readonly run: string };
48
+ const picked = yield* PICK.run(pick(run));
49
+ if (Option.isNone(picked)) return { item: null, outcome: 'nothing to post', finished: false, blocked: null };
50
+ const made = yield* Effect.tapCause(POST.run(postOnce(deps)(picked.value)), () => Effect.sync(() => deps.rests(picked.value)));
51
+ const finished = made.outcome === 'posted' || made.outcome === 'already there';
52
+ return { item: picked.value, outcome: `${made.outcome}${made.why === '' ? '' : `: ${made.why}`}`, finished, blocked: made.outcome === 'refused' ? made.why : null };
53
+ }));
54
+
55
+ return { workflow, layer };
56
+ };
@@ -0,0 +1,172 @@
1
+ import { createHash } from "node:crypto";
2
+ import { mkdirSync, readFileSync, writeFileSync, existsSync, readdirSync, rmSync, statSync } from "node:fs";
3
+ import { homedir, hostname, userInfo } from "node:os";
4
+ import { join, relative, sep } from "node:path";
5
+
6
+ /**
7
+ * Per-machine settings, sync state and the sync token, all under `~/.jive/`.
8
+ *
9
+ * A file rather than environment variables: the endpoint and which machine this is differ per computer
10
+ * and have to survive a login, which is exactly what a config file is for and exactly what an environment
11
+ * variable is not. Which folders to sync is not in here: they are detected, and the choice to leave one
12
+ * out is kept on the server so the dashboard can change it and a reinstalled daemon still remembers it.
13
+ */
14
+
15
+ const JIVE_HOME = join(homedir(), ".jive");
16
+ export const CONFIG_PATH = join(JIVE_HOME, "skill-sync.json");
17
+ const STATE_PATH = join(JIVE_HOME, "skill-sync-state.json");
18
+ /**
19
+ * The sync token, written at sign-in so the daemon is still signed in after a restart, a reboot or an
20
+ * upgrade. An ordinary file: anything that can read the home directory can copy the token, and the
21
+ * dashboard can revoke it.
22
+ */
23
+ export const TOKEN_PATH = join(JIVE_HOME, "skill-sync-token.json");
24
+ /**
25
+ * How the CLI reaches the running daemon: a Unix socket in `~/.jive/`, or a named pipe on Windows. Only
26
+ * this user can open either, which is what lets the CLI hand the daemon work that involves the token.
27
+ */
28
+ export const CONTROL_SOCKET = process.platform === "win32"
29
+ ? `\\\\.\\pipe\\jive-skill-sync-${userInfo().username}`
30
+ : join(JIVE_HOME, "skill-sync.sock");
31
+
32
+ /** Managed by Claude's own cloud sync; see `Settings.exclude`. */
33
+ const DEFAULT_EXCLUDE = ["synced"] as const;
34
+
35
+ /** What `~/.jive/skill-sync.json` holds: nothing secret, so it can live in a file. */
36
+ export interface Settings {
37
+ readonly endpoint: string;
38
+ /**
39
+ * Top-level directory names under each synced folder to leave alone.
40
+ *
41
+ * `synced` holds the skills Claude already pulls from the cloud itself. Syncing them here would mean
42
+ * two systems writing the same files, each undoing the other, and none of them are yours to edit.
43
+ * The list applies to every detected folder, so in Codex's and Grok's skills folders it keeps a skill
44
+ * named `synced` from syncing.
45
+ */
46
+ readonly exclude: ReadonlyArray<string>;
47
+ /** Names this machine on the server: on the dashboard, and as the machine each edit came from. */
48
+ readonly machine: string;
49
+ }
50
+
51
+ /** Settings plus the token, which the daemon has once signed in. */
52
+ export interface Config extends Settings {
53
+ readonly token: string;
54
+ }
55
+
56
+ /** Sync progress for one folder. Each folder syncs with the server on its own, so each has its own. */
57
+ export interface State {
58
+ /** Highest server sequence number already applied. */
59
+ cursor: number;
60
+ /** Last hash this machine agreed with the server on, per relative path. Absent means never synced. */
61
+ known: Record<string, string>;
62
+ /** The synced list as of last cycle, to notice a skill being added to it. */
63
+ skills?: string[];
64
+ }
65
+
66
+ /** Every folder's `State`, keyed by the folder's absolute path. */
67
+ export type States = Record<string, State>;
68
+
69
+ /**
70
+ * The settings, writing a template on first run. Undefined when the file lacks an endpoint or a machine
71
+ * name, which only happens if someone edited it.
72
+ */
73
+ export function loadSettings(): Settings | undefined {
74
+ if (!existsSync(CONFIG_PATH)) {
75
+ mkdirSync(JIVE_HOME, { recursive: true });
76
+ writeFileSync(CONFIG_PATH, `${JSON.stringify({
77
+ endpoint: "https://skill-sync.jive.sh",
78
+ machine: machineName(),
79
+ exclude: DEFAULT_EXCLUDE,
80
+ }, null, 2)}\n`);
81
+ }
82
+ const settings = readJson<Partial<Settings>>(CONFIG_PATH);
83
+ if (!settings.endpoint || !settings.machine) return undefined;
84
+ return { endpoint: settings.endpoint, machine: settings.machine, exclude: settings.exclude ?? DEFAULT_EXCLUDE };
85
+ }
86
+
87
+ function readJson<T>(path: string): T {
88
+ try {
89
+ return JSON.parse(readFileSync(path, "utf-8")) as T;
90
+ } catch {
91
+ return {} as T;
92
+ }
93
+ }
94
+
95
+ /**
96
+ * Every folder's sync state.
97
+ *
98
+ * Before folders were detected the file held one folder's `{ cursor, known }`, for the folder then named
99
+ * by `skillsDir` in the settings. That state is carried over to that folder: dropping it would make the
100
+ * folder look never-synced, and every file in it that differs from the server would become a conflict.
101
+ */
102
+ export function loadStates(): States {
103
+ const stored = readJson<Partial<State> & { folders?: States }>(STATE_PATH);
104
+ if (stored.folders !== undefined) return stored.folders;
105
+ const legacyFolder = readJson<{ skillsDir?: string }>(CONFIG_PATH).skillsDir;
106
+ if (legacyFolder !== undefined && stored.cursor !== undefined && stored.known !== undefined) {
107
+ return { [legacyFolder]: { cursor: stored.cursor, known: stored.known } };
108
+ }
109
+ return {};
110
+ }
111
+
112
+ /** The saved token, or undefined when this machine is signed out. */
113
+ export function loadToken(): string | undefined {
114
+ return readJson<{ token?: string }>(TOKEN_PATH).token;
115
+ }
116
+
117
+ export function saveToken(token: string): void {
118
+ mkdirSync(JIVE_HOME, { recursive: true });
119
+ writeFileSync(TOKEN_PATH, `${JSON.stringify({ token }, null, 2)}\n`);
120
+ }
121
+
122
+ export function deleteToken(): void {
123
+ rmSync(TOKEN_PATH, { force: true });
124
+ }
125
+
126
+ export function stateFor(states: States, folder: string): State {
127
+ states[folder] ??= { cursor: 0, known: {} };
128
+ return states[folder];
129
+ }
130
+
131
+ export function saveStates(states: States): void {
132
+ mkdirSync(JIVE_HOME, { recursive: true });
133
+ writeFileSync(STATE_PATH, `${JSON.stringify({ folders: states }, null, 2)}\n`);
134
+ }
135
+
136
+ /**
137
+ * A name ending in `.lock` is another program's lock, never an agent home, a skill or a skill's file.
138
+ * Claude Code locks a path by creating an empty `<path>.lock` folder beside it and removing it when done;
139
+ * counted as an agent home, `~/.claude-<name>.lock` was filled with skills and the lock could not be released.
140
+ */
141
+ export const isLock = (name: string): boolean => name.endsWith(".lock");
142
+
143
+ /** `HOSTNAME` is not set on macOS, so the template was writing "unknown" on exactly this machine. */
144
+ function machineName(): string {
145
+ return hostname().replace(/\.local$/, "").replace(/[^A-Za-z0-9-]+/g, "-") || "unknown";
146
+ }
147
+
148
+ export function hashBytes(bytes: Uint8Array): string {
149
+ return createHash("sha256").update(bytes).digest("hex");
150
+ }
151
+
152
+ /**
153
+ * Every file under a synced folder, as paths relative to it with forward slashes.
154
+ *
155
+ * Normalised because the same skill synced from Windows and macOS must be one row, not two.
156
+ */
157
+ export function listLocalFiles(folder: string, exclude: ReadonlyArray<string> = DEFAULT_EXCLUDE): string[] {
158
+ if (!existsSync(folder)) return [];
159
+
160
+ const found: string[] = [];
161
+ const walk = (dir: string, top: boolean): void => {
162
+ for (const entry of readdirSync(dir)) {
163
+ if (entry.startsWith(".") || isLock(entry)) continue;
164
+ if (top && exclude.includes(entry)) continue;
165
+ const full = join(dir, entry);
166
+ if (statSync(full).isDirectory()) walk(full, false);
167
+ else found.push(relative(folder, full).split(sep).join("/"));
168
+ }
169
+ };
170
+ walk(folder, true);
171
+ return found.sort();
172
+ }
@@ -0,0 +1,165 @@
1
+ import { createConnection, createServer, type Server, type Socket } from "node:net";
2
+ import { chmodSync, rmSync } from "node:fs";
3
+ import { Cause, Data, Effect, Queue, Stream } from "effect";
4
+ import { CONTROL_SOCKET } from "./config";
5
+ import type { Replied } from "./comment-watch/service";
6
+ import type { Watching } from "./comment-watch/watching";
7
+ import type { ListedSkill } from "./wire";
8
+
9
+ /**
10
+ * The channel between the CLI and the running daemon.
11
+ *
12
+ * The daemon owns the sync token: it claims it from the server once a passkey approves its sign-in, and keeps it in `~/.jive/`, so it never
13
+ * passes through the CLI. The CLI's `login`, `logout`, `list` and `add` are requests to the daemon over this
14
+ * channel. Messages are newline-delimited JSON; each request gets events until one that
15
+ * ends it.
16
+ */
17
+
18
+ export type ControlRequest =
19
+ | { readonly type: "login" }
20
+ | { readonly type: "logout" }
21
+ /** The synced list, which the daemon fetches from the server with its token. */
22
+ | { readonly type: "list" }
23
+ /** Puts a skill on this machine on the synced list, after checking its files (`checkSkillToAdd`). */
24
+ | { readonly type: "add"; readonly skill: string }
25
+ /** Hands one feedback item to this machine's skill refinement workflow: a few words naming it, and its text. */
26
+ | { readonly type: "feedback"; readonly slug: string; readonly text: string }
27
+ /** What the daemon is watching for comments, as its own reads found it. */
28
+ | { readonly type: "watching" }
29
+ /** An agent's words for a comment it was told of, to be posted once. */
30
+ | { readonly type: "reply"; readonly key: string; readonly text: string };
31
+
32
+ export type ControlEvent =
33
+ /** Sign-in has started: the page that approves it with a passkey, from a browser on this computer or any other. */
34
+ | { readonly type: "open"; readonly url: string }
35
+ | { readonly type: "signedIn"; readonly machine: string }
36
+ | { readonly type: "signedOut"; readonly revoked: boolean }
37
+ | { readonly type: "list"; readonly skills: ReadonlyArray<ListedSkill> }
38
+ /**
39
+ * The skill is on the synced list. `added` is false when it already was. `folders` are this machine's
40
+ * folders that hold it; `syncingFolders` are those ticked on the dashboard, which upload it.
41
+ */
42
+ | {
43
+ readonly type: "added";
44
+ readonly skill: string;
45
+ readonly added: boolean;
46
+ readonly folders: ReadonlyArray<string>;
47
+ readonly syncingFolders: ReadonlyArray<string>;
48
+ }
49
+ /** The item is in the workflow's intake, under this id. */
50
+ | { readonly type: "feedbackAdded"; readonly id: string }
51
+ | { readonly type: "watching"; readonly watching: Watching }
52
+ | { readonly type: "replied"; readonly replied: Replied }
53
+ | { readonly type: "error"; readonly message: string };
54
+
55
+ const isFinal = (event: ControlEvent): boolean => event.type !== "open";
56
+
57
+ /** No daemon is listening on the control socket: it is stopped, or has not started since the install. */
58
+ export class DaemonNotRunning extends Data.TaggedError("DaemonNotRunning")<{ readonly message: string }> {}
59
+
60
+ /** The daemon is running but the request failed: it refused it, answered nonsense, or hung up. */
61
+ export class DaemonFailed extends Data.TaggedError("DaemonFailed")<{ readonly message: string }> {}
62
+
63
+ /**
64
+ * Sends one request and streams the daemon's events, ending after the final one. The socket is closed when the
65
+ * stream ends or is interrupted, so a caller that stops waiting (a time limit on Tab) leaves nothing open.
66
+ */
67
+ export function requestEvents(message: ControlRequest): Stream.Stream<ControlEvent, DaemonNotRunning | DaemonFailed> {
68
+ return Stream.callback<ControlEvent, DaemonNotRunning | DaemonFailed>((queue) => Effect.acquireRelease(
69
+ Effect.sync(() => {
70
+ let settled = false;
71
+ const fail = (error: DaemonNotRunning | DaemonFailed) => {
72
+ if (settled) return;
73
+ settled = true;
74
+ Queue.failCauseUnsafe(queue, Cause.fail(error));
75
+ };
76
+ const socket = createConnection(CONTROL_SOCKET);
77
+ socket.on("connect", () => socket.write(`${JSON.stringify(message)}\n`));
78
+ socket.on("error", (cause: NodeJS.ErrnoException) => fail(cause.code === "ENOENT" || cause.code === "ECONNREFUSED"
79
+ ? new DaemonNotRunning({ message: `the skill-sync daemon is not running (${cause.code} on ${CONTROL_SOCKET})` })
80
+ : new DaemonFailed({ message: cause.message })));
81
+ readLines(socket, (line) => {
82
+ if (settled) return;
83
+ let event: ControlEvent;
84
+ try {
85
+ event = JSON.parse(line) as ControlEvent;
86
+ } catch {
87
+ return fail(new DaemonFailed({ message: `unexpected answer from the daemon: ${line}` }));
88
+ }
89
+ Queue.offerUnsafe(queue, event);
90
+ if (isFinal(event)) {
91
+ settled = true;
92
+ socket.end();
93
+ Queue.endUnsafe(queue);
94
+ }
95
+ });
96
+ socket.on("close", () => fail(new DaemonFailed({ message: "the daemon closed the connection without answering" })));
97
+ return socket;
98
+ }),
99
+ (socket) => Effect.sync(() => socket.destroy()),
100
+ ));
101
+ }
102
+
103
+ /** One request being answered: send events, and end the conversation with a final one. */
104
+ export interface Reply {
105
+ readonly send: (event: ControlEvent) => void;
106
+ }
107
+
108
+ /**
109
+ * Listens on the control socket. Resolves false, without listening, when another live daemon already
110
+ * holds it: two installs of skill-sync mean two daemons, and the second stands down rather than fight.
111
+ */
112
+ export async function serve(handle: (message: ControlRequest, reply: Reply) => void): Promise<Server | false> {
113
+ if (await answers()) return false;
114
+ // Nothing answered, so a socket file left here is from a daemon that died; it would block the listen.
115
+ if (process.platform !== "win32") rmSync(CONTROL_SOCKET, { force: true });
116
+
117
+ const server = createServer((socket) => {
118
+ const reply: Reply = {
119
+ send: (event) => {
120
+ if (socket.writable) socket.write(`${JSON.stringify(event)}\n`);
121
+ if (isFinal(event)) socket.end();
122
+ },
123
+ };
124
+ readLines(socket, (line) => {
125
+ try {
126
+ handle(JSON.parse(line) as ControlRequest, reply);
127
+ } catch (cause) {
128
+ reply.send({ type: "error", message: cause instanceof Error ? cause.message : String(cause) });
129
+ }
130
+ });
131
+ socket.on("error", () => undefined); // A CLI that went away mid-request; nothing to tell it.
132
+ });
133
+ await new Promise<void>((resolve, reject) => {
134
+ server.once("error", reject);
135
+ server.listen(CONTROL_SOCKET, () => resolve());
136
+ });
137
+ // Only this user may talk to the daemon that holds their token.
138
+ if (process.platform !== "win32") chmodSync(CONTROL_SOCKET, 0o600);
139
+ return server;
140
+ }
141
+
142
+ /** Whether a live daemon is listening on the control socket. */
143
+ function answers(): Promise<boolean> {
144
+ return new Promise((resolve) => {
145
+ const socket = createConnection(CONTROL_SOCKET);
146
+ socket.on("connect", () => {
147
+ socket.end();
148
+ resolve(true);
149
+ });
150
+ socket.on("error", () => resolve(false));
151
+ });
152
+ }
153
+
154
+ function readLines(socket: Socket, onLine: (line: string) => void): void {
155
+ let buffer = "";
156
+ socket.on("data", (chunk) => {
157
+ buffer += chunk.toString();
158
+ let newline: number;
159
+ while ((newline = buffer.indexOf("\n")) >= 0) {
160
+ const line = buffer.slice(0, newline).trim();
161
+ buffer = buffer.slice(newline + 1);
162
+ if (line !== "") onLine(line);
163
+ }
164
+ });
165
+ }