@scopebond/agent 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +201 -0
- package/README.md +42 -0
- package/dist/agent.d.ts +26 -0
- package/dist/agent.d.ts.map +1 -0
- package/dist/agent.js +79 -0
- package/dist/agent.js.map +1 -0
- package/dist/autostart.d.ts +13 -0
- package/dist/autostart.d.ts.map +1 -0
- package/dist/autostart.js +113 -0
- package/dist/autostart.js.map +1 -0
- package/dist/cli.d.ts +3 -0
- package/dist/cli.d.ts.map +1 -0
- package/dist/cli.js +92 -0
- package/dist/cli.js.map +1 -0
- package/dist/index.d.ts +8 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +5 -0
- package/dist/index.js.map +1 -0
- package/dist/ipc.d.ts +21 -0
- package/dist/ipc.d.ts.map +1 -0
- package/dist/ipc.js +84 -0
- package/dist/ipc.js.map +1 -0
- package/dist/service.d.ts +22 -0
- package/dist/service.d.ts.map +1 -0
- package/dist/service.js +70 -0
- package/dist/service.js.map +1 -0
- package/package.json +53 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or Derivative
|
|
95
|
+
Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
177
|
+
|
|
178
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
179
|
+
|
|
180
|
+
To apply the Apache License to your work, attach the following
|
|
181
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
182
|
+
replaced with your own identifying information. (Don't include
|
|
183
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
184
|
+
comment syntax for the file format. We also recommend that a
|
|
185
|
+
file or class name and description of purpose be included on the
|
|
186
|
+
same "printed page" as the copyright notice for easier
|
|
187
|
+
identification within third-party archives.
|
|
188
|
+
|
|
189
|
+
Copyright 2026 Avouro LLC
|
|
190
|
+
|
|
191
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
192
|
+
you may not use this file except in compliance with the License.
|
|
193
|
+
You may obtain a copy of the License at
|
|
194
|
+
|
|
195
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
196
|
+
|
|
197
|
+
Unless required by applicable law or agreed to in writing, software
|
|
198
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
199
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
200
|
+
See the License for the specific language governing permissions and
|
|
201
|
+
limitations under the License.
|
package/README.md
ADDED
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
# @scopebond/agent
|
|
2
|
+
|
|
3
|
+
The Scopebond Agent keeps a computer connected to its Scopebond workspace without anyone running a command.
|
|
4
|
+
It is one resident process per user. The hook (`@scopebond/hook`) keeps deciding every action on its own; the
|
|
5
|
+
agent never takes part in a decision. It only keeps everything around the decisions working:
|
|
6
|
+
|
|
7
|
+
- **Delivery.** It sends the records the hook queued, all of them, with backoff while the workspace is unreachable.
|
|
8
|
+
A record the workspace refuses on its own is kept as a gap and never holds up the rest.
|
|
9
|
+
- **Rules and connection.** It runs the rules check, which brings the workspace's rules, reports this computer's
|
|
10
|
+
queue, and renews the machine credential before it expires.
|
|
11
|
+
- **Repair.** It notices when an agent's settings lost the Scopebond hook entry (an update or a reset can remove it)
|
|
12
|
+
and, on request, puts it back without touching anything else in the file.
|
|
13
|
+
- **Health.** It reports the same machine-readable status as `scopebond status --json` (`scopebond.status.v1`).
|
|
14
|
+
|
|
15
|
+
## Use
|
|
16
|
+
|
|
17
|
+
```bash
|
|
18
|
+
npm install -g @scopebond/agent
|
|
19
|
+
scopebond-agent autostart on # start with your sign-in (Windows Run entry, macOS LaunchAgent, Linux systemd user unit)
|
|
20
|
+
scopebond-agent status # what it reports about this computer
|
|
21
|
+
```
|
|
22
|
+
|
|
23
|
+
On Windows, type `npx.cmd` instead of `npx` in PowerShell if you run it without installing.
|
|
24
|
+
|
|
25
|
+
| Command | What it does |
|
|
26
|
+
|---|---|
|
|
27
|
+
| `scopebond-agent run` | Run in the foreground (what autostart starts) |
|
|
28
|
+
| `scopebond-agent status [--json]` | Delivery state, records waiting and the last problem |
|
|
29
|
+
| `scopebond-agent flush` | Deliver waiting records now |
|
|
30
|
+
| `scopebond-agent repair` | Put the Scopebond hook back into agent settings that lost it |
|
|
31
|
+
| `scopebond-agent autostart on\|off` | Start with your sign-in, or stop doing so |
|
|
32
|
+
|
|
33
|
+
## Local control channel
|
|
34
|
+
|
|
35
|
+
The agent listens on `127.0.0.1` only, on a random port, and every request must carry a random token. Port, token and
|
|
36
|
+
process id are in `~/.scopebond/agent.json`, readable by you only. Routes: `GET /status`, `POST /flush`, `POST /repair`.
|
|
37
|
+
Exactly one agent serves a computer's Scopebond home; a second one exits.
|
|
38
|
+
|
|
39
|
+
## Status
|
|
40
|
+
|
|
41
|
+
Experimental. A tray window with a one-click fix for every amber or red state, signed installers and signed updates
|
|
42
|
+
are next.
|
package/dist/agent.d.ts
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
import { type Harness, type StatusJson, type SyncOutcome } from "@scopebond/hook";
|
|
2
|
+
export interface CycleOptions {
|
|
3
|
+
/** The Scopebond home this agent serves (the user's ~/.scopebond by default). */
|
|
4
|
+
dir: string;
|
|
5
|
+
fetchImpl?: typeof fetch;
|
|
6
|
+
now?: () => number;
|
|
7
|
+
/** Per-request timeout for the workspace, in milliseconds. */
|
|
8
|
+
timeoutMs?: number;
|
|
9
|
+
}
|
|
10
|
+
export interface CycleResult {
|
|
11
|
+
at: number;
|
|
12
|
+
connected: boolean;
|
|
13
|
+
delivered: number;
|
|
14
|
+
pending: number;
|
|
15
|
+
deliveryError: string | null;
|
|
16
|
+
rules: SyncOutcome["state"] | "skipped";
|
|
17
|
+
missingHookEntries: Harness[];
|
|
18
|
+
}
|
|
19
|
+
/** The agents on this computer whose user-level settings should hold the Scopebond hook. */
|
|
20
|
+
export declare function expectedHarnesses(): Harness[];
|
|
21
|
+
/** Agent settings that lost their Scopebond hook entry (an update or a reset can remove it). */
|
|
22
|
+
export declare function missingHookEntries(harnesses?: Harness[]): Harness[];
|
|
23
|
+
export declare function runCycle(options: CycleOptions): Promise<CycleResult>;
|
|
24
|
+
/** The machine-readable status (scopebond.status.v1) for this computer, as the hook reports it. */
|
|
25
|
+
export declare function computerStatus(dir: string, now?: number): StatusJson;
|
|
26
|
+
//# sourceMappingURL=agent.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"agent.d.ts","sourceRoot":"","sources":["../src/agent.ts"],"names":[],"mappings":"AAWA,OAAO,EAGL,KAAK,OAAO,EAAE,KAAK,UAAU,EAAE,KAAK,WAAW,EAChD,MAAM,iBAAiB,CAAC;AAEzB,MAAM,WAAW,YAAY;IAC3B,iFAAiF;IACjF,GAAG,EAAE,MAAM,CAAC;IACZ,SAAS,CAAC,EAAE,OAAO,KAAK,CAAC;IACzB,GAAG,CAAC,EAAE,MAAM,MAAM,CAAC;IACnB,8DAA8D;IAC9D,SAAS,CAAC,EAAE,MAAM,CAAC;CACpB;AAED,MAAM,WAAW,WAAW;IAC1B,EAAE,EAAE,MAAM,CAAC;IACX,SAAS,EAAE,OAAO,CAAC;IACnB,SAAS,EAAE,MAAM,CAAC;IAClB,OAAO,EAAE,MAAM,CAAC;IAChB,aAAa,EAAE,MAAM,GAAG,IAAI,CAAC;IAC7B,KAAK,EAAE,WAAW,CAAC,OAAO,CAAC,GAAG,SAAS,CAAC;IACxC,kBAAkB,EAAE,OAAO,EAAE,CAAC;CAC/B;AAED,4FAA4F;AAC5F,wBAAgB,iBAAiB,IAAI,OAAO,EAAE,CAE7C;AAED,gGAAgG;AAChG,wBAAgB,kBAAkB,CAAC,SAAS,GAAE,OAAO,EAAwB,GAAG,OAAO,EAAE,CAExF;AAED,wBAAsB,QAAQ,CAAC,OAAO,EAAE,YAAY,GAAG,OAAO,CAAC,WAAW,CAAC,CAwC1E;AAED,mGAAmG;AACnG,wBAAgB,cAAc,CAAC,GAAG,EAAE,MAAM,EAAE,GAAG,CAAC,EAAE,MAAM,GAAG,UAAU,CAOpE"}
|
package/dist/agent.js
ADDED
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
// The Scopebond Agent's work, one cycle at a time. The hook still decides every action on its
|
|
2
|
+
// own (enforcement never depends on the agent); the agent keeps everything around it working:
|
|
3
|
+
// it delivers what the hook queued, keeps the workspace rules and the connection current, and
|
|
4
|
+
// knows when the agent settings lost their hook entry. Every step is best-effort and bounded;
|
|
5
|
+
// a cycle never throws.
|
|
6
|
+
import { existsSync, readFileSync } from "node:fs";
|
|
7
|
+
import { join } from "node:path";
|
|
8
|
+
import { createCloudExporter } from "@scopebond/gateway";
|
|
9
|
+
import { SqliteCloudOutbox } from "@scopebond/gateway/node";
|
|
10
|
+
import { createSigner } from "@scopebond/sdk";
|
|
11
|
+
import { LOSSLESS_OUTBOX, OUTBOX_FILE, buildStatusJson, cursorDetected, codexDetected, hookVersion, ingestUrl, isHarnessConfigured, loadConnection, policyBuilds, recordDeliveryAttempt, syncPolicy, userHarnessFile, } from "@scopebond/hook";
|
|
12
|
+
/** The agents on this computer whose user-level settings should hold the Scopebond hook. */
|
|
13
|
+
export function expectedHarnesses() {
|
|
14
|
+
return ["claude", ...(cursorDetected() ? ["cursor"] : []), ...(codexDetected() ? ["codex"] : [])];
|
|
15
|
+
}
|
|
16
|
+
/** Agent settings that lost their Scopebond hook entry (an update or a reset can remove it). */
|
|
17
|
+
export function missingHookEntries(harnesses = expectedHarnesses()) {
|
|
18
|
+
return harnesses.filter((h) => existsSync(userHarnessFile(h)) && !isHarnessConfigured(userHarnessFile(h)));
|
|
19
|
+
}
|
|
20
|
+
export async function runCycle(options) {
|
|
21
|
+
const now = options.now ?? Date.now;
|
|
22
|
+
const dir = options.dir;
|
|
23
|
+
const result = { at: now(), connected: false, delivered: 0, pending: 0, deliveryError: null, rules: "skipped", missingHookEntries: [] };
|
|
24
|
+
try {
|
|
25
|
+
result.missingHookEntries = missingHookEntries();
|
|
26
|
+
}
|
|
27
|
+
catch { /* reported as none */ }
|
|
28
|
+
const connection = loadConnection(dir);
|
|
29
|
+
if (!connection)
|
|
30
|
+
return result;
|
|
31
|
+
result.connected = true;
|
|
32
|
+
// 1. Deliver everything the hook queued, in batches, until the queue is empty or the workspace refuses.
|
|
33
|
+
try {
|
|
34
|
+
const outbox = new SqliteCloudOutbox(join(dir, OUTBOX_FILE), LOSSLESS_OUTBOX);
|
|
35
|
+
const before = outbox.status().pending;
|
|
36
|
+
const exporter = createCloudExporter({
|
|
37
|
+
url: ingestUrl(connection), credential: connection.credential, outbox,
|
|
38
|
+
flushMs: 24 * 60 * 60 * 1000, fetch: options.fetchImpl, now,
|
|
39
|
+
});
|
|
40
|
+
try {
|
|
41
|
+
const lastSuccess = exporter.status().lastSuccessAt;
|
|
42
|
+
await exporter.flush();
|
|
43
|
+
const status = exporter.status();
|
|
44
|
+
recordDeliveryAttempt(dir, status, now(), lastSuccess);
|
|
45
|
+
result.pending = status.pending;
|
|
46
|
+
result.delivered = Math.max(0, before - status.pending);
|
|
47
|
+
result.deliveryError = status.lastError;
|
|
48
|
+
}
|
|
49
|
+
finally {
|
|
50
|
+
exporter.stop();
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
catch (error) {
|
|
54
|
+
result.deliveryError = error.message;
|
|
55
|
+
}
|
|
56
|
+
// 2. The rules check: the workspace's rules, the queue report, and credential renewal when due.
|
|
57
|
+
try {
|
|
58
|
+
const keyFile = join(dir, "agent.key");
|
|
59
|
+
if (existsSync(keyFile)) {
|
|
60
|
+
const agentKid = createSigner({ privateKeyPem: readFileSync(keyFile, "utf8") }).kid;
|
|
61
|
+
const outcome = await syncPolicy(dir, { agentKid, hookVersion: hookVersion(), policyBuilds, fetchImpl: options.fetchImpl, timeoutMs: options.timeoutMs ?? 10_000 });
|
|
62
|
+
result.rules = outcome.state;
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
catch {
|
|
66
|
+
result.rules = "unavailable";
|
|
67
|
+
}
|
|
68
|
+
return result;
|
|
69
|
+
}
|
|
70
|
+
/** The machine-readable status (scopebond.status.v1) for this computer, as the hook reports it. */
|
|
71
|
+
export function computerStatus(dir, now) {
|
|
72
|
+
const expected = expectedHarnesses();
|
|
73
|
+
const configured = (h) => expected.includes(h) && existsSync(userHarnessFile(h)) && isHarnessConfigured(userHarnessFile(h));
|
|
74
|
+
return buildStatusJson({
|
|
75
|
+
version: hookVersion(), activeDir: dir, candidateDirs: [dir], hasPolicy: existsSync(join(dir, "policy.json")),
|
|
76
|
+
agents: { claude: configured("claude"), cursor: configured("cursor"), codex: configured("codex") }, now,
|
|
77
|
+
});
|
|
78
|
+
}
|
|
79
|
+
//# sourceMappingURL=agent.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"agent.js","sourceRoot":"","sources":["../src/agent.ts"],"names":[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EAAE,CAAC,QAAQ,CAAC,QAAQ,CAAC,CAAC,CAAC,IAAI,UAAU,CAAC,eAAe,CAAC,CAAC,CAAC,CAAC,IAAI,mBAAmB,CAAC,eAAe,CAAC,CAAC,CAAC,CAAC,CAAC;IACrI,OAAO,eAAe,CAAC;QACrB,OAAO,EAAE,WAAW,EAAE,EAAE,SAAS,EAAE,GAAG,EAAE,aAAa,EAAE,CAAC,GAAG,CAAC,EAAE,SAAS,EAAE,UAAU,CAAC,IAAI,CAAC,GAAG,EAAE,aAAa,CAAC,CAAC;QAC7G,MAAM,EAAE,EAAE,MAAM,EAAE,UAAU,CAAC,QAAQ,CAAC,EAAE,MAAM,EAAE,UAAU,CAAC,QAAQ,CAAC,EAAE,KAAK,EAAE,UAAU,CAAC,OAAO,CAAC,EAAE,EAAE,GAAG;KACxG,CAAC,CAAC;AACL,CAAC","sourcesContent":["// The Scopebond Agent's work, one cycle at a time. The hook still decides every action on its\n// own (enforcement never depends on the agent); the agent keeps everything around it working:\n// it delivers what the hook queued, keeps the workspace rules and the connection current, and\n// knows when the agent settings lost their hook entry. Every step is best-effort and bounded;\n// a cycle never throws.\n\nimport { existsSync, readFileSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport { createCloudExporter } from \"@scopebond/gateway\";\nimport { SqliteCloudOutbox } from \"@scopebond/gateway/node\";\nimport { createSigner } from \"@scopebond/sdk\";\nimport {\n LOSSLESS_OUTBOX, OUTBOX_FILE, buildStatusJson, cursorDetected, codexDetected, hookVersion, ingestUrl,\n isHarnessConfigured, loadConnection, policyBuilds, recordDeliveryAttempt, syncPolicy, userHarnessFile,\n type Harness, type StatusJson, type SyncOutcome,\n} from \"@scopebond/hook\";\n\nexport interface CycleOptions {\n /** The Scopebond home this agent serves (the user's ~/.scopebond by default). */\n dir: string;\n fetchImpl?: typeof fetch;\n now?: () => number;\n /** Per-request timeout for the workspace, in milliseconds. */\n timeoutMs?: number;\n}\n\nexport interface CycleResult {\n at: number;\n connected: boolean;\n delivered: number;\n pending: number;\n deliveryError: string | null;\n rules: SyncOutcome[\"state\"] | \"skipped\";\n missingHookEntries: Harness[];\n}\n\n/** The agents on this computer whose user-level settings should hold the Scopebond hook. */\nexport function expectedHarnesses(): Harness[] {\n return [\"claude\", ...(cursorDetected() ? [\"cursor\" as const] : []), ...(codexDetected() ? [\"codex\" as const] : [])];\n}\n\n/** Agent settings that lost their Scopebond hook entry (an update or a reset can remove it). */\nexport function missingHookEntries(harnesses: Harness[] = expectedHarnesses()): Harness[] {\n return harnesses.filter((h) => existsSync(userHarnessFile(h)) && !isHarnessConfigured(userHarnessFile(h)));\n}\n\nexport async function runCycle(options: CycleOptions): Promise<CycleResult> {\n const now = options.now ?? Date.now;\n const dir = options.dir;\n const result: CycleResult = { at: now(), connected: false, delivered: 0, pending: 0, deliveryError: null, rules: \"skipped\", missingHookEntries: [] };\n try { result.missingHookEntries = missingHookEntries(); } catch { /* reported as none */ }\n const connection = loadConnection(dir);\n if (!connection) return result;\n result.connected = true;\n\n // 1. Deliver everything the hook queued, in batches, until the queue is empty or the workspace refuses.\n try {\n const outbox = new SqliteCloudOutbox(join(dir, OUTBOX_FILE), LOSSLESS_OUTBOX);\n const before = outbox.status().pending;\n const exporter = createCloudExporter({\n url: ingestUrl(connection), credential: connection.credential, outbox,\n flushMs: 24 * 60 * 60 * 1000, fetch: options.fetchImpl, now,\n });\n try {\n const lastSuccess = exporter.status().lastSuccessAt;\n await exporter.flush();\n const status = exporter.status();\n recordDeliveryAttempt(dir, status, now(), lastSuccess);\n result.pending = status.pending;\n result.delivered = Math.max(0, before - status.pending);\n result.deliveryError = status.lastError;\n } finally { exporter.stop(); }\n } catch (error) {\n result.deliveryError = (error as Error).message;\n }\n\n // 2. The rules check: the workspace's rules, the queue report, and credential renewal when due.\n try {\n const keyFile = join(dir, \"agent.key\");\n if (existsSync(keyFile)) {\n const agentKid = createSigner({ privateKeyPem: readFileSync(keyFile, \"utf8\") }).kid;\n const outcome = await syncPolicy(dir, { agentKid, hookVersion: hookVersion(), policyBuilds, fetchImpl: options.fetchImpl, timeoutMs: options.timeoutMs ?? 10_000 });\n result.rules = outcome.state;\n }\n } catch { result.rules = \"unavailable\"; }\n return result;\n}\n\n/** The machine-readable status (scopebond.status.v1) for this computer, as the hook reports it. */\nexport function computerStatus(dir: string, now?: number): StatusJson {\n const expected = expectedHarnesses();\n const configured = (h: Harness) => expected.includes(h) && existsSync(userHarnessFile(h)) && isHarnessConfigured(userHarnessFile(h));\n return buildStatusJson({\n version: hookVersion(), activeDir: dir, candidateDirs: [dir], hasPolicy: existsSync(join(dir, \"policy.json\")),\n agents: { claude: configured(\"claude\"), cursor: configured(\"cursor\"), codex: configured(\"codex\") }, now,\n });\n}\n"]}
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
export declare const LABEL = "com.scopebond.agent";
|
|
2
|
+
export declare function windowsRunCommand(node: string, cli: string): string;
|
|
3
|
+
export declare function macLaunchAgent(node: string, cli: string, logFile: string): string;
|
|
4
|
+
export declare function linuxUserUnit(node: string, cli: string): string;
|
|
5
|
+
export declare function autostartPaths(home?: string): {
|
|
6
|
+
macPlist: string;
|
|
7
|
+
linuxUnit: string;
|
|
8
|
+
log: string;
|
|
9
|
+
};
|
|
10
|
+
/** Turn autostart on for this user. Returns a one-line description of what changed. */
|
|
11
|
+
export declare function enableAutostart(cli: string, node?: string, platform?: NodeJS.Platform): string;
|
|
12
|
+
export declare function disableAutostart(platform?: NodeJS.Platform): string;
|
|
13
|
+
//# sourceMappingURL=autostart.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"autostart.d.ts","sourceRoot":"","sources":["../src/autostart.ts"],"names":[],"mappings":"AAUA,eAAO,MAAM,KAAK,wBAAwB,CAAC;AAO3C,wBAAgB,iBAAiB,CAAC,IAAI,EAAE,MAAM,EAAE,GAAG,EAAE,MAAM,GAAG,MAAM,CAEnE;AAED,wBAAgB,cAAc,CAAC,IAAI,EAAE,MAAM,EAAE,GAAG,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,GAAG,MAAM,CAejF;AAED,wBAAgB,aAAa,CAAC,IAAI,EAAE,MAAM,EAAE,GAAG,EAAE,MAAM,GAAG,MAAM,CAc/D;AAED,wBAAgB,cAAc,CAAC,IAAI,SAAY;;;;EAM9C;AAED,uFAAuF;AACvF,wBAAgB,eAAe,CAAC,GAAG,EAAE,MAAM,EAAE,IAAI,SAAmB,EAAE,QAAQ,kBAAmB,GAAG,MAAM,CAkBzG;AAED,wBAAgB,gBAAgB,CAAC,QAAQ,kBAAmB,GAAG,MAAM,CAgBpE"}
|
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
// Start the agent when the person signs in to the computer, per user, with no administrator
|
|
2
|
+
// rights: a Run entry on Windows, a LaunchAgent on macOS, a systemd user unit on Linux. The
|
|
3
|
+
// builders are pure (and tested); `enable`/`disable` apply them. The command pins this Node and
|
|
4
|
+
// this agent's absolute path, so it never depends on a shell's PATH or npm's temporary cache.
|
|
5
|
+
import { execFileSync } from "node:child_process";
|
|
6
|
+
import { existsSync, mkdirSync, rmSync, writeFileSync } from "node:fs";
|
|
7
|
+
import { homedir } from "node:os";
|
|
8
|
+
import { dirname, join } from "node:path";
|
|
9
|
+
export const LABEL = "com.scopebond.agent";
|
|
10
|
+
const RUN_KEY = "HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Run";
|
|
11
|
+
const RUN_VALUE = "ScopebondAgent";
|
|
12
|
+
const quoteWin = (s) => `"${s.replace(/"/g, "")}"`;
|
|
13
|
+
const xml = (s) => s.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">");
|
|
14
|
+
export function windowsRunCommand(node, cli) {
|
|
15
|
+
return `${quoteWin(node)} ${quoteWin(cli)} run`;
|
|
16
|
+
}
|
|
17
|
+
export function macLaunchAgent(node, cli, logFile) {
|
|
18
|
+
return `<?xml version="1.0" encoding="UTF-8"?>
|
|
19
|
+
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
|
20
|
+
<plist version="1.0">
|
|
21
|
+
<dict>
|
|
22
|
+
<key>Label</key><string>${LABEL}</string>
|
|
23
|
+
<key>ProgramArguments</key>
|
|
24
|
+
<array><string>${xml(node)}</string><string>${xml(cli)}</string><string>run</string></array>
|
|
25
|
+
<key>RunAtLoad</key><true/>
|
|
26
|
+
<key>KeepAlive</key><dict><key>SuccessfulExit</key><false/></dict>
|
|
27
|
+
<key>StandardOutPath</key><string>${xml(logFile)}</string>
|
|
28
|
+
<key>StandardErrorPath</key><string>${xml(logFile)}</string>
|
|
29
|
+
</dict>
|
|
30
|
+
</plist>
|
|
31
|
+
`;
|
|
32
|
+
}
|
|
33
|
+
export function linuxUserUnit(node, cli) {
|
|
34
|
+
const q = (s) => `"${s.replace(/(["\\])/g, "\\$1")}"`;
|
|
35
|
+
return `[Unit]
|
|
36
|
+
Description=Scopebond Agent (delivers this computer's records to its Scopebond workspace)
|
|
37
|
+
After=network-online.target
|
|
38
|
+
|
|
39
|
+
[Service]
|
|
40
|
+
ExecStart=${q(node)} ${q(cli)} run
|
|
41
|
+
Restart=on-failure
|
|
42
|
+
RestartSec=30
|
|
43
|
+
|
|
44
|
+
[Install]
|
|
45
|
+
WantedBy=default.target
|
|
46
|
+
`;
|
|
47
|
+
}
|
|
48
|
+
export function autostartPaths(home = homedir()) {
|
|
49
|
+
return {
|
|
50
|
+
macPlist: join(home, "Library", "LaunchAgents", `${LABEL}.plist`),
|
|
51
|
+
linuxUnit: join(home, ".config", "systemd", "user", "scopebond-agent.service"),
|
|
52
|
+
log: join(home, ".scopebond", "agent.log"),
|
|
53
|
+
};
|
|
54
|
+
}
|
|
55
|
+
/** Turn autostart on for this user. Returns a one-line description of what changed. */
|
|
56
|
+
export function enableAutostart(cli, node = process.execPath, platform = process.platform) {
|
|
57
|
+
const paths = autostartPaths();
|
|
58
|
+
if (platform === "win32") {
|
|
59
|
+
execFileSync("reg", ["add", RUN_KEY, "/v", RUN_VALUE, "/t", "REG_SZ", "/d", windowsRunCommand(node, cli), "/f"], { stdio: "ignore" });
|
|
60
|
+
return `added ${RUN_VALUE} to ${RUN_KEY}`;
|
|
61
|
+
}
|
|
62
|
+
if (platform === "darwin") {
|
|
63
|
+
mkdirSync(dirname(paths.macPlist), { recursive: true });
|
|
64
|
+
mkdirSync(dirname(paths.log), { recursive: true });
|
|
65
|
+
writeFileSync(paths.macPlist, macLaunchAgent(node, cli, paths.log));
|
|
66
|
+
try {
|
|
67
|
+
execFileSync("launchctl", ["load", "-w", paths.macPlist], { stdio: "ignore" });
|
|
68
|
+
}
|
|
69
|
+
catch { /* loads at next sign-in */ }
|
|
70
|
+
return `wrote ${paths.macPlist}`;
|
|
71
|
+
}
|
|
72
|
+
mkdirSync(dirname(paths.linuxUnit), { recursive: true });
|
|
73
|
+
writeFileSync(paths.linuxUnit, linuxUserUnit(node, cli));
|
|
74
|
+
try {
|
|
75
|
+
execFileSync("systemctl", ["--user", "daemon-reload"], { stdio: "ignore" });
|
|
76
|
+
execFileSync("systemctl", ["--user", "enable", "--now", "scopebond-agent.service"], { stdio: "ignore" });
|
|
77
|
+
}
|
|
78
|
+
catch {
|
|
79
|
+
return `wrote ${paths.linuxUnit} (enable it with: systemctl --user enable --now scopebond-agent)`;
|
|
80
|
+
}
|
|
81
|
+
return `wrote and enabled ${paths.linuxUnit}`;
|
|
82
|
+
}
|
|
83
|
+
export function disableAutostart(platform = process.platform) {
|
|
84
|
+
const paths = autostartPaths();
|
|
85
|
+
if (platform === "win32") {
|
|
86
|
+
try {
|
|
87
|
+
execFileSync("reg", ["delete", RUN_KEY, "/v", RUN_VALUE, "/f"], { stdio: "ignore" });
|
|
88
|
+
}
|
|
89
|
+
catch {
|
|
90
|
+
return "autostart was not on";
|
|
91
|
+
}
|
|
92
|
+
return `removed ${RUN_VALUE} from ${RUN_KEY}`;
|
|
93
|
+
}
|
|
94
|
+
if (platform === "darwin") {
|
|
95
|
+
if (!existsSync(paths.macPlist))
|
|
96
|
+
return "autostart was not on";
|
|
97
|
+
try {
|
|
98
|
+
execFileSync("launchctl", ["unload", "-w", paths.macPlist], { stdio: "ignore" });
|
|
99
|
+
}
|
|
100
|
+
catch { /* not loaded */ }
|
|
101
|
+
rmSync(paths.macPlist, { force: true });
|
|
102
|
+
return `removed ${paths.macPlist}`;
|
|
103
|
+
}
|
|
104
|
+
if (!existsSync(paths.linuxUnit))
|
|
105
|
+
return "autostart was not on";
|
|
106
|
+
try {
|
|
107
|
+
execFileSync("systemctl", ["--user", "disable", "--now", "scopebond-agent.service"], { stdio: "ignore" });
|
|
108
|
+
}
|
|
109
|
+
catch { /* not enabled */ }
|
|
110
|
+
rmSync(paths.linuxUnit, { force: true });
|
|
111
|
+
return `removed ${paths.linuxUnit}`;
|
|
112
|
+
}
|
|
113
|
+
//# sourceMappingURL=autostart.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"autostart.js","sourceRoot":"","sources":["../src/autostart.ts"],"names":[],"mappings":"AAAA,4FAA4F;AAC5F,4FAA4F;AAC5F,gGAAgG;AAChG,8FAA8F;AAE9F,OAAO,EAAE,YAAY,EAAE,MAAM,oBAAoB,CAAC;AAClD,OAAO,EAAE,UAAU,EAAE,SAAS,EAAE,MAAM,EAAE,aAAa,EAAE,MAAM,SAAS,CAAC;AACvE,OAAO,EAAE,OAAO,EAAE,MAAM,SAAS,CAAC;AAClC,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AAE1C,MAAM,CAAC,MAAM,KAAK,GAAG,qBAAqB,CAAC;AAC3C,MAAM,OAAO,GAAG,yDAAyD,CAAC;AAC1E,MAAM,SAAS,GAAG,gBAAgB,CAAC;AAEnC,MAAM,QAAQ,GAAG,CAAC,CAAS,EAAE,EAAE,CAAC,IAAI,CAAC,CAAC,OAAO,CAAC,IAAI,EAAE,EAAE,CAAC,GAAG,CAAC;AAC3D,MAAM,GAAG,GAAG,CA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,gBAAgB,CAAC,CAAC;QACpH,MAAM,CAAC,KAAK,CAAC,QAAQ,EAAE,EAAE,KAAK,EAAE,IAAI,EAAE,CAAC,CAAC;QACxC,OAAO,WAAW,KAAK,CAAC,QAAQ,EAAE,CAAC;IACrC,CAAC;IACD,IAAI,CAAC,UAAU,CAAC,KAAK,CAAC,SAAS,CAAC;QAAE,OAAO,sBAAsB,CAAC;IAChE,IAAI,CAAC;QAAC,YAAY,CAAC,WAAW,EAAE,CAAC,QAAQ,EAAE,SAAS,EAAE,OAAO,EAAE,yBAAyB,CAAC,EAAE,EAAE,KAAK,EAAE,QAAQ,EAAE,CAAC,CAAC;IAAC,CAAC;IAAC,MAAM,CAAC,CAAC,iBAAiB,CAAC,CAAC;IAC9I,MAAM,CAAC,KAAK,CAAC,SAAS,EAAE,EAAE,KAAK,EAAE,IAAI,EAAE,CAAC,CAAC;IACzC,OAAO,WAAW,KAAK,CAAC,SAAS,EAAE,CAAC;AACtC,CAAC","sourcesContent":["// Start the agent when the person signs in to the computer, per user, with no administrator\n// rights: a Run entry on Windows, a LaunchAgent on macOS, a systemd user unit on Linux. The\n// builders are pure (and tested); `enable`/`disable` apply them. The command pins this Node and\n// this agent's absolute path, so it never depends on a shell's PATH or npm's temporary cache.\n\nimport { execFileSync } from \"node:child_process\";\nimport { existsSync, mkdirSync, rmSync, writeFileSync } from \"node:fs\";\nimport { homedir } from \"node:os\";\nimport { dirname, join } from \"node:path\";\n\nexport const LABEL = \"com.scopebond.agent\";\nconst RUN_KEY = \"HKCU\\\\Software\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\Run\";\nconst RUN_VALUE = \"ScopebondAgent\";\n\nconst quoteWin = (s: string) => `\"${s.replace(/\"/g, \"\")}\"`;\nconst xml = (s: string) => s.replace(/&/g, \"&\").replace(/</g, \"<\").replace(/>/g, \">\");\n\nexport function windowsRunCommand(node: string, cli: string): string {\n return `${quoteWin(node)} ${quoteWin(cli)} run`;\n}\n\nexport function macLaunchAgent(node: string, cli: string, logFile: string): string {\n return `<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">\n<plist version=\"1.0\">\n<dict>\n <key>Label</key><string>${LABEL}</string>\n <key>ProgramArguments</key>\n <array><string>${xml(node)}</string><string>${xml(cli)}</string><string>run</string></array>\n <key>RunAtLoad</key><true/>\n <key>KeepAlive</key><dict><key>SuccessfulExit</key><false/></dict>\n <key>StandardOutPath</key><string>${xml(logFile)}</string>\n <key>StandardErrorPath</key><string>${xml(logFile)}</string>\n</dict>\n</plist>\n`;\n}\n\nexport function linuxUserUnit(node: string, cli: string): string {\n const q = (s: string) => `\"${s.replace(/([\"\\\\])/g, \"\\\\$1\")}\"`;\n return `[Unit]\nDescription=Scopebond Agent (delivers this computer's records to its Scopebond workspace)\nAfter=network-online.target\n\n[Service]\nExecStart=${q(node)} ${q(cli)} run\nRestart=on-failure\nRestartSec=30\n\n[Install]\nWantedBy=default.target\n`;\n}\n\nexport function autostartPaths(home = homedir()) {\n return {\n macPlist: join(home, \"Library\", \"LaunchAgents\", `${LABEL}.plist`),\n linuxUnit: join(home, \".config\", \"systemd\", \"user\", \"scopebond-agent.service\"),\n log: join(home, \".scopebond\", \"agent.log\"),\n };\n}\n\n/** Turn autostart on for this user. Returns a one-line description of what changed. */\nexport function enableAutostart(cli: string, node = process.execPath, platform = process.platform): string {\n const paths = autostartPaths();\n if (platform === \"win32\") {\n execFileSync(\"reg\", [\"add\", RUN_KEY, \"/v\", RUN_VALUE, \"/t\", \"REG_SZ\", \"/d\", windowsRunCommand(node, cli), \"/f\"], { stdio: \"ignore\" });\n return `added ${RUN_VALUE} to ${RUN_KEY}`;\n }\n if (platform === \"darwin\") {\n mkdirSync(dirname(paths.macPlist), { recursive: true });\n mkdirSync(dirname(paths.log), { recursive: true });\n writeFileSync(paths.macPlist, macLaunchAgent(node, cli, paths.log));\n try { execFileSync(\"launchctl\", [\"load\", \"-w\", paths.macPlist], { stdio: \"ignore\" }); } catch { /* loads at next sign-in */ }\n return `wrote ${paths.macPlist}`;\n }\n mkdirSync(dirname(paths.linuxUnit), { recursive: true });\n writeFileSync(paths.linuxUnit, linuxUserUnit(node, cli));\n try { execFileSync(\"systemctl\", [\"--user\", \"daemon-reload\"], { stdio: \"ignore\" }); execFileSync(\"systemctl\", [\"--user\", \"enable\", \"--now\", \"scopebond-agent.service\"], { stdio: \"ignore\" }); }\n catch { return `wrote ${paths.linuxUnit} (enable it with: systemctl --user enable --now scopebond-agent)`; }\n return `wrote and enabled ${paths.linuxUnit}`;\n}\n\nexport function disableAutostart(platform = process.platform): string {\n const paths = autostartPaths();\n if (platform === \"win32\") {\n try { execFileSync(\"reg\", [\"delete\", RUN_KEY, \"/v\", RUN_VALUE, \"/f\"], { stdio: \"ignore\" }); } catch { return \"autostart was not on\"; }\n return `removed ${RUN_VALUE} from ${RUN_KEY}`;\n }\n if (platform === \"darwin\") {\n if (!existsSync(paths.macPlist)) return \"autostart was not on\";\n try { execFileSync(\"launchctl\", [\"unload\", \"-w\", paths.macPlist], { stdio: \"ignore\" }); } catch { /* not loaded */ }\n rmSync(paths.macPlist, { force: true });\n return `removed ${paths.macPlist}`;\n }\n if (!existsSync(paths.linuxUnit)) return \"autostart was not on\";\n try { execFileSync(\"systemctl\", [\"--user\", \"disable\", \"--now\", \"scopebond-agent.service\"], { stdio: \"ignore\" }); } catch { /* not enabled */ }\n rmSync(paths.linuxUnit, { force: true });\n return `removed ${paths.linuxUnit}`;\n}\n"]}
|
package/dist/cli.d.ts
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"cli.d.ts","sourceRoot":"","sources":["../src/cli.ts"],"names":[],"mappings":""}
|
package/dist/cli.js
ADDED
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// scopebond-agent: run, look at and control the Scopebond Agent for this user.
|
|
3
|
+
//
|
|
4
|
+
// scopebond-agent run run in the foreground (what autostart starts)
|
|
5
|
+
// scopebond-agent status [--json] what the running agent reports, or why it is not running
|
|
6
|
+
// scopebond-agent flush deliver now
|
|
7
|
+
// scopebond-agent repair put the Scopebond hook back where agent settings lost it
|
|
8
|
+
// scopebond-agent autostart on|off start with this user's sign-in, or stop doing so
|
|
9
|
+
import { realpathSync } from "node:fs";
|
|
10
|
+
import { fileURLToPath } from "node:url";
|
|
11
|
+
import { isEphemeralPath, userHome } from "@scopebond/hook";
|
|
12
|
+
import { computerStatus } from "./agent.js";
|
|
13
|
+
import { disableAutostart, enableAutostart } from "./autostart.js";
|
|
14
|
+
import { callAgent } from "./ipc.js";
|
|
15
|
+
import { startService } from "./service.js";
|
|
16
|
+
const [cmd = "help", ...rest] = process.argv.slice(2);
|
|
17
|
+
const dir = process.env.SCOPEBOND_HOME ?? userHome();
|
|
18
|
+
const cliPath = realpathSync(fileURLToPath(import.meta.url));
|
|
19
|
+
function help() {
|
|
20
|
+
console.log(`Scopebond Agent — keeps this computer delivering to its Scopebond workspace.
|
|
21
|
+
|
|
22
|
+
scopebond-agent run run in the foreground (what autostart starts)
|
|
23
|
+
scopebond-agent status [--json] what the agent reports about this computer
|
|
24
|
+
scopebond-agent flush deliver waiting records now
|
|
25
|
+
scopebond-agent repair put the Scopebond hook back where agent settings lost it
|
|
26
|
+
scopebond-agent autostart on|off start with your sign-in, or stop doing so
|
|
27
|
+
|
|
28
|
+
The hook keeps deciding every action on its own; the agent only keeps delivery, rules and the
|
|
29
|
+
connection current. Home: ${dir}`);
|
|
30
|
+
}
|
|
31
|
+
async function main() {
|
|
32
|
+
switch (cmd) {
|
|
33
|
+
case "run": {
|
|
34
|
+
const service = await startService({ dir });
|
|
35
|
+
const stop = () => { void service.stop().finally(() => process.exit(0)); };
|
|
36
|
+
process.on("SIGINT", stop);
|
|
37
|
+
process.on("SIGTERM", stop);
|
|
38
|
+
return;
|
|
39
|
+
}
|
|
40
|
+
case "status": {
|
|
41
|
+
const live = await callAgent(dir, "GET", "/status");
|
|
42
|
+
const status = live ?? { ...computerStatus(dir), agent: null };
|
|
43
|
+
if (rest.includes("--json")) {
|
|
44
|
+
console.log(JSON.stringify(status, null, 2));
|
|
45
|
+
return;
|
|
46
|
+
}
|
|
47
|
+
const d = status.delivery;
|
|
48
|
+
console.log(`Scopebond Agent: ${live ? "running" : "not running"}`);
|
|
49
|
+
console.log(` state ${status.state}`);
|
|
50
|
+
console.log(` connected ${d.connected ? "yes" : "no"}`);
|
|
51
|
+
console.log(` waiting to send ${d.pending} record(s)${d.oldest_pending_age_s !== null ? `, oldest ${Math.round(d.oldest_pending_age_s / 60)} min` : ""}`);
|
|
52
|
+
if (d.last_error)
|
|
53
|
+
console.log(` last problem ${d.last_error}`);
|
|
54
|
+
if (!live)
|
|
55
|
+
console.log(`\nStart it with: scopebond-agent run (or: scopebond-agent autostart on)`);
|
|
56
|
+
return;
|
|
57
|
+
}
|
|
58
|
+
case "flush":
|
|
59
|
+
case "repair": {
|
|
60
|
+
const answer = await callAgent(dir, "POST", `/${cmd}`, {}, 60_000);
|
|
61
|
+
if (!answer) {
|
|
62
|
+
console.error("The Scopebond Agent is not running. Start it with: scopebond-agent run");
|
|
63
|
+
process.exitCode = 1;
|
|
64
|
+
return;
|
|
65
|
+
}
|
|
66
|
+
console.log(JSON.stringify(answer, null, 2));
|
|
67
|
+
return;
|
|
68
|
+
}
|
|
69
|
+
case "autostart": {
|
|
70
|
+
const on = rest[0] === "on";
|
|
71
|
+
if (rest[0] !== "on" && rest[0] !== "off") {
|
|
72
|
+
console.error("usage: scopebond-agent autostart on|off");
|
|
73
|
+
process.exitCode = 1;
|
|
74
|
+
return;
|
|
75
|
+
}
|
|
76
|
+
if (on && isEphemeralPath(cliPath)) {
|
|
77
|
+
// npx runs from a cache npm clears; an autostart entry pointing there would stop working.
|
|
78
|
+
console.error("Install the agent first so autostart has a stable path: npm install -g @scopebond/agent");
|
|
79
|
+
process.exitCode = 1;
|
|
80
|
+
return;
|
|
81
|
+
}
|
|
82
|
+
console.log(on ? enableAutostart(cliPath) : disableAutostart());
|
|
83
|
+
return;
|
|
84
|
+
}
|
|
85
|
+
default:
|
|
86
|
+
help();
|
|
87
|
+
if (cmd !== "help" && cmd !== "--help")
|
|
88
|
+
process.exitCode = 1;
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
void main().catch((error) => { console.error(error.message); process.exitCode = 1; });
|
|
92
|
+
//# sourceMappingURL=cli.js.map
|
package/dist/cli.js.map
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"cli.js","sourceRoot":"","sources":["../src/cli.ts"],"names":[],"mappings":";AACA,+EAA+E;AAC/E,EAAE;AACF,sFAAsF;AACtF,iGAAiG;AACjG,oDAAoD;AACpD,iGAAiG;AACjG,yFAAyF;AAEzF,OAAO,EAAE,YAAY,EAAE,MAAM,SAAS,CAAC;AACvC,OAAO,EAAE,aAAa,EAAE,MAAM,UAAU,CAAC;AACzC,OAAO,EAAE,eAAe,EAAE,QAAQ,EAAE,MAAM,iBAAiB,CAAC;AAC5D,OAAO,EAAE,cAAc,EAAE,MAAM,YAAY,CAAC;AAC5C,OAAO,EAAE,gBAAgB,EAAE,eAAe,EAAE,MAAM,gBAAgB,CAAC;AACnE,OAAO,EAAE,SAAS,EAAE,MAAM,UAAU,CAAC;AACrC,OAAO,EAAE,YAAY,EAAE,MAAM,cAAc,CAAC;AAE5C,MAAM,CAAC,GAAG,GAAG,MAAM,EAAE,GAAG,IAAI,CAAC,GAAG,OAAO,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC;AACtD,MAAM,GAAG,GAAG,OAAO,CAAC,GAAG,CAAC,cAAc,IAAI,QAAQ,EAAE,CAAC;AACrD,MAAM,OAAO,GAAG,YAAY,CAAC,aAAa,CAAC,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,CAAC;AAE7D,SAAS,IAAI;IACX,OAAO,CAAC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CAAyC,CAAC,CAAC;gBAAC,OAAO,CAAC,QAAQ,GAAG,CAAC,CAAC;gBAAC,OAAO;YAAC,CAAC;YACtI,IAAI,EAAE,IAAI,eAAe,CAAC,OAAO,CAAC,EAAE,CAAC;gBACnC,0FAA0F;gBAC1F,OAAO,CAAC,KAAK,CAAC,yFAAyF,CAAC,CAAC;gBACzG,OAAO,CAAC,QAAQ,GAAG,CAAC,CAAC;gBACrB,OAAO;YACT,CAAC;YACD,OAAO,CAAC,GAAG,CAAC,EAAE,CAAC,CAAC,CAAC,eAAe,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,gBAAgB,EAAE,CAAC,CAAC;YAChE,OAAO;QACT,CAAC;QACD;YACE,IAAI,EAAE,CAAC;YACP,IAAI,GAAG,KAAK,MAAM,IAAI,GAAG,KAAK,QAAQ;gBAAE,OAAO,CAAC,QAAQ,GAAG,CAAC,CAAC;IACjE,CAAC;AACH,CAAC;AAED,KAAK,IAAI,EAAE,CAAC,KAAK,CAAC,CAAC,KAAK,EAAE,EAAE,GAAG,OAAO,CAAC,KAAK,CAAE,KAAe,CAAC,OAAO,CAAC,CAAC,CAAC,OAAO,CAAC,QAAQ,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC","sourcesContent":["#!/usr/bin/env node\n// scopebond-agent: run, look at and control the Scopebond Agent for this user.\n//\n// scopebond-agent run run in the foreground (what autostart starts)\n// scopebond-agent status [--json] what the running agent reports, or why it is not running\n// scopebond-agent flush deliver now\n// scopebond-agent repair put the Scopebond hook back where agent settings lost it\n// scopebond-agent autostart on|off start with this user's sign-in, or stop doing so\n\nimport { realpathSync } from \"node:fs\";\nimport { fileURLToPath } from \"node:url\";\nimport { isEphemeralPath, userHome } from \"@scopebond/hook\";\nimport { computerStatus } from \"./agent.js\";\nimport { disableAutostart, enableAutostart } from \"./autostart.js\";\nimport { callAgent } from \"./ipc.js\";\nimport { startService } from \"./service.js\";\n\nconst [cmd = \"help\", ...rest] = process.argv.slice(2);\nconst dir = process.env.SCOPEBOND_HOME ?? userHome();\nconst cliPath = realpathSync(fileURLToPath(import.meta.url));\n\nfunction help(): void {\n console.log(`Scopebond Agent — keeps this computer delivering to its Scopebond workspace.\n\n scopebond-agent run run in the foreground (what autostart starts)\n scopebond-agent status [--json] what the agent reports about this computer\n scopebond-agent flush deliver waiting records now\n scopebond-agent repair put the Scopebond hook back where agent settings lost it\n scopebond-agent autostart on|off start with your sign-in, or stop doing so\n\nThe hook keeps deciding every action on its own; the agent only keeps delivery, rules and the\nconnection current. Home: ${dir}`);\n}\n\nasync function main(): Promise<void> {\n switch (cmd) {\n case \"run\": {\n const service = await startService({ dir });\n const stop = () => { void service.stop().finally(() => process.exit(0)); };\n process.on(\"SIGINT\", stop);\n process.on(\"SIGTERM\", stop);\n return;\n }\n case \"status\": {\n const live = await callAgent(dir, \"GET\", \"/status\") as (ReturnType<typeof computerStatus> & { agent?: unknown }) | null;\n const status = live ?? { ...computerStatus(dir), agent: null };\n if (rest.includes(\"--json\")) { console.log(JSON.stringify(status, null, 2)); return; }\n const d = status.delivery;\n console.log(`Scopebond Agent: ${live ? \"running\" : \"not running\"}`);\n console.log(` state ${status.state}`);\n console.log(` connected ${d.connected ? \"yes\" : \"no\"}`);\n console.log(` waiting to send ${d.pending} record(s)${d.oldest_pending_age_s !== null ? `, oldest ${Math.round(d.oldest_pending_age_s / 60)} min` : \"\"}`);\n if (d.last_error) console.log(` last problem ${d.last_error}`);\n if (!live) console.log(`\\nStart it with: scopebond-agent run (or: scopebond-agent autostart on)`);\n return;\n }\n case \"flush\":\n case \"repair\": {\n const answer = await callAgent(dir, \"POST\", `/${cmd}`, {}, 60_000);\n if (!answer) { console.error(\"The Scopebond Agent is not running. Start it with: scopebond-agent run\"); process.exitCode = 1; return; }\n console.log(JSON.stringify(answer, null, 2));\n return;\n }\n case \"autostart\": {\n const on = rest[0] === \"on\";\n if (rest[0] !== \"on\" && rest[0] !== \"off\") { console.error(\"usage: scopebond-agent autostart on|off\"); process.exitCode = 1; return; }\n if (on && isEphemeralPath(cliPath)) {\n // npx runs from a cache npm clears; an autostart entry pointing there would stop working.\n console.error(\"Install the agent first so autostart has a stable path: npm install -g @scopebond/agent\");\n process.exitCode = 1;\n return;\n }\n console.log(on ? enableAutostart(cliPath) : disableAutostart());\n return;\n }\n default:\n help();\n if (cmd !== \"help\" && cmd !== \"--help\") process.exitCode = 1;\n }\n}\n\nvoid main().catch((error) => { console.error((error as Error).message); process.exitCode = 1; });\n"]}
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
export { runCycle, computerStatus, expectedHarnesses, missingHookEntries } from "./agent.js";
|
|
2
|
+
export type { CycleOptions, CycleResult } from "./agent.js";
|
|
3
|
+
export { startService, repairHookEntries, AGENT_VERSION } from "./service.js";
|
|
4
|
+
export type { Service, ServiceOptions } from "./service.js";
|
|
5
|
+
export { startControl, callAgent, readEndpoint, AGENT_FILE, TOKEN_HEADER } from "./ipc.js";
|
|
6
|
+
export type { AgentEndpoint } from "./ipc.js";
|
|
7
|
+
export { windowsRunCommand, macLaunchAgent, linuxUserUnit, enableAutostart, disableAutostart, autostartPaths, LABEL } from "./autostart.js";
|
|
8
|
+
//# sourceMappingURL=index.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,cAAc,EAAE,iBAAiB,EAAE,kBAAkB,EAAE,MAAM,YAAY,CAAC;AAC7F,YAAY,EAAE,YAAY,EAAE,WAAW,EAAE,MAAM,YAAY,CAAC;AAC5D,OAAO,EAAE,YAAY,EAAE,iBAAiB,EAAE,aAAa,EAAE,MAAM,cAAc,CAAC;AAC9E,YAAY,EAAE,OAAO,EAAE,cAAc,EAAE,MAAM,cAAc,CAAC;AAC5D,OAAO,EAAE,YAAY,EAAE,SAAS,EAAE,YAAY,EAAE,UAAU,EAAE,YAAY,EAAE,MAAM,UAAU,CAAC;AAC3F,YAAY,EAAE,aAAa,EAAE,MAAM,UAAU,CAAC;AAC9C,OAAO,EAAE,iBAAiB,EAAE,cAAc,EAAE,aAAa,EAAE,eAAe,EAAE,gBAAgB,EAAE,cAAc,EAAE,KAAK,EAAE,MAAM,gBAAgB,CAAC"}
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
export { runCycle, computerStatus, expectedHarnesses, missingHookEntries } from "./agent.js";
|
|
2
|
+
export { startService, repairHookEntries, AGENT_VERSION } from "./service.js";
|
|
3
|
+
export { startControl, callAgent, readEndpoint, AGENT_FILE, TOKEN_HEADER } from "./ipc.js";
|
|
4
|
+
export { windowsRunCommand, macLaunchAgent, linuxUserUnit, enableAutostart, disableAutostart, autostartPaths, LABEL } from "./autostart.js";
|
|
5
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,cAAc,EAAE,iBAAiB,EAAE,kBAAkB,EAAE,MAAM,YAAY,CAAC;AAE7F,OAAO,EAAE,YAAY,EAAE,iBAAiB,EAAE,aAAa,EAAE,MAAM,cAAc,CAAC;AAE9E,OAAO,EAAE,YAAY,EAAE,SAAS,EAAE,YAAY,EAAE,UAAU,EAAE,YAAY,EAAE,MAAM,UAAU,CAAC;AAE3F,OAAO,EAAE,iBAAiB,EAAE,cAAc,EAAE,aAAa,EAAE,eAAe,EAAE,gBAAgB,EAAE,cAAc,EAAE,KAAK,EAAE,MAAM,gBAAgB,CAAC","sourcesContent":["export { runCycle, computerStatus, expectedHarnesses, missingHookEntries } from \"./agent.js\";\nexport type { CycleOptions, CycleResult } from \"./agent.js\";\nexport { startService, repairHookEntries, AGENT_VERSION } from \"./service.js\";\nexport type { Service, ServiceOptions } from \"./service.js\";\nexport { startControl, callAgent, readEndpoint, AGENT_FILE, TOKEN_HEADER } from \"./ipc.js\";\nexport type { AgentEndpoint } from \"./ipc.js\";\nexport { windowsRunCommand, macLaunchAgent, linuxUserUnit, enableAutostart, disableAutostart, autostartPaths, LABEL } from \"./autostart.js\";\n"]}
|
package/dist/ipc.d.ts
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import { type Server } from "node:http";
|
|
2
|
+
export declare const AGENT_FILE = "agent.json";
|
|
3
|
+
export declare const TOKEN_HEADER = "x-scopebond-agent-token";
|
|
4
|
+
export interface AgentEndpoint {
|
|
5
|
+
port: number;
|
|
6
|
+
token: string;
|
|
7
|
+
pid: number;
|
|
8
|
+
started_at: number;
|
|
9
|
+
version: string;
|
|
10
|
+
}
|
|
11
|
+
export type Handler = (body: unknown) => Promise<unknown> | unknown;
|
|
12
|
+
export declare function readEndpoint(dir: string): AgentEndpoint | null;
|
|
13
|
+
/** Start the control server. `routes` maps "METHOD /path" to a handler. */
|
|
14
|
+
export declare function startControl(dir: string, version: string, routes: Record<string, Handler>): Promise<{
|
|
15
|
+
server: Server;
|
|
16
|
+
endpoint: AgentEndpoint;
|
|
17
|
+
close(): Promise<void>;
|
|
18
|
+
}>;
|
|
19
|
+
/** Call a running agent. Returns null when no agent answers. */
|
|
20
|
+
export declare function callAgent(dir: string, method: "GET" | "POST", path: string, body?: unknown, timeoutMs?: number): Promise<unknown | null>;
|
|
21
|
+
//# sourceMappingURL=ipc.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"ipc.d.ts","sourceRoot":"","sources":["../src/ipc.ts"],"names":[],"mappings":"AAKA,OAAO,EAAsC,KAAK,MAAM,EAAuB,MAAM,WAAW,CAAC;AAKjG,eAAO,MAAM,UAAU,eAAe,CAAC;AACvC,eAAO,MAAM,YAAY,4BAA4B,CAAC;AAEtD,MAAM,WAAW,aAAa;IAAG,IAAI,EAAE,MAAM,CAAC;IAAC,KAAK,EAAE,MAAM,CAAC;IAAC,GAAG,EAAE,MAAM,CAAC;IAAC,UAAU,EAAE,MAAM,CAAC;IAAC,OAAO,EAAE,MAAM,CAAA;CAAE;AAEhH,MAAM,MAAM,OAAO,GAAG,CAAC,IAAI,EAAE,OAAO,KAAK,OAAO,CAAC,OAAO,CAAC,GAAG,OAAO,CAAC;AAEpE,wBAAgB,YAAY,CAAC,GAAG,EAAE,MAAM,GAAG,aAAa,GAAG,IAAI,CAI9D;AAED,2EAA2E;AAC3E,wBAAsB,YAAY,CAAC,GAAG,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,OAAO,CAAC;IAAE,MAAM,EAAE,MAAM,CAAC;IAAC,QAAQ,EAAE,aAAa,CAAC;IAAC,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC,CAAA;CAAE,CAAC,CA8B9K;AAED,gEAAgE;AAChE,wBAAsB,SAAS,CAAC,GAAG,EAAE,MAAM,EAAE,MAAM,EAAE,KAAK,GAAG,MAAM,EAAE,IAAI,EAAE,MAAM,EAAE,IAAI,CAAC,EAAE,OAAO,EAAE,SAAS,SAAQ,GAAG,OAAO,CAAC,OAAO,GAAG,IAAI,CAAC,CAU7I"}
|
package/dist/ipc.js
ADDED
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
// The agent's local control channel: an HTTP server bound to 127.0.0.1 on a random port, with a
|
|
2
|
+
// random token. Port, token and process id are written to agent.json in the Scopebond home (owner
|
|
3
|
+
// read/write only), which is how the CLI and, later, the tray find it. Nothing listens beyond this
|
|
4
|
+
// computer, and every request must carry the token.
|
|
5
|
+
import { createServer } from "node:http";
|
|
6
|
+
import { randomBytes, timingSafeEqual } from "node:crypto";
|
|
7
|
+
import { existsSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs";
|
|
8
|
+
import { join } from "node:path";
|
|
9
|
+
export const AGENT_FILE = "agent.json";
|
|
10
|
+
export const TOKEN_HEADER = "x-scopebond-agent-token";
|
|
11
|
+
export function readEndpoint(dir) {
|
|
12
|
+
const file = join(dir, AGENT_FILE);
|
|
13
|
+
if (!existsSync(file))
|
|
14
|
+
return null;
|
|
15
|
+
try {
|
|
16
|
+
return JSON.parse(readFileSync(file, "utf8"));
|
|
17
|
+
}
|
|
18
|
+
catch {
|
|
19
|
+
return null;
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
/** Start the control server. `routes` maps "METHOD /path" to a handler. */
|
|
23
|
+
export async function startControl(dir, version, routes) {
|
|
24
|
+
const token = randomBytes(24).toString("base64url");
|
|
25
|
+
const expected = Buffer.from(token);
|
|
26
|
+
const server = createServer(async (req, res) => {
|
|
27
|
+
const send = (status, body) => { res.writeHead(status, { "content-type": "application/json", "cache-control": "no-store" }); res.end(JSON.stringify(body)); };
|
|
28
|
+
const offered = Buffer.from(String(req.headers[TOKEN_HEADER] ?? ""));
|
|
29
|
+
if (offered.length !== expected.length || !timingSafeEqual(offered, expected))
|
|
30
|
+
return send(401, { error: "unauthorized" });
|
|
31
|
+
const handler = routes[`${req.method} ${(req.url ?? "/").split("?")[0]}`];
|
|
32
|
+
if (!handler)
|
|
33
|
+
return send(404, { error: "not found" });
|
|
34
|
+
let raw = "";
|
|
35
|
+
for await (const chunk of req) {
|
|
36
|
+
raw += chunk;
|
|
37
|
+
if (raw.length > 64 * 1024)
|
|
38
|
+
return send(413, { error: "too large" });
|
|
39
|
+
}
|
|
40
|
+
try {
|
|
41
|
+
send(200, await handler(raw ? JSON.parse(raw) : null));
|
|
42
|
+
}
|
|
43
|
+
catch (error) {
|
|
44
|
+
send(500, { error: error.message.slice(0, 200) });
|
|
45
|
+
}
|
|
46
|
+
});
|
|
47
|
+
await new Promise((resolve, reject) => { server.once("error", reject); server.listen(0, "127.0.0.1", () => resolve()); });
|
|
48
|
+
const address = server.address();
|
|
49
|
+
const port = typeof address === "object" && address ? address.port : 0;
|
|
50
|
+
const endpoint = { port, token, pid: process.pid, started_at: Date.now(), version };
|
|
51
|
+
const file = join(dir, AGENT_FILE);
|
|
52
|
+
const temp = `${file}.${process.pid}.tmp`;
|
|
53
|
+
writeFileSync(temp, JSON.stringify(endpoint, null, 2) + "\n", { mode: 0o600 });
|
|
54
|
+
renameSync(temp, file);
|
|
55
|
+
return {
|
|
56
|
+
server, endpoint,
|
|
57
|
+
close: () => new Promise((resolve) => {
|
|
58
|
+
server.close(() => resolve());
|
|
59
|
+
// Only remove the file if it is still ours (a newer agent may have replaced it).
|
|
60
|
+
try {
|
|
61
|
+
if (readEndpoint(dir)?.pid === process.pid)
|
|
62
|
+
rmSync(file, { force: true });
|
|
63
|
+
}
|
|
64
|
+
catch { /* best effort */ }
|
|
65
|
+
}),
|
|
66
|
+
};
|
|
67
|
+
}
|
|
68
|
+
/** Call a running agent. Returns null when no agent answers. */
|
|
69
|
+
export async function callAgent(dir, method, path, body, timeoutMs = 5_000) {
|
|
70
|
+
const endpoint = readEndpoint(dir);
|
|
71
|
+
if (!endpoint)
|
|
72
|
+
return null;
|
|
73
|
+
try {
|
|
74
|
+
const res = await fetch(`http://127.0.0.1:${endpoint.port}${path}`, {
|
|
75
|
+
method, headers: { [TOKEN_HEADER]: endpoint.token, ...(body !== undefined ? { "content-type": "application/json" } : {}) },
|
|
76
|
+
body: body !== undefined ? JSON.stringify(body) : undefined, signal: AbortSignal.timeout(timeoutMs),
|
|
77
|
+
});
|
|
78
|
+
return res.ok ? await res.json() : null;
|
|
79
|
+
}
|
|
80
|
+
catch {
|
|
81
|
+
return null;
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
//# sourceMappingURL=ipc.js.map
|
package/dist/ipc.js.map
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"ipc.js","sourceRoot":"","sources":["../src/ipc.ts"],"names":[],"mappings":"AAAA,gGAAgG;AAChG,kGAAkG;AAClG,mGAAmG;AACnG,oDAAoD;AAEpD,OAAO,EAAE,YAAY,EAA0D,MAAM,WAAW,CAAC;AACjG,OAAO,EAAE,WAA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AI,EAAE,EAAE,KAAK,EAAE,IAAI,EAAE,CAAC,CAAC;YAAC,CAAC;YAAC,MAAM,CAAC,CAAC,iBAAiB,CAAC,CAAC;QAChH,CAAC,CAAC;KACH,CAAC;AACJ,CAAC;AAED,gEAAgE;AAChE,MAAM,CAAC,KAAK,UAAU,SAAS,CAAC,GAAW,EAAE,MAAsB,EAAE,IAAY,EAAE,IAAc,EAAE,SAAS,GAAG,KAAK;IAClH,MAAM,QAAQ,GAAG,YAAY,CAAC,GAAG,CAAC,CAAC;IACnC,IAAI,CAAC,QAAQ;QAAE,OAAO,IAAI,CAAC;IAC3B,IAAI,CAAC;QACH,MAAM,GAAG,GAAG,MAAM,KAAK,CAAC,oBAAoB,QAAQ,CAAC,IAAI,GAAG,IAAI,EAAE,EAAE;YAClE,MAAM,EAAE,OAAO,EAAE,EAAE,CAAC,YAAY,CAAC,EAAE,QAAQ,CAAC,KAAK,EAAE,GAAG,CAAC,IAAI,KAAK,SAAS,CAAC,CAAC,CAAC,EAAE,cAAc,EAAE,kBAAkB,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE;YAC1H,IAAI,EAAE,IAAI,KAAK,SAAS,CAAC,CAAC,CAAC,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,SAAS,EAAE,MAAM,EAAE,WAAW,CAAC,OAAO,CAAC,SAAS,CAAC;SACpG,CAAC,CAAC;QACH,OAAO,GAAG,CAAC,EAAE,CAAC,CAAC,CAAC,MAAM,GAAG,CAAC,IAAI,EAAE,CAAC,CAAC,CAAC,IAAI,CAAC;IAC1C,CAAC;IAAC,MAAM,CAAC;QAAC,OAAO,IAAI,CAAC;IAAC,CAAC;AAC1B,CAAC","sourcesContent":["// The agent's local control channel: an HTTP server bound to 127.0.0.1 on a random port, with a\n// random token. Port, token and process id are written to agent.json in the Scopebond home (owner\n// read/write only), which is how the CLI and, later, the tray find it. Nothing listens beyond this\n// computer, and every request must carry the token.\n\nimport { createServer, type IncomingMessage, type Server, type ServerResponse } from \"node:http\";\nimport { randomBytes, timingSafeEqual } from \"node:crypto\";\nimport { existsSync, readFileSync, renameSync, rmSync, writeFileSync } from \"node:fs\";\nimport { join } from \"node:path\";\n\nexport const AGENT_FILE = \"agent.json\";\nexport const TOKEN_HEADER = \"x-scopebond-agent-token\";\n\nexport interface AgentEndpoint { port: number; token: string; pid: number; started_at: number; version: string }\n\nexport type Handler = (body: unknown) => Promise<unknown> | unknown;\n\nexport function readEndpoint(dir: string): AgentEndpoint | null {\n const file = join(dir, AGENT_FILE);\n if (!existsSync(file)) return null;\n try { return JSON.parse(readFileSync(file, \"utf8\")) as AgentEndpoint; } catch { return null; }\n}\n\n/** Start the control server. `routes` maps \"METHOD /path\" to a handler. */\nexport async function startControl(dir: string, version: string, routes: Record<string, Handler>): Promise<{ server: Server; endpoint: AgentEndpoint; close(): Promise<void> }> {\n const token = randomBytes(24).toString(\"base64url\");\n const expected = Buffer.from(token);\n const server = createServer(async (req: IncomingMessage, res: ServerResponse) => {\n const send = (status: number, body: unknown) => { res.writeHead(status, { \"content-type\": \"application/json\", \"cache-control\": \"no-store\" }); res.end(JSON.stringify(body)); };\n const offered = Buffer.from(String(req.headers[TOKEN_HEADER] ?? \"\"));\n if (offered.length !== expected.length || !timingSafeEqual(offered, expected)) return send(401, { error: \"unauthorized\" });\n const handler = routes[`${req.method} ${(req.url ?? \"/\").split(\"?\")[0]}`];\n if (!handler) return send(404, { error: \"not found\" });\n let raw = \"\";\n for await (const chunk of req) { raw += chunk; if (raw.length > 64 * 1024) return send(413, { error: \"too large\" }); }\n try { send(200, await handler(raw ? JSON.parse(raw) : null)); }\n catch (error) { send(500, { error: (error as Error).message.slice(0, 200) }); }\n });\n await new Promise<void>((resolve, reject) => { server.once(\"error\", reject); server.listen(0, \"127.0.0.1\", () => resolve()); });\n const address = server.address();\n const port = typeof address === \"object\" && address ? address.port : 0;\n const endpoint: AgentEndpoint = { port, token, pid: process.pid, started_at: Date.now(), version };\n const file = join(dir, AGENT_FILE);\n const temp = `${file}.${process.pid}.tmp`;\n writeFileSync(temp, JSON.stringify(endpoint, null, 2) + \"\\n\", { mode: 0o600 });\n renameSync(temp, file);\n return {\n server, endpoint,\n close: () => new Promise<void>((resolve) => {\n server.close(() => resolve());\n // Only remove the file if it is still ours (a newer agent may have replaced it).\n try { if (readEndpoint(dir)?.pid === process.pid) rmSync(file, { force: true }); } catch { /* best effort */ }\n }),\n };\n}\n\n/** Call a running agent. Returns null when no agent answers. */\nexport async function callAgent(dir: string, method: \"GET\" | \"POST\", path: string, body?: unknown, timeoutMs = 5_000): Promise<unknown | null> {\n const endpoint = readEndpoint(dir);\n if (!endpoint) return null;\n try {\n const res = await fetch(`http://127.0.0.1:${endpoint.port}${path}`, {\n method, headers: { [TOKEN_HEADER]: endpoint.token, ...(body !== undefined ? { \"content-type\": \"application/json\" } : {}) },\n body: body !== undefined ? JSON.stringify(body) : undefined, signal: AbortSignal.timeout(timeoutMs),\n });\n return res.ok ? await res.json() : null;\n } catch { return null; }\n}\n"]}
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import { type Harness } from "@scopebond/hook";
|
|
2
|
+
import { type CycleResult } from "./agent.js";
|
|
3
|
+
export declare const AGENT_VERSION = "agent/1";
|
|
4
|
+
export interface ServiceOptions {
|
|
5
|
+
dir: string;
|
|
6
|
+
intervalMs?: number;
|
|
7
|
+
fetchImpl?: typeof fetch;
|
|
8
|
+
log?: (line: string) => void;
|
|
9
|
+
}
|
|
10
|
+
export interface Service {
|
|
11
|
+
stop(): Promise<void>;
|
|
12
|
+
cycleNow(): Promise<CycleResult>;
|
|
13
|
+
port: number;
|
|
14
|
+
}
|
|
15
|
+
/** Put the Scopebond hook back into agent settings that lost it. A visible change: each one is
|
|
16
|
+
* logged and returned, and only settings of agents this computer has are touched. */
|
|
17
|
+
export declare function repairHookEntries(harnesses?: Harness[]): Array<{
|
|
18
|
+
harness: Harness;
|
|
19
|
+
file: string;
|
|
20
|
+
}>;
|
|
21
|
+
export declare function startService(options: ServiceOptions): Promise<Service>;
|
|
22
|
+
//# sourceMappingURL=service.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"service.d.ts","sourceRoot":"","sources":["../src/service.ts"],"names":[],"mappings":"AAIA,OAAO,EAAiE,KAAK,OAAO,EAAE,MAAM,iBAAiB,CAAC;AAC9G,OAAO,EAAmE,KAAK,WAAW,EAAE,MAAM,YAAY,CAAC;AAG/G,eAAO,MAAM,aAAa,YAAY,CAAC;AAIvC,MAAM,WAAW,cAAc;IAAG,GAAG,EAAE,MAAM,CAAC;IAAC,UAAU,CAAC,EAAE,MAAM,CAAC;IAAC,SAAS,CAAC,EAAE,OAAO,KAAK,CAAC;IAAC,GAAG,CAAC,EAAE,CAAC,IAAI,EAAE,MAAM,KAAK,IAAI,CAAA;CAAE;AAE5H,MAAM,WAAW,OAAO;IAAG,IAAI,IAAI,OAAO,CAAC,IAAI,CAAC,CAAC;IAAC,QAAQ,IAAI,OAAO,CAAC,WAAW,CAAC,CAAC;IAAC,IAAI,EAAE,MAAM,CAAA;CAAE;AAElG;sFACsF;AACtF,wBAAgB,iBAAiB,CAAC,SAAS,GAAE,OAAO,EAAwB,GAAG,KAAK,CAAC;IAAE,OAAO,EAAE,OAAO,CAAC;IAAC,IAAI,EAAE,MAAM,CAAA;CAAE,CAAC,CAOvH;AAED,wBAAsB,YAAY,CAAC,OAAO,EAAE,cAAc,GAAG,OAAO,CAAC,OAAO,CAAC,CA4C5E"}
|
package/dist/service.js
ADDED
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
// The resident loop: one cycle now, then one every interval, sooner after a change is asked for,
|
|
2
|
+
// backing off while the workspace is unreachable. Exactly one agent serves a Scopebond home: a
|
|
3
|
+
// second one finds the first answering and exits.
|
|
4
|
+
import { userHarnessFile, writeHarnessConfig, hookCommand, hookVersion } from "@scopebond/hook";
|
|
5
|
+
import { computerStatus, expectedHarnesses, missingHookEntries, runCycle } from "./agent.js";
|
|
6
|
+
import { callAgent, startControl } from "./ipc.js";
|
|
7
|
+
export const AGENT_VERSION = "agent/1";
|
|
8
|
+
const INTERVAL_MS = 60_000;
|
|
9
|
+
const MAX_BACKOFF_MS = 15 * 60_000;
|
|
10
|
+
/** Put the Scopebond hook back into agent settings that lost it. A visible change: each one is
|
|
11
|
+
* logged and returned, and only settings of agents this computer has are touched. */
|
|
12
|
+
export function repairHookEntries(harnesses = expectedHarnesses()) {
|
|
13
|
+
const repaired = [];
|
|
14
|
+
for (const harness of missingHookEntries(harnesses)) {
|
|
15
|
+
const file = writeHarnessConfig(userHarnessFile(harness), harness, hookCommand(harness));
|
|
16
|
+
repaired.push({ harness, file });
|
|
17
|
+
}
|
|
18
|
+
return repaired;
|
|
19
|
+
}
|
|
20
|
+
export async function startService(options) {
|
|
21
|
+
const log = options.log ?? ((line) => console.log(`${new Date().toISOString()} ${line}`));
|
|
22
|
+
if (await callAgent(options.dir, "GET", "/status", undefined, 2_000))
|
|
23
|
+
throw new Error("a Scopebond Agent is already running for this computer");
|
|
24
|
+
const interval = options.intervalMs ?? INTERVAL_MS;
|
|
25
|
+
let last = null;
|
|
26
|
+
let failures = 0;
|
|
27
|
+
let timer = null;
|
|
28
|
+
let running = null;
|
|
29
|
+
let stopped = false;
|
|
30
|
+
const cycle = async () => {
|
|
31
|
+
if (running)
|
|
32
|
+
return running;
|
|
33
|
+
running = runCycle({ dir: options.dir, fetchImpl: options.fetchImpl }).then((result) => {
|
|
34
|
+
last = result;
|
|
35
|
+
failures = result.deliveryError ? failures + 1 : 0;
|
|
36
|
+
if (result.delivered)
|
|
37
|
+
log(`delivered ${result.delivered} record(s); ${result.pending} waiting`);
|
|
38
|
+
if (result.deliveryError)
|
|
39
|
+
log(`delivery problem: ${result.deliveryError}`);
|
|
40
|
+
return result;
|
|
41
|
+
}).finally(() => { running = null; });
|
|
42
|
+
return running;
|
|
43
|
+
};
|
|
44
|
+
const schedule = () => {
|
|
45
|
+
if (stopped)
|
|
46
|
+
return;
|
|
47
|
+
const delay = failures ? Math.min(MAX_BACKOFF_MS, interval * 2 ** Math.min(failures, 6)) : interval;
|
|
48
|
+
timer = setTimeout(() => { void cycle().finally(schedule); }, delay);
|
|
49
|
+
};
|
|
50
|
+
const control = await startControl(options.dir, `${AGENT_VERSION} hook/${hookVersion()}`, {
|
|
51
|
+
"GET /status": () => ({ ...computerStatus(options.dir), agent: { pid: process.pid, version: AGENT_VERSION, last_cycle: last } }),
|
|
52
|
+
"POST /flush": async () => ({ cycle: await cycle() }),
|
|
53
|
+
"POST /repair": () => {
|
|
54
|
+
const repaired = repairHookEntries();
|
|
55
|
+
for (const r of repaired)
|
|
56
|
+
log(`repaired the Scopebond hook entry in ${r.file}`);
|
|
57
|
+
return { repaired };
|
|
58
|
+
},
|
|
59
|
+
});
|
|
60
|
+
log(`Scopebond Agent running for ${options.dir} (control on 127.0.0.1:${control.endpoint.port})`);
|
|
61
|
+
await cycle();
|
|
62
|
+
schedule();
|
|
63
|
+
return {
|
|
64
|
+
port: control.endpoint.port,
|
|
65
|
+
cycleNow: cycle,
|
|
66
|
+
stop: async () => { stopped = true; if (timer)
|
|
67
|
+
clearTimeout(timer); await running?.catch(() => undefined); await control.close(); },
|
|
68
|
+
};
|
|
69
|
+
}
|
|
70
|
+
//# sourceMappingURL=service.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"service.js","sourceRoot":"","sources":["../src/service.ts"],"names":[],"mappings":"AAAA,iGAAiG;AACjG,+FAA+F;AAC/F,kDAAkD;AAElD,OAAO,EAAE,eAAe,EAAE,kBAAkB,EAAE,WAAW,EAAE,WAAW,EAAgB,MAAM,iBAAiB,CAAC;AAC9G,OAAO,EAAE,cAAc,EAAE,iBAAiB,EAAE,kBAAkB,EAAE,QAAQ,EAAoB,MAAM,YAAY,CAAC;AAC/G,OAAO,EAAE,SAAS,EAAE,YAAY,EAAE,MAAM,UAAU,CAAC;AAEnD,MAAM,CAAC,MAAM,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AE,GAAG,EAAE,CAAC,CAAC,EAAE,GAAG,cAAc,CAAC,OAAO,CAAC,GAAG,CAAC,EAAE,KAAK,EAAE,EAAE,GAAG,EAAE,OAAO,CAAC,GAAG,EAAE,OAAO,EAAE,aAAa,EAAE,UAAU,EAAE,IAAI,EAAE,EAAE,CAAC;QAChI,aAAa,EAAE,KAAK,IAAI,EAAE,CAAC,CAAC,EAAE,KAAK,EAAE,MAAM,KAAK,EAAE,EAAE,CAAC;QACrD,cAAc,EAAE,GAAG,EAAE;YACnB,MAAM,QAAQ,GAAG,iBAAiB,EAAE,CAAC;YACrC,KAAK,MAAM,CAAC,IAAI,QAAQ;gBAAE,GAAG,CAAC,wCAAwC,CAAC,CAAC,IAAI,EAAE,CAAC,CAAC;YAChF,OAAO,EAAE,QAAQ,EAAE,CAAC;QACtB,CAAC;KACF,CAAC,CAAC;IACH,GAAG,CAAC,+BAA+B,OAAO,CAAC,GAAG,0BAA0B,OAAO,CAAC,QAAQ,CAAC,IAAI,GAAG,CAAC,CAAC;IAClG,MAAM,KAAK,EAAE,CAAC;IACd,QAAQ,EAAE,CAAC;IACX,OAAO;QACL,IAAI,EAAE,OAAO,CAAC,QAAQ,CAAC,IAAI;QAC3B,QAAQ,EAAE,KAAK;QACf,IAAI,EAAE,KAAK,IAAI,EAAE,GAAG,OAAO,GAAG,IAAI,CAAC,CAAC,IAAI,KAAK;YAAE,YAAY,CAAC,KAAK,CAAC,CAAC,CAAC,MAAM,OAAO,EAAE,KAAK,CAAC,GAAG,EAAE,CAAC,SAAS,CAAC,CAAC,CAAC,MAAM,OAAO,CAAC,KAAK,EAAE,CAAC,CAAC,CAAC;KACpI,CAAC;AACJ,CAAC","sourcesContent":["// The resident loop: one cycle now, then one every interval, sooner after a change is asked for,\n// backing off while the workspace is unreachable. Exactly one agent serves a Scopebond home: a\n// second one finds the first answering and exits.\n\nimport { userHarnessFile, writeHarnessConfig, hookCommand, hookVersion, type Harness } from \"@scopebond/hook\";\nimport { computerStatus, expectedHarnesses, missingHookEntries, runCycle, type CycleResult } from \"./agent.js\";\nimport { callAgent, startControl } from \"./ipc.js\";\n\nexport const AGENT_VERSION = \"agent/1\";\nconst INTERVAL_MS = 60_000;\nconst MAX_BACKOFF_MS = 15 * 60_000;\n\nexport interface ServiceOptions { dir: string; intervalMs?: number; fetchImpl?: typeof fetch; log?: (line: string) => void }\n\nexport interface Service { stop(): Promise<void>; cycleNow(): Promise<CycleResult>; port: number }\n\n/** Put the Scopebond hook back into agent settings that lost it. A visible change: each one is\n * logged and returned, and only settings of agents this computer has are touched. */\nexport function repairHookEntries(harnesses: Harness[] = expectedHarnesses()): Array<{ harness: Harness; file: string }> {\n const repaired: Array<{ harness: Harness; file: string }> = [];\n for (const harness of missingHookEntries(harnesses)) {\n const file = writeHarnessConfig(userHarnessFile(harness), harness, hookCommand(harness));\n repaired.push({ harness, file });\n }\n return repaired;\n}\n\nexport async function startService(options: ServiceOptions): Promise<Service> {\n const log = options.log ?? ((line: string) => console.log(`${new Date().toISOString()} ${line}`));\n if (await callAgent(options.dir, \"GET\", \"/status\", undefined, 2_000)) throw new Error(\"a Scopebond Agent is already running for this computer\");\n const interval = options.intervalMs ?? INTERVAL_MS;\n let last: CycleResult | null = null;\n let failures = 0;\n let timer: ReturnType<typeof setTimeout> | null = null;\n let running: Promise<CycleResult> | null = null;\n let stopped = false;\n\n const cycle = async (): Promise<CycleResult> => {\n if (running) return running;\n running = runCycle({ dir: options.dir, fetchImpl: options.fetchImpl }).then((result) => {\n last = result;\n failures = result.deliveryError ? failures + 1 : 0;\n if (result.delivered) log(`delivered ${result.delivered} record(s); ${result.pending} waiting`);\n if (result.deliveryError) log(`delivery problem: ${result.deliveryError}`);\n return result;\n }).finally(() => { running = null; });\n return running;\n };\n const schedule = () => {\n if (stopped) return;\n const delay = failures ? Math.min(MAX_BACKOFF_MS, interval * 2 ** Math.min(failures, 6)) : interval;\n timer = setTimeout(() => { void cycle().finally(schedule); }, delay);\n };\n\n const control = await startControl(options.dir, `${AGENT_VERSION} hook/${hookVersion()}`, {\n \"GET /status\": () => ({ ...computerStatus(options.dir), agent: { pid: process.pid, version: AGENT_VERSION, last_cycle: last } }),\n \"POST /flush\": async () => ({ cycle: await cycle() }),\n \"POST /repair\": () => {\n const repaired = repairHookEntries();\n for (const r of repaired) log(`repaired the Scopebond hook entry in ${r.file}`);\n return { repaired };\n },\n });\n log(`Scopebond Agent running for ${options.dir} (control on 127.0.0.1:${control.endpoint.port})`);\n await cycle();\n schedule();\n return {\n port: control.endpoint.port,\n cycleNow: cycle,\n stop: async () => { stopped = true; if (timer) clearTimeout(timer); await running?.catch(() => undefined); await control.close(); },\n };\n}\n"]}
|
package/package.json
ADDED
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@scopebond/agent",
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "The Scopebond Agent — one resident process per user that delivers this computer's signed records to its Scopebond workspace, keeps its rules and connection current, and reports its health, so nobody has to run a command to keep it working.",
|
|
5
|
+
"license": "Apache-2.0",
|
|
6
|
+
"author": "Avouro LLC",
|
|
7
|
+
"homepage": "https://github.com/avouro-com/scopebond/tree/main/packages/agent#readme",
|
|
8
|
+
"repository": {
|
|
9
|
+
"type": "git",
|
|
10
|
+
"url": "https://github.com/avouro-com/scopebond.git",
|
|
11
|
+
"directory": "packages/agent"
|
|
12
|
+
},
|
|
13
|
+
"bugs": {
|
|
14
|
+
"url": "https://github.com/avouro-com/scopebond/issues"
|
|
15
|
+
},
|
|
16
|
+
"keywords": [
|
|
17
|
+
"scopebond",
|
|
18
|
+
"ai-agents",
|
|
19
|
+
"agent",
|
|
20
|
+
"delivery",
|
|
21
|
+
"claude-code"
|
|
22
|
+
],
|
|
23
|
+
"engines": {
|
|
24
|
+
"node": ">=22.13"
|
|
25
|
+
},
|
|
26
|
+
"type": "module",
|
|
27
|
+
"main": "dist/index.js",
|
|
28
|
+
"types": "dist/index.d.ts",
|
|
29
|
+
"bin": {
|
|
30
|
+
"scopebond-agent": "dist/cli.js"
|
|
31
|
+
},
|
|
32
|
+
"exports": {
|
|
33
|
+
".": {
|
|
34
|
+
"types": "./dist/index.d.ts",
|
|
35
|
+
"default": "./dist/index.js"
|
|
36
|
+
}
|
|
37
|
+
},
|
|
38
|
+
"files": [
|
|
39
|
+
"dist"
|
|
40
|
+
],
|
|
41
|
+
"dependencies": {
|
|
42
|
+
"@scopebond/gateway": "^0.12.0",
|
|
43
|
+
"@scopebond/sdk": "^0.1.3",
|
|
44
|
+
"@scopebond/hook": "^0.15.0"
|
|
45
|
+
},
|
|
46
|
+
"publishConfig": {
|
|
47
|
+
"access": "public"
|
|
48
|
+
},
|
|
49
|
+
"scripts": {
|
|
50
|
+
"build": "tsc -p tsconfig.json",
|
|
51
|
+
"test": "tsc -p tsconfig.json && node --test test/*.test.mjs"
|
|
52
|
+
}
|
|
53
|
+
}
|