@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.
- package/README.md +346 -0
- package/bin/package.json +1 -0
- package/bin/skill-sync +34 -0
- package/bin/skill-sync-daemon +34 -0
- package/dist/daemons/skill-sync-daemon.js +664 -0
- package/dist/daemons/skill-sync-daemon.js.map +1 -0
- package/dist/entrypoints/skill-sync.js +7 -0
- package/dist/entrypoints/skill-sync.js.map +1 -0
- package/dist/index.js +10 -0
- package/dist/index.js.map +1 -0
- package/dist/internal/agents/agent-tool.js +102 -0
- package/dist/internal/agents/agent-tool.js.map +1 -0
- package/dist/internal/agents/claude.js +424 -0
- package/dist/internal/agents/claude.js.map +1 -0
- package/dist/internal/agents/codex.js +270 -0
- package/dist/internal/agents/codex.js.map +1 -0
- package/dist/internal/agents/command.js +219 -0
- package/dist/internal/agents/command.js.map +1 -0
- package/dist/internal/agents/grok.js +170 -0
- package/dist/internal/agents/grok.js.map +1 -0
- package/dist/internal/agents/index.js +70 -0
- package/dist/internal/agents/index.js.map +1 -0
- package/dist/internal/cli.js +218 -0
- package/dist/internal/cli.js.map +1 -0
- package/dist/internal/comment-watch/held.js +14 -0
- package/dist/internal/comment-watch/held.js.map +1 -0
- package/dist/internal/comment-watch/key.js +4 -0
- package/dist/internal/comment-watch/key.js.map +1 -0
- package/dist/internal/comment-watch/message.js +37 -0
- package/dist/internal/comment-watch/message.js.map +1 -0
- package/dist/internal/comment-watch/paths.js +16 -0
- package/dist/internal/comment-watch/paths.js.map +1 -0
- package/dist/internal/comment-watch/platform.js +66 -0
- package/dist/internal/comment-watch/platform.js.map +1 -0
- package/dist/internal/comment-watch/protocol.js +124 -0
- package/dist/internal/comment-watch/protocol.js.map +1 -0
- package/dist/internal/comment-watch/recent.js +27 -0
- package/dist/internal/comment-watch/recent.js.map +1 -0
- package/dist/internal/comment-watch/replies.js +28 -0
- package/dist/internal/comment-watch/replies.js.map +1 -0
- package/dist/internal/comment-watch/service.js +174 -0
- package/dist/internal/comment-watch/service.js.map +1 -0
- package/dist/internal/comment-watch/settings.js +66 -0
- package/dist/internal/comment-watch/settings.js.map +1 -0
- package/dist/internal/comment-watch/source/github-pull-requests/conversations.js +85 -0
- package/dist/internal/comment-watch/source/github-pull-requests/conversations.js.map +1 -0
- package/dist/internal/comment-watch/source/github-pull-requests/impl.js +276 -0
- package/dist/internal/comment-watch/source/github-pull-requests/impl.js.map +1 -0
- package/dist/internal/comment-watch/source/github-pull-requests/queries.js +97 -0
- package/dist/internal/comment-watch/source/github-pull-requests/queries.js.map +1 -0
- package/dist/internal/comment-watch/source/google-doc/doc.js +57 -0
- package/dist/internal/comment-watch/source/google-doc/doc.js.map +1 -0
- package/dist/internal/comment-watch/source/google-doc/impl.js +190 -0
- package/dist/internal/comment-watch/source/google-doc/impl.js.map +1 -0
- package/dist/internal/comment-watch/source/http-api.js +74 -0
- package/dist/internal/comment-watch/source/http-api.js.map +1 -0
- package/dist/internal/comment-watch/source/interface.js +48 -0
- package/dist/internal/comment-watch/source/interface.js.map +1 -0
- package/dist/internal/comment-watch/source/sign-in.js +40 -0
- package/dist/internal/comment-watch/source/sign-in.js.map +1 -0
- package/dist/internal/comment-watch/source/sources.js +15 -0
- package/dist/internal/comment-watch/source/sources.js.map +1 -0
- package/dist/internal/comment-watch/store/impl.js +242 -0
- package/dist/internal/comment-watch/store/impl.js.map +1 -0
- package/dist/internal/comment-watch/store/interface.js +10 -0
- package/dist/internal/comment-watch/store/interface.js.map +1 -0
- package/dist/internal/comment-watch/t3.js +49 -0
- package/dist/internal/comment-watch/t3.js.map +1 -0
- package/dist/internal/comment-watch/watching.js +65 -0
- package/dist/internal/comment-watch/watching.js.map +1 -0
- package/dist/internal/comment-watch/workflow/comment-watch.js +19 -0
- package/dist/internal/comment-watch/workflow/comment-watch.js.map +1 -0
- package/dist/internal/comment-watch/workflow/deliver.js +104 -0
- package/dist/internal/comment-watch/workflow/deliver.js.map +1 -0
- package/dist/internal/comment-watch/workflow/find.js +67 -0
- package/dist/internal/comment-watch/workflow/find.js.map +1 -0
- package/dist/internal/comment-watch/workflow/post-once.js +66 -0
- package/dist/internal/comment-watch/workflow/post-once.js.map +1 -0
- package/dist/internal/comment-watch/workflow/post.js +40 -0
- package/dist/internal/comment-watch/workflow/post.js.map +1 -0
- package/dist/internal/config.js +131 -0
- package/dist/internal/config.js.map +1 -0
- package/dist/internal/control.js +113 -0
- package/dist/internal/control.js.map +1 -0
- package/dist/internal/daemon-control/impl.js +80 -0
- package/dist/internal/daemon-control/impl.js.map +1 -0
- package/dist/internal/daemon-control/interface.js +4 -0
- package/dist/internal/daemon-control/interface.js.map +1 -0
- package/dist/internal/folders.js +47 -0
- package/dist/internal/folders.js.map +1 -0
- package/dist/internal/local-skills.js +43 -0
- package/dist/internal/local-skills.js.map +1 -0
- package/dist/internal/path.js +36 -0
- package/dist/internal/path.js.map +1 -0
- package/dist/internal/server.js +80 -0
- package/dist/internal/server.js.map +1 -0
- package/dist/internal/skill-check.js +83 -0
- package/dist/internal/skill-check.js.map +1 -0
- package/dist/internal/skill-refinement/evals/cases.js +143 -0
- package/dist/internal/skill-refinement/evals/cases.js.map +1 -0
- package/dist/internal/skill-refinement/evals/opus-action-judge-original.json +350 -0
- package/dist/internal/skill-refinement/evals/opus-judge-original.json +165 -0
- package/dist/internal/skill-refinement/feedback/import-legacy.js +13 -0
- package/dist/internal/skill-refinement/feedback/import-legacy.js.map +1 -0
- package/dist/internal/skill-refinement/feedback/intake.js +52 -0
- package/dist/internal/skill-refinement/feedback/intake.js.map +1 -0
- package/dist/internal/skill-refinement/feedback/managed-intake.js +19 -0
- package/dist/internal/skill-refinement/feedback/managed-intake.js.map +1 -0
- package/dist/internal/skill-refinement/feedback/outbox.js +44 -0
- package/dist/internal/skill-refinement/feedback/outbox.js.map +1 -0
- package/dist/internal/skill-refinement/jev/impl.js +63 -0
- package/dist/internal/skill-refinement/jev/impl.js.map +1 -0
- package/dist/internal/skill-refinement/jev/interface.js +6 -0
- package/dist/internal/skill-refinement/jev/interface.js.map +1 -0
- package/dist/internal/skill-refinement/managed-daemon.js +30 -0
- package/dist/internal/skill-refinement/managed-daemon.js.map +1 -0
- package/dist/internal/skill-refinement/managed-worker-credentials.js +60 -0
- package/dist/internal/skill-refinement/managed-worker-credentials.js.map +1 -0
- package/dist/internal/skill-refinement/managed-worker-files.js +25 -0
- package/dist/internal/skill-refinement/managed-worker-files.js.map +1 -0
- package/dist/internal/skill-refinement/managed-worker-loop.js +36 -0
- package/dist/internal/skill-refinement/managed-worker-loop.js.map +1 -0
- package/dist/internal/skill-refinement/organization-site.js +13 -0
- package/dist/internal/skill-refinement/organization-site.js.map +1 -0
- package/dist/internal/skill-refinement/paths.js +62 -0
- package/dist/internal/skill-refinement/paths.js.map +1 -0
- package/dist/internal/skill-refinement/platform.js +67 -0
- package/dist/internal/skill-refinement/platform.js.map +1 -0
- package/dist/internal/skill-refinement/service.js +365 -0
- package/dist/internal/skill-refinement/service.js.map +1 -0
- package/dist/internal/skill-refinement/skills/skill-text.js +219 -0
- package/dist/internal/skill-refinement/skills/skill-text.js.map +1 -0
- package/dist/internal/skill-refinement/workflow/retry.js +44 -0
- package/dist/internal/skill-refinement/workflow/retry.js.map +1 -0
- package/dist/internal/skill-refinement/workflow/skill-refinement.js +690 -0
- package/dist/internal/skill-refinement/workflow/skill-refinement.js.map +1 -0
- package/dist/internal/skill-refinement/writer/impl.js +2 -0
- package/dist/internal/skill-refinement/writer/impl.js.map +1 -0
- package/dist/internal/skill-refinement/writer/interface.js +2 -0
- package/dist/internal/skill-refinement/writer/interface.js.map +1 -0
- package/dist/internal/sync.js +182 -0
- package/dist/internal/sync.js.map +1 -0
- package/dist/internal/wire.js +31 -0
- package/dist/internal/wire.js.map +1 -0
- package/dist/internal/writer/claude.js +84 -0
- package/dist/internal/writer/claude.js.map +1 -0
- package/dist/internal/writer/codex.js +102 -0
- package/dist/internal/writer/codex.js.map +1 -0
- package/dist/internal/writer/interface.js +6 -0
- package/dist/internal/writer/interface.js.map +1 -0
- package/dist/internal/writer/live.js +13 -0
- package/dist/internal/writer/live.js.map +1 -0
- package/dist/internal/writer/reset.js +38 -0
- package/dist/internal/writer/reset.js.map +1 -0
- package/dist/internal/writer/selection.js +79 -0
- package/dist/internal/writer/selection.js.map +1 -0
- package/package.json +45 -11
- package/postinstall.cjs +663 -0
- package/src/daemons/skill-sync-daemon.ts +677 -0
- package/src/entrypoints/skill-sync.ts +12 -0
- package/src/index.ts +15 -0
- package/src/internal/agents/agent-tool.ts +149 -0
- package/src/internal/agents/claude.ts +442 -0
- package/src/internal/agents/codex.ts +288 -0
- package/src/internal/agents/command.ts +257 -0
- package/src/internal/agents/grok.ts +174 -0
- package/src/internal/agents/index.ts +74 -0
- package/src/internal/cli.ts +249 -0
- package/src/internal/comment-watch/held.ts +20 -0
- package/src/internal/comment-watch/key.ts +5 -0
- package/src/internal/comment-watch/message.ts +39 -0
- package/src/internal/comment-watch/paths.ts +17 -0
- package/src/internal/comment-watch/platform.ts +69 -0
- package/src/internal/comment-watch/protocol.ts +140 -0
- package/src/internal/comment-watch/recent.ts +26 -0
- package/src/internal/comment-watch/replies.ts +28 -0
- package/src/internal/comment-watch/service.ts +198 -0
- package/src/internal/comment-watch/settings.ts +82 -0
- package/src/internal/comment-watch/source/github-pull-requests/conversations.ts +111 -0
- package/src/internal/comment-watch/source/github-pull-requests/impl.ts +291 -0
- package/src/internal/comment-watch/source/github-pull-requests/queries.ts +113 -0
- package/src/internal/comment-watch/source/google-doc/doc.ts +76 -0
- package/src/internal/comment-watch/source/google-doc/impl.ts +198 -0
- package/src/internal/comment-watch/source/http-api.ts +93 -0
- package/src/internal/comment-watch/source/interface.ts +116 -0
- package/src/internal/comment-watch/source/sign-in.ts +45 -0
- package/src/internal/comment-watch/source/sources.ts +20 -0
- package/src/internal/comment-watch/store/impl.ts +268 -0
- package/src/internal/comment-watch/store/interface.ts +83 -0
- package/src/internal/comment-watch/t3.ts +68 -0
- package/src/internal/comment-watch/watching.ts +122 -0
- package/src/internal/comment-watch/workflow/comment-watch.ts +34 -0
- package/src/internal/comment-watch/workflow/deliver.ts +115 -0
- package/src/internal/comment-watch/workflow/find.ts +78 -0
- package/src/internal/comment-watch/workflow/post-once.ts +72 -0
- package/src/internal/comment-watch/workflow/post.ts +56 -0
- package/src/internal/config.ts +172 -0
- package/src/internal/control.ts +165 -0
- package/src/internal/daemon-control/impl.ts +94 -0
- package/src/internal/daemon-control/interface.ts +46 -0
- package/src/internal/folders.ts +50 -0
- package/src/internal/local-skills.ts +58 -0
- package/src/internal/path.ts +32 -0
- package/src/internal/server.ts +76 -0
- package/src/internal/skill-check.ts +97 -0
- package/src/internal/skill-refinement/evals/cases.ts +167 -0
- package/src/internal/skill-refinement/evals/opus-action-judge-original.json +350 -0
- package/src/internal/skill-refinement/evals/opus-judge-original.json +165 -0
- package/src/internal/skill-refinement/feedback/import-legacy.ts +16 -0
- package/src/internal/skill-refinement/feedback/intake.ts +66 -0
- package/src/internal/skill-refinement/feedback/managed-intake.ts +19 -0
- package/src/internal/skill-refinement/feedback/outbox.ts +50 -0
- package/src/internal/skill-refinement/jev/impl.ts +76 -0
- package/src/internal/skill-refinement/jev/interface.ts +56 -0
- package/src/internal/skill-refinement/managed-daemon.ts +38 -0
- package/src/internal/skill-refinement/managed-worker-credentials.ts +59 -0
- package/src/internal/skill-refinement/managed-worker-files.ts +24 -0
- package/src/internal/skill-refinement/managed-worker-loop.ts +46 -0
- package/src/internal/skill-refinement/organization-site.ts +15 -0
- package/src/internal/skill-refinement/paths.ts +87 -0
- package/src/internal/skill-refinement/platform.ts +71 -0
- package/src/internal/skill-refinement/service.ts +418 -0
- package/src/internal/skill-refinement/skills/skill-text.ts +292 -0
- package/src/internal/skill-refinement/workflow/retry.ts +61 -0
- package/src/internal/skill-refinement/workflow/skill-refinement.ts +777 -0
- package/src/internal/skill-refinement/writer/impl.ts +1 -0
- package/src/internal/skill-refinement/writer/interface.ts +1 -0
- package/src/internal/sync.ts +216 -0
- package/src/internal/wire.ts +439 -0
- package/src/internal/writer/claude.ts +98 -0
- package/src/internal/writer/codex.ts +93 -0
- package/src/internal/writer/interface.ts +48 -0
- package/src/internal/writer/live.ts +19 -0
- package/src/internal/writer/reset.ts +34 -0
- package/src/internal/writer/selection.ts +84 -0
- package/multi-call-binary +0 -4
|
@@ -0,0 +1,677 @@
|
|
|
1
|
+
import { mkdirSync, watch, type FSWatcher } from "node:fs";
|
|
2
|
+
import { homedir } from "node:os";
|
|
3
|
+
import { join } from "node:path";
|
|
4
|
+
import { autoUpgrade, exitWhenUninstalled } from "jive-abstract-library";
|
|
5
|
+
import { name, version } from "../../package.json";
|
|
6
|
+
import {
|
|
7
|
+
CONFIG_PATH, TOKEN_PATH, deleteToken, loadSettings, loadStates, loadToken, saveStates, saveToken, stateFor,
|
|
8
|
+
type Config,
|
|
9
|
+
} from "../internal/config";
|
|
10
|
+
import { serve, type ControlRequest, type Reply } from "../internal/control";
|
|
11
|
+
import { describe, register } from "../internal/folders";
|
|
12
|
+
import { authHeaders, claimSignInRequest, fetchServer, openSignInRequest, TokenOfAnotherMachine, TokenRejected } from "../internal/server";
|
|
13
|
+
import { describeActivity, isQuiet, syncOnce, type Report } from "../internal/sync";
|
|
14
|
+
import { checkSkillToAdd } from "../internal/skill-check";
|
|
15
|
+
import { detectFolders, readUsage } from "../internal/agents";
|
|
16
|
+
import { findCommand } from "../internal/agents/command";
|
|
17
|
+
import { startSkillRefinement, type NotRunning, type SkillRefinementRunner } from "../internal/skill-refinement/service";
|
|
18
|
+
import { managedDaemon } from "../internal/skill-refinement/managed-daemon";
|
|
19
|
+
import { startCommentWatch, startedCommentWatch, type CommentWatch } from "../internal/comment-watch/service";
|
|
20
|
+
import {
|
|
21
|
+
DAEMON_VERSION_HEADER, type AddSkillResponse, type DaemonMessage, type FolderPrefs, type FolderState, type HubToDaemon, type ListedSkill,
|
|
22
|
+
type ListSkillsResponse, type Refinement,
|
|
23
|
+
} from "../internal/wire";
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* Keeps every enabled skills folder on this machine identical to every other machine's.
|
|
27
|
+
*
|
|
28
|
+
* Folders are detected: the skills folders each agent tool reads (`AGENT_TOOLS`, `detectFolders`). Which of them sync, and the one list of skills that syncs in all of them, are
|
|
29
|
+
* held by the server and changed from the dashboard, so they survive a reinstall and apply the moment
|
|
30
|
+
* they change. A skill not on the list is never pushed or pulled.
|
|
31
|
+
*
|
|
32
|
+
* The daemon holds a WebSocket to the service's hub. That connection is how the dashboard knows this
|
|
33
|
+
* machine is running, how a preference change arrives, and how a write from another machine triggers a
|
|
34
|
+
* cycle here at once. Polling stays as the fallback: every 5 minutes while connected, every 30 seconds
|
|
35
|
+
* while not, so a dropped connection costs latency and never correctness.
|
|
36
|
+
*
|
|
37
|
+
* `skill-sync login` asks the daemon, over the control socket, to sign in (`login`); once a passkey approves it, this
|
|
38
|
+
* process claims the token from the server and keeps it in `~/.jive/skill-sync-token.json` (`TOKEN_PATH`). A
|
|
39
|
+
* daemon that starts and finds that file is signed in, so a restart, a reboot or an upgrade needs no
|
|
40
|
+
* sign-in. Signing out, or the server rejecting the token, deletes the file.
|
|
41
|
+
*
|
|
42
|
+
* Every minute it also reads each Claude, Codex and Grok account on the machine (`readUsage`): who it is
|
|
43
|
+
* and its plan limits, asked of the tool's own CLI at most every five minutes, and this machine's use of
|
|
44
|
+
* it, from the files the tool writes. It sends them over the same connection when they change, for the
|
|
45
|
+
* dashboard. No credential is read or sent: the CLIs make the authenticated calls.
|
|
46
|
+
*
|
|
47
|
+
* It runs this machine's skill refinement workflow (`startSkillRefinement`): Alex's feedback, handed over with
|
|
48
|
+
* `skill-sync feedback`, becomes tested changes to the synced skills. It reports the workflow's queue and runs to the hub for
|
|
49
|
+
* the dashboard's Skill refinement tab, and takes that tab's limit changes.
|
|
50
|
+
*
|
|
51
|
+
* On a machine whose settings name somewhere to watch (`commentWatch` in `~/.jive/skill-sync.json`), it also runs the comment
|
|
52
|
+
* watch (`startCommentWatch`): each new comment left there is queued once, and each reply to one is posted once.
|
|
53
|
+
*
|
|
54
|
+
* It keeps itself on the latest published version (`autoUpgrade`): every 5 minutes it asks the package
|
|
55
|
+
* manager that installed it whether a newer one is out, installs it the same way, and is restarted on it.
|
|
56
|
+
*/
|
|
57
|
+
|
|
58
|
+
const POLL_CONNECTED_MS = 5 * 60_000;
|
|
59
|
+
const POLL_DISCONNECTED_MS = 30_000;
|
|
60
|
+
/** Long enough that an editor's write-rename-write lands as one cycle, short enough to feel immediate. */
|
|
61
|
+
const SETTLE_MS = 1_000;
|
|
62
|
+
const PING_MS = 30_000;
|
|
63
|
+
/** No pong for this long means the connection is dead even if the socket has not noticed. */
|
|
64
|
+
const PONG_TIMEOUT_MS = 75_000;
|
|
65
|
+
const RECONNECT_MIN_MS = 5_000;
|
|
66
|
+
const RECONNECT_MAX_MS = 5 * 60_000;
|
|
67
|
+
/** How often this machine's use is read from local files; account limits are asked of the CLIs less often (`ACCOUNT_READ_MS`). */
|
|
68
|
+
const USAGE_READ_MS = 60_000;
|
|
69
|
+
/** How often a sign-in asks the server whether a passkey has approved it; the server says when it expired. */
|
|
70
|
+
const SIGN_IN_CLAIM_MS = 2_000;
|
|
71
|
+
/** How often the skill refinement workflow's runs and limits are read for the dashboard; sent only when they changed. */
|
|
72
|
+
const REFINEMENT_REPORT_MS = 60_000;
|
|
73
|
+
/** A hub message over this is refused by the platform (1 MiB); the dashboard is told the figures are too big instead. */
|
|
74
|
+
const MAX_REFINEMENT_MESSAGE_BYTES = 900_000;
|
|
75
|
+
|
|
76
|
+
exitWhenUninstalled();
|
|
77
|
+
|
|
78
|
+
const settings = loadSettings();
|
|
79
|
+
if (settings === undefined) {
|
|
80
|
+
console.error("~/.jive/skill-sync.json needs an endpoint and a machine name");
|
|
81
|
+
// Zero, not one: the service manager restarts a daemon that fails, and a file nobody has fixed would
|
|
82
|
+
// only fill the log.
|
|
83
|
+
process.exit(0);
|
|
84
|
+
}
|
|
85
|
+
const states = loadStates();
|
|
86
|
+
|
|
87
|
+
/** Set while signed in. Everything that talks to the server reads it; signing out clears it. */
|
|
88
|
+
let session: Config | undefined;
|
|
89
|
+
/** The signed-in config, for code that only runs during a session. */
|
|
90
|
+
function current(): Config {
|
|
91
|
+
if (session === undefined) throw new Error("not signed in");
|
|
92
|
+
return session;
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/** What was last registered, so registration is repeated only when a folder or skill appears or goes. */
|
|
96
|
+
let registered = "";
|
|
97
|
+
/** The enabled folders, each with the synced list. */
|
|
98
|
+
let prefs = new Map<string, ReadonlySet<string>>();
|
|
99
|
+
const watchers = new Map<string, FSWatcher>();
|
|
100
|
+
|
|
101
|
+
// ── Folders ─────────────────────────────────────────────────────────────────────────────────────────
|
|
102
|
+
|
|
103
|
+
/**
|
|
104
|
+
* Reports this machine's folders and skills, and adopts the server's answer for what syncs. The server takes it
|
|
105
|
+
* only from a token issued to the machine this one is configured as, so the session's first registration is
|
|
106
|
+
* where that is known.
|
|
107
|
+
*/
|
|
108
|
+
async function registerFolders(): Promise<void> {
|
|
109
|
+
const config = current();
|
|
110
|
+
const request = describe(config);
|
|
111
|
+
const first = registered === "";
|
|
112
|
+
const folders = await register(config, request);
|
|
113
|
+
if (first) console.log(`signed in as ${config.machine}: the server confirmed the token is this machine's; syncing with ${config.endpoint}`);
|
|
114
|
+
applyPrefs(folders);
|
|
115
|
+
registered = JSON.stringify(request);
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
/** True when a folder or a skill has appeared or gone since the last registration. */
|
|
119
|
+
const registrationStale = (): boolean => JSON.stringify(describe(current())) !== registered;
|
|
120
|
+
|
|
121
|
+
function applyPrefs(folders: ReadonlyArray<FolderPrefs>): void {
|
|
122
|
+
// Only folders this machine still has. The hub can hold a stale list — it answers a reconnect before
|
|
123
|
+
// the next registration — and creating a listed folder whose agent home is gone would bring it back.
|
|
124
|
+
const present = new Set(detectFolders());
|
|
125
|
+
const next = new Map(folders.filter((folder) => present.has(folder.path))
|
|
126
|
+
.map((folder) => [folder.path, new Set(folder.skills)] as const));
|
|
127
|
+
for (const [folder, watcher] of watchers) {
|
|
128
|
+
if (!next.has(folder)) {
|
|
129
|
+
watcher.close();
|
|
130
|
+
watchers.delete(folder);
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
// An unticked folder leaves no trace of syncing: its state goes, so the state file lists only folders
|
|
134
|
+
// that sync, and ticking it again starts it fresh.
|
|
135
|
+
// Covers folders with state from an earlier run too, not only ones this run was syncing.
|
|
136
|
+
const stopped = [...new Set([...prefs.keys(), ...Object.keys(states)])].filter((folder) => !next.has(folder));
|
|
137
|
+
for (const folder of stopped) {
|
|
138
|
+
delete states[folder];
|
|
139
|
+
console.log(`stopped syncing ${folder}`);
|
|
140
|
+
}
|
|
141
|
+
if (stopped.length > 0) saveStates(states);
|
|
142
|
+
for (const folder of next.keys()) {
|
|
143
|
+
if (watchers.has(folder)) continue;
|
|
144
|
+
mkdirSync(folder, { recursive: true });
|
|
145
|
+
let settle: ReturnType<typeof setTimeout> | undefined;
|
|
146
|
+
watchers.set(folder, watch(folder, { recursive: true }, () => {
|
|
147
|
+
if (settle !== undefined) clearTimeout(settle);
|
|
148
|
+
settle = setTimeout(runCycle, SETTLE_MS);
|
|
149
|
+
}));
|
|
150
|
+
}
|
|
151
|
+
const changed = JSON.stringify([...next].map(([path, skills]) => [path, [...skills].sort()]))
|
|
152
|
+
!== JSON.stringify([...prefs].map(([path, skills]) => [path, [...skills].sort()]));
|
|
153
|
+
prefs = next;
|
|
154
|
+
if (!changed) return;
|
|
155
|
+
for (const [folder, skills] of prefs) console.log(`syncing ${folder}: ${[...skills].sort().join(", ") || "no skills"}`);
|
|
156
|
+
if (prefs.size === 0) console.log("syncing no folders");
|
|
157
|
+
void runCycle();
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
// ── Hub connection ──────────────────────────────────────────────────────────────────────────────────
|
|
161
|
+
|
|
162
|
+
let socket: WebSocket | undefined;
|
|
163
|
+
let lastPong = 0;
|
|
164
|
+
let reconnectDelay = RECONNECT_MIN_MS;
|
|
165
|
+
/** What the hub was last told about each folder (state and detail), so only changes are sent. */
|
|
166
|
+
const reported = new Map<string, string>();
|
|
167
|
+
|
|
168
|
+
function connect(): void {
|
|
169
|
+
if (session === undefined) return;
|
|
170
|
+
const config = session;
|
|
171
|
+
const url = `${config.endpoint.replace(/^http/, "ws")}/daemon`;
|
|
172
|
+
// Bun's WebSocket takes headers; the browser's does not, which is why the token can travel this way.
|
|
173
|
+
// The version goes with it: an upgrade restarts the daemon, so each connection runs exactly one version.
|
|
174
|
+
const ws = new WebSocket(url, { headers: authHeaders(config, { [DAEMON_VERSION_HEADER]: version }) } as unknown as string[]);
|
|
175
|
+
ws.onopen = () => {
|
|
176
|
+
socket = ws;
|
|
177
|
+
lastPong = Date.now();
|
|
178
|
+
reconnectDelay = RECONNECT_MIN_MS;
|
|
179
|
+
console.log("connected to the hub");
|
|
180
|
+
// Whatever the hub last heard from a previous connection is stale until re-sent.
|
|
181
|
+
reported.clear();
|
|
182
|
+
for (const folder of prefs.keys()) report(folder, "idle");
|
|
183
|
+
reportedUsage = "";
|
|
184
|
+
reportUsage();
|
|
185
|
+
reportedRefinement = "";
|
|
186
|
+
void reportRefinement();
|
|
187
|
+
};
|
|
188
|
+
ws.onmessage = (event) => {
|
|
189
|
+
const data = String(event.data);
|
|
190
|
+
if (data === "pong") {
|
|
191
|
+
lastPong = Date.now();
|
|
192
|
+
return;
|
|
193
|
+
}
|
|
194
|
+
const message = JSON.parse(data) as HubToDaemon;
|
|
195
|
+
if (message.type === "prefs") applyPrefs(message.folders);
|
|
196
|
+
if (message.type === "changed") void runCycle();
|
|
197
|
+
if (message.type === "setLimit") setRefinementLimit(message);
|
|
198
|
+
};
|
|
199
|
+
ws.onclose = () => {
|
|
200
|
+
if (socket === ws) socket = undefined;
|
|
201
|
+
// Only the session that opened it reconnects: after a sign-out, or a sign-in with a new token, this
|
|
202
|
+
// socket belongs to nobody.
|
|
203
|
+
if (session !== config) return;
|
|
204
|
+
setTimeout(connect, reconnectDelay);
|
|
205
|
+
reconnectDelay = Math.min(reconnectDelay * 2, RECONNECT_MAX_MS);
|
|
206
|
+
};
|
|
207
|
+
ws.onerror = () => {
|
|
208
|
+
// `onclose` follows and schedules the reconnect.
|
|
209
|
+
};
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
setInterval(() => {
|
|
213
|
+
if (socket === undefined) return;
|
|
214
|
+
if (Date.now() - lastPong > PONG_TIMEOUT_MS) {
|
|
215
|
+
console.error("hub connection went quiet; reconnecting");
|
|
216
|
+
socket.close();
|
|
217
|
+
return;
|
|
218
|
+
}
|
|
219
|
+
socket.send("ping");
|
|
220
|
+
}, PING_MS);
|
|
221
|
+
|
|
222
|
+
function report(folder: string, state: FolderState, detail?: string, activity?: string): void {
|
|
223
|
+
const key = `${state}|${detail ?? ""}`;
|
|
224
|
+
if (reported.get(folder) === key && activity === undefined) return;
|
|
225
|
+
if (socket === undefined) return;
|
|
226
|
+
const message: DaemonMessage = {
|
|
227
|
+
type: "status",
|
|
228
|
+
folder,
|
|
229
|
+
state,
|
|
230
|
+
...(detail === undefined ? {} : { detail }),
|
|
231
|
+
...(activity === undefined ? {} : { activity }),
|
|
232
|
+
};
|
|
233
|
+
socket.send(JSON.stringify(message));
|
|
234
|
+
reported.set(folder, key);
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
/** The usage the hub last heard, so it is sent again only when a number changes. */
|
|
238
|
+
let reportedUsage = "";
|
|
239
|
+
|
|
240
|
+
/** True while a reading runs: a CLI can take seconds to answer, and two readings at once would ask it twice. */
|
|
241
|
+
let readingUsage = false;
|
|
242
|
+
|
|
243
|
+
/** Sends every account's usage to the hub when it differs from what was last sent. */
|
|
244
|
+
async function reportUsage(): Promise<void> {
|
|
245
|
+
if (socket === undefined || readingUsage) return;
|
|
246
|
+
readingUsage = true;
|
|
247
|
+
let message: DaemonMessage;
|
|
248
|
+
try {
|
|
249
|
+
message = { type: "usage", accounts: await readUsage() };
|
|
250
|
+
} catch (cause) {
|
|
251
|
+
// Only an unreadable home directory gets here; each account's own failure is reported as `unknown`.
|
|
252
|
+
console.error(`could not read account usage: ${cause instanceof Error ? cause.message : String(cause)}`);
|
|
253
|
+
return;
|
|
254
|
+
} finally {
|
|
255
|
+
readingUsage = false;
|
|
256
|
+
}
|
|
257
|
+
const text = JSON.stringify(message);
|
|
258
|
+
// The socket can have closed, or been replaced, while the CLIs ran.
|
|
259
|
+
if (text === reportedUsage || socket === undefined) return;
|
|
260
|
+
socket.send(text);
|
|
261
|
+
reportedUsage = text;
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
setInterval(reportUsage, USAGE_READ_MS);
|
|
265
|
+
|
|
266
|
+
// ── Skill refinement ────────────────────────────────────────────────────────────────────────────────
|
|
267
|
+
|
|
268
|
+
/** The workflow running here, or why it is not; it runs whether or not the machine is signed in. */
|
|
269
|
+
let refinement: SkillRefinementRunner | NotRunning = { notRunning: "starting" };
|
|
270
|
+
/** What the hub last heard about it, so it is sent again only when something the dashboard draws changed. */
|
|
271
|
+
let reportedRefinement = "";
|
|
272
|
+
|
|
273
|
+
/** Sends the workflow's state and figures to the hub when they differ from what was last sent. */
|
|
274
|
+
async function reportRefinement(): Promise<void> {
|
|
275
|
+
if (socket === undefined) return;
|
|
276
|
+
const runner = refinement;
|
|
277
|
+
let state: Refinement;
|
|
278
|
+
try {
|
|
279
|
+
state = "notRunning" in runner ? { state: "notRunning", reason: runner.notRunning } : { state: "running", data: await runner.pageData() };
|
|
280
|
+
} catch (cause) {
|
|
281
|
+
console.error(`skill refinement: could not read its runs and limits: ${describeError(cause)}`);
|
|
282
|
+
return;
|
|
283
|
+
}
|
|
284
|
+
let text = JSON.stringify({ type: "refinement", refinement: state } satisfies DaemonMessage);
|
|
285
|
+
if (text.length > MAX_REFINEMENT_MESSAGE_BYTES) {
|
|
286
|
+
console.error(`skill refinement: its figures are ${text.length} bytes, over the hub's limit; sending its state without them`);
|
|
287
|
+
text = JSON.stringify({ type: "refinement", refinement: { state: "notRunning", reason: `its figures (${text.length} bytes) are too big to send` } } satisfies DaemonMessage);
|
|
288
|
+
}
|
|
289
|
+
if (text === reportedRefinement || socket === undefined) return;
|
|
290
|
+
socket.send(text);
|
|
291
|
+
reportedRefinement = text;
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
setInterval(reportRefinement, REFINEMENT_REPORT_MS);
|
|
295
|
+
|
|
296
|
+
/** A limit set on the dashboard's Skill refinement tab for this machine. */
|
|
297
|
+
function setRefinementLimit(change: Extract<HubToDaemon, { type: "setLimit" }>): void {
|
|
298
|
+
const runner = refinement;
|
|
299
|
+
if ("notRunning" in runner) {
|
|
300
|
+
console.error(`skill refinement: a ${change.limit} limit came from the dashboard, but the workflow is not running here: ${runner.notRunning}`);
|
|
301
|
+
return;
|
|
302
|
+
}
|
|
303
|
+
runner.setLimit({ workflow: change.workflow, limit: change.limit, value: change.value }).then(
|
|
304
|
+
() => reportRefinement(),
|
|
305
|
+
(cause) => console.error(`skill refinement: the dashboard's ${change.limit} limit for ${change.workflow} was not set: ${describeError(cause)}`),
|
|
306
|
+
);
|
|
307
|
+
}
|
|
308
|
+
|
|
309
|
+
/** The synced list, for the workflow's install guard: the same request `skill-sync list` makes, from this process. */
|
|
310
|
+
async function syncedSkills(): Promise<ReadonlyArray<ListedSkill>> {
|
|
311
|
+
const config = session;
|
|
312
|
+
if (config === undefined) throw new Error(signedOutMessage());
|
|
313
|
+
return await fetchSyncedSkills(config);
|
|
314
|
+
}
|
|
315
|
+
|
|
316
|
+
async function fetchSyncedSkills(config: Config): Promise<ReadonlyArray<ListedSkill>> {
|
|
317
|
+
const response = await fetchServer(config, "/skills");
|
|
318
|
+
if (!response.ok) throw new Error(`GET /skills: ${response.status} ${await response.text()}`);
|
|
319
|
+
return (await response.json() as ListSkillsResponse).skills;
|
|
320
|
+
}
|
|
321
|
+
|
|
322
|
+
/** Hands a feedback item to the workflow, for `skill-sync feedback`. */
|
|
323
|
+
function addFeedback(item: { readonly slug: string; readonly text: string }, reply: Reply): void {
|
|
324
|
+
const runner = refinement;
|
|
325
|
+
if ("notRunning" in runner) {
|
|
326
|
+
reply.send({ type: "error", message: `skill refinement is not running on this machine: ${runner.notRunning}` });
|
|
327
|
+
return;
|
|
328
|
+
}
|
|
329
|
+
runner.addFeedback(item).then(
|
|
330
|
+
(id) => {
|
|
331
|
+
console.log(`skill refinement: feedback ${id} added`);
|
|
332
|
+
reply.send({ type: "feedbackAdded", id });
|
|
333
|
+
},
|
|
334
|
+
(cause) => reply.send({ type: "error", message: describeError(cause) }),
|
|
335
|
+
);
|
|
336
|
+
}
|
|
337
|
+
|
|
338
|
+
// ── Comment watch ───────────────────────────────────────────────────────────────────────────────────
|
|
339
|
+
|
|
340
|
+
/** The comment watch running here, or why it watches nothing; what is asked of it as it starts waits for it. */
|
|
341
|
+
let startWatch: (starting: Promise<CommentWatch>) => void = () => undefined;
|
|
342
|
+
const commentWatch = startedCommentWatch(new Promise<CommentWatch>((resolve) => { startWatch = resolve; }));
|
|
343
|
+
|
|
344
|
+
/** What it is watching, for `skill-sync watching`. */
|
|
345
|
+
function watching(reply: Reply): void {
|
|
346
|
+
commentWatch.watching().then(
|
|
347
|
+
(found) => reply.send({ type: "watching", watching: found }),
|
|
348
|
+
(cause) => reply.send({ type: "error", message: `what is watched could not be read: ${describeError(cause)}` }),
|
|
349
|
+
);
|
|
350
|
+
}
|
|
351
|
+
|
|
352
|
+
/** Posts an agent's words for a comment, for `skill-sync reply`. */
|
|
353
|
+
function postReply(words: { readonly key: string; readonly text: string }, reply: Reply): void {
|
|
354
|
+
commentWatch.reply({ key: words.key, text: words.text }).then(
|
|
355
|
+
(replied) => reply.send({ type: "replied", replied }),
|
|
356
|
+
(cause) => reply.send({ type: "error", message: `the reply could not be taken: ${describeError(cause)}` }),
|
|
357
|
+
);
|
|
358
|
+
}
|
|
359
|
+
|
|
360
|
+
// ── Sync cycles ─────────────────────────────────────────────────────────────────────────────────────
|
|
361
|
+
|
|
362
|
+
let running = false;
|
|
363
|
+
let cycleQueued = false;
|
|
364
|
+
|
|
365
|
+
async function runCycle(): Promise<void> {
|
|
366
|
+
if (session === undefined) return;
|
|
367
|
+
if (running) {
|
|
368
|
+
cycleQueued = true;
|
|
369
|
+
return;
|
|
370
|
+
}
|
|
371
|
+
running = true;
|
|
372
|
+
try {
|
|
373
|
+
// Folders sync one after another against the same server, so a change pushed from one folder is
|
|
374
|
+
// pulled into the others on the follow-up pass this triggers.
|
|
375
|
+
for (const [folder, skills] of [...prefs]) {
|
|
376
|
+
try {
|
|
377
|
+
const result = await syncOnce(current(), folder, stateFor(states, folder), skills);
|
|
378
|
+
saveStates(states);
|
|
379
|
+
log(folder, result);
|
|
380
|
+
if (result.rejected.length > 0) report(folder, "attention", result.rejected.join("; "), describeActivity(result) || undefined);
|
|
381
|
+
else report(folder, "idle", undefined, isQuiet(result) ? undefined : describeActivity(result));
|
|
382
|
+
// What this folder pushed is pulled into the machine's other folders on the follow-up pass.
|
|
383
|
+
if (result.pushed.length > 0) cycleQueued = true;
|
|
384
|
+
} catch (cause) {
|
|
385
|
+
if (endRefusedSession(cause)) return;
|
|
386
|
+
// One failed folder must not end the daemon or the other folders: the usual cause is the network.
|
|
387
|
+
const reason = cause instanceof Error ? cause.message : String(cause);
|
|
388
|
+
console.error(`${folder}: sync failed: ${reason}`);
|
|
389
|
+
report(folder, "attention", `sync failed: ${reason}`);
|
|
390
|
+
}
|
|
391
|
+
}
|
|
392
|
+
// A skill created or removed locally changes what the dashboard should list.
|
|
393
|
+
if (registrationStale()) {
|
|
394
|
+
await registerFolders().catch((cause: unknown) => {
|
|
395
|
+
endRefusedSession(cause);
|
|
396
|
+
});
|
|
397
|
+
}
|
|
398
|
+
} finally {
|
|
399
|
+
running = false;
|
|
400
|
+
if (cycleQueued) {
|
|
401
|
+
cycleQueued = false;
|
|
402
|
+
setTimeout(runCycle, SETTLE_MS);
|
|
403
|
+
}
|
|
404
|
+
}
|
|
405
|
+
}
|
|
406
|
+
|
|
407
|
+
function log(folder: string, result: Report): void {
|
|
408
|
+
for (const path of result.pulled) console.log(`${folder}: pulled ${path}`);
|
|
409
|
+
for (const path of result.pushed) console.log(`${folder}: pushed ${path}`);
|
|
410
|
+
for (const path of result.deletedLocally) console.log(`${folder}: deleted ${path}`);
|
|
411
|
+
for (const path of result.rejected) console.error(`${folder}: refused a path the server sent: ${path}`);
|
|
412
|
+
}
|
|
413
|
+
|
|
414
|
+
let pollTimer: ReturnType<typeof setTimeout> | undefined;
|
|
415
|
+
|
|
416
|
+
/** Re-detects folders each poll: an agent home created since the last one should join without a restart. */
|
|
417
|
+
async function poll(): Promise<void> {
|
|
418
|
+
if (session === undefined) return;
|
|
419
|
+
try {
|
|
420
|
+
if (registered === "" || registrationStale()) await registerFolders();
|
|
421
|
+
} catch (cause) {
|
|
422
|
+
if (endRefusedSession(cause)) return;
|
|
423
|
+
console.error(`could not register folders: ${cause instanceof Error ? cause.message : String(cause)}`);
|
|
424
|
+
}
|
|
425
|
+
await runCycle();
|
|
426
|
+
if (session !== undefined) pollTimer = setTimeout(poll, socket === undefined ? POLL_DISCONNECTED_MS : POLL_CONNECTED_MS);
|
|
427
|
+
}
|
|
428
|
+
|
|
429
|
+
// ── Signing in and out ──────────────────────────────────────────────────────────────────────────────
|
|
430
|
+
|
|
431
|
+
/**
|
|
432
|
+
* Starts a session with a token just claimed from a sign-in. Registering this machine's folders is the first call
|
|
433
|
+
* that needs the token, so it doubles as the check that the token works: a failure leaves the daemon
|
|
434
|
+
* signed out, not half-running, and the token unsaved.
|
|
435
|
+
*/
|
|
436
|
+
async function signIn(token: string): Promise<void> {
|
|
437
|
+
if (session !== undefined) await signOut();
|
|
438
|
+
tokenOfAnotherMachine = undefined;
|
|
439
|
+
session = { ...settings!, token };
|
|
440
|
+
try {
|
|
441
|
+
await registerFolders();
|
|
442
|
+
} catch (cause) {
|
|
443
|
+
session = undefined;
|
|
444
|
+
throw cause;
|
|
445
|
+
}
|
|
446
|
+
saveToken(token);
|
|
447
|
+
connect();
|
|
448
|
+
void poll();
|
|
449
|
+
}
|
|
450
|
+
|
|
451
|
+
/**
|
|
452
|
+
* Starts a session with the token saved by an earlier sign-in. Not checked first, unlike `signIn`: at boot
|
|
453
|
+
* the network may not be up yet, and a failure for that reason must not sign the machine out. The first
|
|
454
|
+
* poll registers, which is when the server says whose token it is: a rejected token signs out there, and
|
|
455
|
+
* one issued to another machine stops the session (`endRefusedSession`).
|
|
456
|
+
*/
|
|
457
|
+
function resume(token: string): void {
|
|
458
|
+
session = { ...settings!, token };
|
|
459
|
+
console.log(`resuming as ${session.machine} with the token in ${TOKEN_PATH}; checking it with ${session.endpoint}`);
|
|
460
|
+
connect();
|
|
461
|
+
void poll();
|
|
462
|
+
}
|
|
463
|
+
|
|
464
|
+
/**
|
|
465
|
+
* Stops syncing and reporting. The token file stays: `endSession` deletes it, and a token found to be another
|
|
466
|
+
* machine's is left for that machine's sake. Returns the session that stopped.
|
|
467
|
+
*/
|
|
468
|
+
function stopSession(): Config | undefined {
|
|
469
|
+
const config = session;
|
|
470
|
+
if (config === undefined) return undefined;
|
|
471
|
+
session = undefined;
|
|
472
|
+
if (pollTimer !== undefined) clearTimeout(pollTimer);
|
|
473
|
+
socket?.close();
|
|
474
|
+
socket = undefined;
|
|
475
|
+
for (const watcher of watchers.values()) watcher.close();
|
|
476
|
+
watchers.clear();
|
|
477
|
+
prefs = new Map();
|
|
478
|
+
registered = "";
|
|
479
|
+
return config;
|
|
480
|
+
}
|
|
481
|
+
|
|
482
|
+
/** Stops syncing and forgets the token, here and in `TOKEN_PATH`. Returns the session that ended. */
|
|
483
|
+
function endSession(): Config | undefined {
|
|
484
|
+
const config = stopSession();
|
|
485
|
+
if (config !== undefined) deleteToken();
|
|
486
|
+
return config;
|
|
487
|
+
}
|
|
488
|
+
|
|
489
|
+
/**
|
|
490
|
+
* Set when the server said the saved token was issued to another machine. The session is stopped and the
|
|
491
|
+
* token file kept; the CLI's requests are answered with `describeTokenOfAnotherMachine` until a sign-in.
|
|
492
|
+
*/
|
|
493
|
+
let tokenOfAnotherMachine: TokenOfAnotherMachine | undefined;
|
|
494
|
+
|
|
495
|
+
/** What to tell a person about a token issued to another machine, and the one command that fixes it. */
|
|
496
|
+
const describeTokenOfAnotherMachine = (cause: TokenOfAnotherMachine): string =>
|
|
497
|
+
`${CONFIG_PATH} names this machine "${cause.configuredMachine}", but the token in ${TOKEN_PATH} was issued to "${cause.tokenMachine}", `
|
|
498
|
+
+ `most likely copied from it. skill-sync stopped syncing and reporting here so this machine does not write as "${cause.tokenMachine}". `
|
|
499
|
+
+ `Run \`skill-sync login\` to sign this machine in as "${cause.configuredMachine}". `
|
|
500
|
+
+ `Do not run \`skill-sync logout\` here: it would revoke "${cause.tokenMachine}"'s token and sign that machine out.`;
|
|
501
|
+
|
|
502
|
+
/**
|
|
503
|
+
* Ends the session when the server refused its token: revoked or unknown (`TokenRejected`), it is deleted; issued
|
|
504
|
+
* to another machine (`TokenOfAnotherMachine`), syncing and reporting stop and the file is kept. Returns whether
|
|
505
|
+
* `cause` was such a refusal. Only for this session's token: a request still in flight from before a new
|
|
506
|
+
* sign-in may be refused too.
|
|
507
|
+
*/
|
|
508
|
+
function endRefusedSession(cause: unknown): boolean {
|
|
509
|
+
if (cause instanceof TokenRejected) {
|
|
510
|
+
if (session?.token !== cause.token) return true;
|
|
511
|
+
endSession();
|
|
512
|
+
console.error(`${cause.message}; signed out and deleted ${TOKEN_PATH}. Run \`skill-sync login\` to sign in again.`);
|
|
513
|
+
return true;
|
|
514
|
+
}
|
|
515
|
+
if (cause instanceof TokenOfAnotherMachine) {
|
|
516
|
+
if (session?.token !== cause.token) return true;
|
|
517
|
+
stopSession();
|
|
518
|
+
tokenOfAnotherMachine = cause;
|
|
519
|
+
console.error(describeTokenOfAnotherMachine(cause));
|
|
520
|
+
return true;
|
|
521
|
+
}
|
|
522
|
+
return false;
|
|
523
|
+
}
|
|
524
|
+
|
|
525
|
+
/** Why a request that needs the server cannot be made: no session, or a token that is another machine's. */
|
|
526
|
+
const signedOutMessage = (): string => tokenOfAnotherMachine !== undefined
|
|
527
|
+
? describeTokenOfAnotherMachine(tokenOfAnotherMachine)
|
|
528
|
+
: "this machine is signed out; run `skill-sync login` first";
|
|
529
|
+
|
|
530
|
+
/** Revokes the token on the server, forgets it, and stops syncing. Returns whether the revoke succeeded. */
|
|
531
|
+
async function signOut(): Promise<boolean> {
|
|
532
|
+
const config = endSession();
|
|
533
|
+
if (config === undefined) return false;
|
|
534
|
+
// Revoked, not just forgotten: a token copied while it was live would otherwise keep working.
|
|
535
|
+
// A token the server already rejects is as revoked as it can be.
|
|
536
|
+
const revoked = await fetchServer(config, "/cli/token", { method: "DELETE" })
|
|
537
|
+
.then((response) => response.ok, (cause: unknown) => cause instanceof TokenRejected);
|
|
538
|
+
console.log(`signed out${revoked ? "" : " (the server could not be reached to revoke the token)"}`);
|
|
539
|
+
return revoked;
|
|
540
|
+
}
|
|
541
|
+
|
|
542
|
+
let loginInProgress = false;
|
|
543
|
+
|
|
544
|
+
/**
|
|
545
|
+
* One sign-in: open a sign-in request on the server, tell the CLI the page that approves it, and claim the
|
|
546
|
+
* request every few seconds until a passkey has approved it, on this computer or any other, or it expires.
|
|
547
|
+
* The claim secret stays in this process, so only this daemon can collect the token.
|
|
548
|
+
*/
|
|
549
|
+
function login(reply: Reply): void {
|
|
550
|
+
if (loginInProgress) {
|
|
551
|
+
reply.send({ type: "error", message: "a sign-in is already in progress" });
|
|
552
|
+
return;
|
|
553
|
+
}
|
|
554
|
+
loginInProgress = true;
|
|
555
|
+
const fail = (message: string): void => {
|
|
556
|
+
loginInProgress = false;
|
|
557
|
+
reply.send({ type: "error", message });
|
|
558
|
+
};
|
|
559
|
+
openSignInRequest({ endpoint: settings!.endpoint, machine: settings!.machine }).then(
|
|
560
|
+
({ url, claimSecret, expiresAt }) => {
|
|
561
|
+
reply.send({ type: "open", url });
|
|
562
|
+
const claim = (): void => {
|
|
563
|
+
claimSignInRequest({ endpoint: settings!.endpoint, claimSecret }).then(
|
|
564
|
+
(answer) => {
|
|
565
|
+
if (answer.state === "pending") return void setTimeout(claim, SIGN_IN_CLAIM_MS);
|
|
566
|
+
if (answer.state === "expired") return fail("the sign-in expired before it was approved; run `skill-sync login` again");
|
|
567
|
+
loginInProgress = false;
|
|
568
|
+
signIn(answer.token).then(
|
|
569
|
+
() => reply.send({ type: "signedIn", machine: settings!.machine }),
|
|
570
|
+
(cause) => reply.send({ type: "error", message: `the server refused the sign-in: ${describeError(cause)}` }),
|
|
571
|
+
);
|
|
572
|
+
},
|
|
573
|
+
// The network can drop for a moment while someone fetches their phone; the request outlives it, until it expires.
|
|
574
|
+
(cause) => Date.now() > expiresAt
|
|
575
|
+
? fail(`could not reach the server before the sign-in expired: ${describeError(cause)}`)
|
|
576
|
+
: void setTimeout(claim, SIGN_IN_CLAIM_MS),
|
|
577
|
+
);
|
|
578
|
+
};
|
|
579
|
+
claim();
|
|
580
|
+
},
|
|
581
|
+
(cause) => fail(`could not start a sign-in: ${describeError(cause)}`),
|
|
582
|
+
);
|
|
583
|
+
}
|
|
584
|
+
|
|
585
|
+
const describeError = (cause: unknown): string => cause instanceof Error ? cause.message : String(cause);
|
|
586
|
+
|
|
587
|
+
/** The synced list, from the server: the CLI has no token to ask with, so it asks this daemon. */
|
|
588
|
+
function list(reply: Reply): void {
|
|
589
|
+
const config = session;
|
|
590
|
+
if (config === undefined) {
|
|
591
|
+
reply.send({ type: "error", message: signedOutMessage() });
|
|
592
|
+
return;
|
|
593
|
+
}
|
|
594
|
+
fetchSyncedSkills(config)
|
|
595
|
+
.then((skills) => reply.send({ type: "list", skills }))
|
|
596
|
+
.catch((cause: unknown) => {
|
|
597
|
+
if (endRefusedSession(cause)) {
|
|
598
|
+
reply.send({ type: "error", message: signedOutMessage() });
|
|
599
|
+
return;
|
|
600
|
+
}
|
|
601
|
+
reply.send({ type: "error", message: `could not reach the server: ${cause instanceof Error ? cause.message : String(cause)}` });
|
|
602
|
+
});
|
|
603
|
+
}
|
|
604
|
+
|
|
605
|
+
/**
|
|
606
|
+
* Puts a skill from this machine on the synced list, for an agent that has just written it. The files are
|
|
607
|
+
* checked here, where they are; the server only adds the name, and every daemon then syncs the skill.
|
|
608
|
+
*/
|
|
609
|
+
function add(skill: string, reply: Reply): void {
|
|
610
|
+
const config = session;
|
|
611
|
+
if (config === undefined) {
|
|
612
|
+
reply.send({ type: "error", message: signedOutMessage() });
|
|
613
|
+
return;
|
|
614
|
+
}
|
|
615
|
+
const check = checkSkillToAdd({ skill, folders: detectFolders(), exclude: config.exclude });
|
|
616
|
+
if (!check.ok) {
|
|
617
|
+
reply.send({ type: "error", message: check.reason });
|
|
618
|
+
return;
|
|
619
|
+
}
|
|
620
|
+
fetchServer(config, `/skills/${encodeURIComponent(skill)}`, { method: "PUT" })
|
|
621
|
+
.then(async (response) => {
|
|
622
|
+
if (!response.ok) throw new Error(`PUT /skills/${skill}: ${response.status} ${await response.text()}`);
|
|
623
|
+
const { added } = await response.json() as AddSkillResponse;
|
|
624
|
+
reply.send({
|
|
625
|
+
type: "added", skill, added, folders: check.folders,
|
|
626
|
+
syncingFolders: check.folders.filter((folder) => prefs.has(folder)),
|
|
627
|
+
});
|
|
628
|
+
})
|
|
629
|
+
.catch((cause: unknown) => {
|
|
630
|
+
if (endRefusedSession(cause)) {
|
|
631
|
+
reply.send({ type: "error", message: signedOutMessage() });
|
|
632
|
+
return;
|
|
633
|
+
}
|
|
634
|
+
reply.send({ type: "error", message: `could not reach the server: ${cause instanceof Error ? cause.message : String(cause)}` });
|
|
635
|
+
});
|
|
636
|
+
}
|
|
637
|
+
|
|
638
|
+
function handleControl(message: ControlRequest, reply: Reply): void {
|
|
639
|
+
if (message.type === "login") login(reply);
|
|
640
|
+
// A token issued to another machine is that machine's sign-in: revoking it would sign that machine out.
|
|
641
|
+
else if (message.type === "logout" && tokenOfAnotherMachine !== undefined) reply.send({ type: "error", message: signedOutMessage() });
|
|
642
|
+
else if (message.type === "logout") void signOut().then((revoked) => reply.send({ type: "signedOut", revoked }));
|
|
643
|
+
else if (message.type === "list") list(reply);
|
|
644
|
+
else if (message.type === "add") add(message.skill, reply);
|
|
645
|
+
else if (message.type === "feedback") addFeedback(message, reply);
|
|
646
|
+
else if (message.type === "watching") watching(reply);
|
|
647
|
+
else if (message.type === "reply") postReply(message, reply);
|
|
648
|
+
else reply.send({ type: "error", message: `unknown request ${JSON.stringify(message)}` });
|
|
649
|
+
}
|
|
650
|
+
|
|
651
|
+
if (await serve(handleControl) === false) {
|
|
652
|
+
console.log("another skill-sync daemon is already running for this user; standing down");
|
|
653
|
+
// Zero: a second install's daemon is not a failure, and the service manager must not keep retrying it.
|
|
654
|
+
process.exit(0);
|
|
655
|
+
}
|
|
656
|
+
// Only after taking the control socket: a daemon that stands down must not sync, or upgrade, too.
|
|
657
|
+
autoUpgrade({ packageName: name });
|
|
658
|
+
startSkillRefinement({
|
|
659
|
+
home: homedir(),
|
|
660
|
+
managed: managedDaemon({ home: homedir(), machine: settings.machine, signal: new AbortController().signal }),
|
|
661
|
+
claudeCommand: findCommand({ name: "claude", home: homedir(), also: [join(homedir(), ".claude", "local", "claude")] }),
|
|
662
|
+
syncedSkills,
|
|
663
|
+
onState: (state) => {
|
|
664
|
+
refinement = state;
|
|
665
|
+
if ("notRunning" in state) console.log(`skill refinement: ${state.notRunning}`);
|
|
666
|
+
void reportRefinement();
|
|
667
|
+
},
|
|
668
|
+
}).catch((cause: unknown) => {
|
|
669
|
+
refinement = { notRunning: `it could not start: ${describeError(cause)}` };
|
|
670
|
+
console.error(`skill refinement: ${refinement.notRunning}`);
|
|
671
|
+
void reportRefinement();
|
|
672
|
+
});
|
|
673
|
+
startWatch(startCommentWatch({ home: homedir(), settingsFile: CONFIG_PATH, claudeCommand: findCommand({ name: "claude", home: homedir(), also: [join(homedir(), ".claude", "local", "claude")] }) }));
|
|
674
|
+
void commentWatch.started.then((watch) => console.log(`comment watch: ${watch.notWatching ?? "watching"}`));
|
|
675
|
+
const savedToken = loadToken();
|
|
676
|
+
if (savedToken !== undefined) resume(savedToken);
|
|
677
|
+
else console.log(`skill-sync daemon for ${settings.machine}; waiting for \`skill-sync login\``);
|