@mmerterden/multi-agent-pipeline 23.3.0 → 23.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (224) hide show
  1. package/CHANGELOG.md +44 -0
  2. package/README.md +25 -6
  3. package/README.tr.md +26 -7
  4. package/docs/adr/0008-installer-modularization-and-secret-leak-defense.md +1 -1
  5. package/docs/adr/0010-own-code-graph.md +299 -8
  6. package/docs/architecture.md +3 -3
  7. package/docs/ecosystem.md +10 -10
  8. package/docs/engineering.md +4 -4
  9. package/docs/facts.json +8 -8
  10. package/docs/features.md +5 -5
  11. package/docs/performance.md +17 -17
  12. package/install/_dev-only-files.mjs +9 -0
  13. package/install/claude.mjs +28 -2
  14. package/install/templates/claude-hooks.json +32 -1
  15. package/manifest.json +223 -155
  16. package/package.json +11 -3
  17. package/pipeline/commands/multi-agent/SKILL.md +1 -1
  18. package/pipeline/commands/multi-agent/design-check/SKILL.md +2 -2
  19. package/pipeline/commands/multi-agent/diff-explain/SKILL.md +3 -3
  20. package/pipeline/commands/multi-agent/graph/SKILL.md +57 -24
  21. package/pipeline/commands/multi-agent/pair/SKILL.md +92 -0
  22. package/pipeline/commands/multi-agent/prune-prompts/SKILL.md +1 -1
  23. package/pipeline/commands/multi-agent/search/SKILL.md +7 -1
  24. package/pipeline/commands/multi-agent/status/SKILL.md +4 -0
  25. package/pipeline/commands/multi-agent/sync/SKILL.md +3 -3
  26. package/pipeline/contract/CHANGELOG.md +49 -0
  27. package/pipeline/contract/build.mjs +13 -1
  28. package/pipeline/contract/fixtures/error-invalid-request.json +1 -1
  29. package/pipeline/contract/fixtures/error-unauthorized.json +1 -1
  30. package/pipeline/contract/fixtures/runs-awaiting-question.json +4 -1
  31. package/pipeline/contract/fixtures/runs-empty.json +1 -1
  32. package/pipeline/contract/fixtures/runs-failed.json +4 -1
  33. package/pipeline/contract/fixtures/runs-old-schema.json +3 -0
  34. package/pipeline/contract/fixtures/runs-pr-opened-redacted.json +4 -1
  35. package/pipeline/contract/fixtures/runs-pr-opened.json +4 -1
  36. package/pipeline/contract/fixtures/runs-running.json +4 -1
  37. package/pipeline/contract/manifest.json +28 -15
  38. package/pipeline/contract/types/index.d.ts +55 -3
  39. package/pipeline/lib/detach-self.mjs +95 -0
  40. package/pipeline/lib/public-mcp-servers.mjs +33 -0
  41. package/pipeline/lib/rotated-log.mjs +93 -0
  42. package/pipeline/lib/tls-trust.mjs +29 -0
  43. package/pipeline/lib/usage-lifecycle.mjs +9 -11
  44. package/pipeline/lib/usage-names.generated.mjs +614 -0
  45. package/pipeline/lib/usage-run-key.mjs +235 -0
  46. package/pipeline/lib/usage-vocab.mjs +210 -0
  47. package/pipeline/multi-agent-refs/analysis/intake.md +2 -2
  48. package/pipeline/multi-agent-refs/analysis/render.md +1 -1
  49. package/pipeline/multi-agent-refs/channels/generator.md +4 -5
  50. package/pipeline/multi-agent-refs/cross-cli-contract.md +3 -3
  51. package/pipeline/multi-agent-refs/design-check/scope-and-ledger.md +1 -1
  52. package/pipeline/multi-agent-refs/features/code-graph.md +146 -11
  53. package/pipeline/multi-agent-refs/features/code-intelligence.md +16 -14
  54. package/pipeline/multi-agent-refs/features/dev-critic.md +7 -7
  55. package/pipeline/multi-agent-refs/features/model-fallback.md +6 -4
  56. package/pipeline/multi-agent-refs/features/remote-control.md +252 -0
  57. package/pipeline/multi-agent-refs/features/review-delta.md +1 -1
  58. package/pipeline/multi-agent-refs/features/review-file-set.md +3 -3
  59. package/pipeline/multi-agent-refs/features/review-multi-repo.md +1 -1
  60. package/pipeline/multi-agent-refs/features/session-brief.md +42 -0
  61. package/pipeline/multi-agent-refs/features/skill-conformance.md +3 -3
  62. package/pipeline/multi-agent-refs/features/usage-reporting.md +252 -24
  63. package/pipeline/multi-agent-refs/help/en.md +3 -2
  64. package/pipeline/multi-agent-refs/help/tr.md +3 -2
  65. package/pipeline/multi-agent-refs/knowledge.md +1 -1
  66. package/pipeline/multi-agent-refs/orchestrator/dispatcher.md +1 -1
  67. package/pipeline/multi-agent-refs/phases/operations.md +2 -2
  68. package/pipeline/multi-agent-refs/phases/phase-0-init.md +13 -12
  69. package/pipeline/multi-agent-refs/phases/phase-1-plan.md +4 -4
  70. package/pipeline/multi-agent-refs/phases/phase-3-review.md +2 -0
  71. package/pipeline/multi-agent-refs/phases/phase-5-report.md +1 -1
  72. package/pipeline/multi-agent-refs/platform-parity.md +2 -2
  73. package/pipeline/multi-agent-refs/wiki-capture.md +3 -17
  74. package/pipeline/office/index.html +1207 -233
  75. package/pipeline/office/toolkit.json +1 -1
  76. package/pipeline/rules/outside-the-pipeline.md +1 -1
  77. package/pipeline/schemas/activity.schema.json +23 -0
  78. package/pipeline/schemas/agent-state.schema.json +6 -1
  79. package/pipeline/schemas/code-graph-calls.schema.json +254 -0
  80. package/pipeline/schemas/code-graph-docs.schema.json +223 -0
  81. package/pipeline/schemas/code-graph-infra.schema.json +227 -0
  82. package/pipeline/schemas/code-graph.schema.json +2 -2
  83. package/pipeline/schemas/examples/design-check-config.json +27 -0
  84. package/pipeline/schemas/learning-curve.schema.json +67 -0
  85. package/pipeline/schemas/office-jobs.json +69 -2
  86. package/pipeline/schemas/office-jobs.schema.json +8 -1
  87. package/pipeline/schemas/phases.json +5 -0
  88. package/pipeline/schemas/phases.schema.json +8 -0
  89. package/pipeline/schemas/prefs.schema.json +46 -12
  90. package/pipeline/schemas/runs-index.schema.json +17 -0
  91. package/pipeline/schemas/toolkit-path-params.json +84 -8
  92. package/pipeline/scripts/README.md +1 -0
  93. package/pipeline/scripts/_code-graph.mjs +184 -103
  94. package/pipeline/scripts/_contract-core.mjs +1 -1
  95. package/pipeline/scripts/_contract-routes-office.mjs +21 -0
  96. package/pipeline/scripts/_diff-impact.mjs +21 -2
  97. package/pipeline/scripts/_graph-sidecars.mjs +372 -0
  98. package/pipeline/scripts/_http-post.mjs +103 -115
  99. package/pipeline/scripts/_safe-read.mjs +57 -0
  100. package/pipeline/scripts/_skill-practices.mjs +26 -0
  101. package/pipeline/scripts/_strip-code.mjs +380 -0
  102. package/pipeline/scripts/activity-snapshot.mjs +13 -1
  103. package/pipeline/scripts/aggregate-metrics.mjs +3 -5
  104. package/pipeline/scripts/call-graph/index.mjs +78 -0
  105. package/pipeline/scripts/call-graph/lang/cpp.mjs +308 -0
  106. package/pipeline/scripts/call-graph/lang/csharp.mjs +130 -0
  107. package/pipeline/scripts/call-graph/lang/go.mjs +303 -0
  108. package/pipeline/scripts/call-graph/lang/java.mjs +370 -0
  109. package/pipeline/scripts/call-graph/lang/kotlin.mjs +397 -0
  110. package/pipeline/scripts/call-graph/lang/python.mjs +399 -0
  111. package/pipeline/scripts/call-graph/lang/rust.mjs +345 -0
  112. package/pipeline/scripts/call-graph/lang/shared.mjs +230 -0
  113. package/pipeline/scripts/call-graph/lang/swift.mjs +432 -0
  114. package/pipeline/scripts/call-graph/lang/typescript.mjs +692 -0
  115. package/pipeline/scripts/call-graph/lex.mjs +396 -0
  116. package/pipeline/scripts/call-graph/platform.mjs +86 -0
  117. package/pipeline/scripts/call-graph/profiles.mjs +89 -0
  118. package/pipeline/scripts/call-graph/resolve.mjs +1125 -0
  119. package/pipeline/scripts/call-graph/scan.mjs +267 -0
  120. package/pipeline/scripts/code-graph-rules/android.json +7 -2
  121. package/pipeline/scripts/code-graph-rules/cpp.json +99 -0
  122. package/pipeline/scripts/code-graph-rules/csharp.json +102 -0
  123. package/pipeline/scripts/code-graph-rules/go.json +2 -1
  124. package/pipeline/scripts/code-graph-rules/ios.json +3 -1
  125. package/pipeline/scripts/code-graph-rules/java.json +76 -0
  126. package/pipeline/scripts/code-graph-rules/node.json +7 -2
  127. package/pipeline/scripts/code-graph-rules/python.json +6 -2
  128. package/pipeline/scripts/code-graph-rules/rust.json +105 -0
  129. package/pipeline/scripts/contract-server.mjs +1 -0
  130. package/pipeline/scripts/feedback-send.mjs +26 -26
  131. package/pipeline/scripts/gate-ledger.mjs +2 -1
  132. package/pipeline/scripts/gen-usage-names.mjs +124 -0
  133. package/pipeline/scripts/graph-affected.mjs +109 -20
  134. package/pipeline/scripts/graph-build.mjs +95 -15
  135. package/pipeline/scripts/graph-export.mjs +272 -0
  136. package/pipeline/scripts/graph-hint.mjs +15 -2
  137. package/pipeline/scripts/graph-query.mjs +305 -26
  138. package/pipeline/scripts/graph-report.mjs +187 -1
  139. package/pipeline/scripts/health-report.mjs +3 -4
  140. package/pipeline/scripts/infra/docs.mjs +317 -0
  141. package/pipeline/scripts/infra/extract.mjs +998 -0
  142. package/pipeline/scripts/infra/graph.mjs +245 -0
  143. package/pipeline/scripts/infra/yaml-lite.mjs +311 -0
  144. package/pipeline/scripts/job-launch.mjs +67 -2
  145. package/pipeline/scripts/learning-curve.mjs +288 -178
  146. package/pipeline/scripts/log-metric.sh +10 -1
  147. package/pipeline/scripts/note-agent-event.mjs +3 -4
  148. package/pipeline/scripts/note-command-use.mjs +333 -0
  149. package/pipeline/scripts/note-command-use.sh +126 -0
  150. package/pipeline/scripts/note-mcp-call.sh +89 -0
  151. package/pipeline/scripts/note-mcp-failure.mjs +272 -1
  152. package/pipeline/scripts/note-session.sh +62 -3
  153. package/pipeline/scripts/note-skill-use.mjs +58 -2
  154. package/pipeline/scripts/office-build.mjs +115 -1
  155. package/pipeline/scripts/office-memory.mjs +14 -5
  156. package/pipeline/scripts/pair.mjs +333 -0
  157. package/pipeline/scripts/pre-push-check.sh +1 -1
  158. package/pipeline/scripts/remote/cbor.mjs +128 -0
  159. package/pipeline/scripts/remote/contract.mjs +98 -0
  160. package/pipeline/scripts/remote/handler.mjs +317 -0
  161. package/pipeline/scripts/remote/handles.mjs +57 -0
  162. package/pipeline/scripts/remote/lifecycle.mjs +186 -0
  163. package/pipeline/scripts/remote/listener.mjs +204 -0
  164. package/pipeline/scripts/remote/lockout.mjs +103 -0
  165. package/pipeline/scripts/remote/nonces.mjs +61 -0
  166. package/pipeline/scripts/remote/pairing.mjs +519 -0
  167. package/pipeline/scripts/remote/qr-encode.mjs +459 -0
  168. package/pipeline/scripts/remote/store.mjs +188 -0
  169. package/pipeline/scripts/remote/transport.mjs +211 -0
  170. package/pipeline/scripts/remote/verbs.json +70 -0
  171. package/pipeline/scripts/remote/verbs.mjs +217 -0
  172. package/pipeline/scripts/remote/webauthn.mjs +169 -0
  173. package/pipeline/scripts/remote/wire.mjs +364 -0
  174. package/pipeline/scripts/remote-listener.mjs +83 -0
  175. package/pipeline/scripts/route-learn.mjs +4 -4
  176. package/pipeline/scripts/run-kill.mjs +1 -1
  177. package/pipeline/scripts/run-write.mjs +13 -2
  178. package/pipeline/scripts/runs-index.mjs +30 -3
  179. package/pipeline/scripts/search-logs.sh +9 -0
  180. package/pipeline/scripts/session-brief.mjs +458 -0
  181. package/pipeline/scripts/session-brief.sh +130 -0
  182. package/pipeline/scripts/test-gap-rules/cpp.json +25 -0
  183. package/pipeline/scripts/test-gap-rules/csharp.json +20 -0
  184. package/pipeline/scripts/test-gap-rules/java.json +20 -0
  185. package/pipeline/scripts/test-gap-rules/rust.json +14 -0
  186. package/pipeline/scripts/token-budget-report.mjs +3 -2
  187. package/pipeline/scripts/uninstall.mjs +29 -0
  188. package/pipeline/scripts/usage-access.mjs +16 -31
  189. package/pipeline/scripts/usage-health.mjs +31 -62
  190. package/pipeline/scripts/usage-register-beacon.mjs +11 -22
  191. package/pipeline/scripts/usage-register.mjs +39 -29
  192. package/pipeline/scripts/usage-report.mjs +579 -178
  193. package/pipeline/scripts/validate-code-graph.mjs +361 -111
  194. package/pipeline/scripts/write-state.mjs +39 -0
  195. package/pipeline/skills/.skill-manifest.json +21 -17
  196. package/pipeline/skills/.skills-index.json +13 -2
  197. package/pipeline/skills/shared/README.md +5 -4
  198. package/pipeline/skills/shared/core/multi-agent-design-check/SKILL.md +1 -1
  199. package/pipeline/skills/shared/core/multi-agent-diff-explain/SKILL.md +3 -3
  200. package/pipeline/skills/shared/core/multi-agent-graph/SKILL.md +55 -21
  201. package/pipeline/skills/shared/core/multi-agent-pair/SKILL.md +41 -0
  202. package/pipeline/skills/shared/core/multi-agent-prune-prompts/SKILL.md +1 -1
  203. package/pipeline/skills/shared/core/multi-agent-sync/SKILL.md +3 -3
  204. package/pipeline/skills/shared/external/app-store-optimization/SKILL.md +2 -3
  205. package/pipeline/skills/shared/external/app-store-optimization/references/keyword-research-methodology.md +2 -2
  206. package/pipeline/skills/shared/external/app-store-optimization/references/product-page-variants.md +2 -2
  207. package/pipeline/skills/shared/external/app-store-review/SKILL.md +11 -4
  208. package/pipeline/skills/shared/external/build-settings-audit/SKILL.md +1 -1
  209. package/pipeline/skills/shared/external/build-time-benchmark/SKILL.md +5 -5
  210. package/pipeline/skills/shared/external/build-time-fixes/SKILL.md +5 -5
  211. package/pipeline/skills/shared/external/build-time-optimizer/SKILL.md +6 -6
  212. package/pipeline/skills/shared/external/free-llm-apis/references/providers.md +1 -0
  213. package/pipeline/skills/shared/external/ios-coding-standard/references/STANDARD.md +2 -2
  214. package/pipeline/skills/shared/external/ios-haptics/references/core-haptics.md +1 -1
  215. package/pipeline/skills/shared/external/localization-reuse-map/references/publish-and-snapshot.md +1 -1
  216. package/pipeline/skills/shared/external/package-build-audit/SKILL.md +3 -3
  217. package/pipeline/skills/shared/external/reverse-engineer-own-app/SKILL.md +2 -3
  218. package/pipeline/skills/shared/external/swift-compile-hotspots/SKILL.md +2 -2
  219. package/pipeline/skills/shared/external/weatherkit/SKILL.md +5 -6
  220. package/pipeline/skills/skills-index.md +3 -2
  221. package/docs/FIGMA_PIPELINE.md +0 -137
  222. package/pipeline/lib/identifier-scan.mjs +0 -156
  223. package/pipeline/scripts/publish-staged.mjs +0 -324
  224. package/pipeline/skills/shared/external/ios-coding-standard/scripts/check_structure.py +0 -765
@@ -0,0 +1,317 @@
1
+ /**
2
+ * handler.mjs - what this computer checks before it acts on one request the
3
+ * site handed it, and how it answers.
4
+ *
5
+ * The site is not trusted. For every request, in this order, nothing below is
6
+ * taken on the site's word:
7
+ *
8
+ * 1. shape and size of every field, then: the device is one this computer
9
+ * pinned after a local confirmation, and the envelope version is 3;
10
+ * 2. the sequence number is newer than the highest accepted for the device,
11
+ * and the request's freshness nonce (cn) is one this computer issued in
12
+ * its last polls, less than 120 seconds ago, and not yet used;
13
+ * 3. the passkey assertion, over a challenge recomputed here from the server
14
+ * nonce, device, this machine's id, the verb, the run tag, the sequence
15
+ * number, the exact ciphertext and the freshness nonce, verifies against the key pinned at pairing
16
+ * (rpIdHash, user presence and verification, type, origin, challenge,
17
+ * ES256 signature, counter);
18
+ * 4. the envelope opens under the device's key with the header as
19
+ * authenticated data. The sequence number and the passkey counter are
20
+ * committed here, so even a request refused below cannot be replayed;
21
+ * 5. the plaintext verb equals the clear one and is a contract verb at an
22
+ * enabled phase this computer implements, the arguments validate against
23
+ * the contract schema, and `iat` is within 10 minutes in either
24
+ * direction;
25
+ * 6. for a run verb the run tag matches the run named inside the payload;
26
+ * 7. a mutating verb is refused when this machine is unattended.
27
+ *
28
+ * A failure in steps 1 to 4 is dropped without an answer: the sender is not
29
+ * proven. A failure in steps 5 to 7 is an authenticated refusal, answered
30
+ * with a fixed error code. Every outcome is audited without content.
31
+ *
32
+ * Freshness: the request carries a nonce this computer issued, bound into the
33
+ * authenticated header and the passkey challenge. It is accepted once, within
34
+ * its lifetime (nonces.mjs). The sequence number (accepted once, and only if
35
+ * newer than every earlier one), the passkey counter where the authenticator
36
+ * keeps one, and `iat` inside the authenticated payload bound replay further.
37
+ *
38
+ * @module pipeline/scripts/remote/handler
39
+ */
40
+
41
+ import { CONTRACT, validateArgs, verbSpec } from "./contract.mjs";
42
+ import { audit, mutateDevices, readDevices } from "./store.mjs";
43
+ import { WebAuthnError, verifyAssertion } from "./webauthn.mjs";
44
+ import {
45
+ REQUEST_CT_MAX_BYTES,
46
+ SEQ_MAX,
47
+ WIRE_VERSION,
48
+ WireError,
49
+ b64uDecode,
50
+ b64uEncode,
51
+ equalBytes,
52
+ open,
53
+ isFreshNonce,
54
+ runTag,
55
+ seal,
56
+ verbChallenge,
57
+ } from "./wire.mjs";
58
+
59
+ export const IAT_WINDOW_MS = 10 * 60 * 1000;
60
+ const VERB_NAME = /^[a-z][a-z0-9_]{0,31}$/;
61
+ const DEVICE_ID = /^[A-Za-z0-9-]{8,64}$/;
62
+ const RUN_TAG = /^[A-Za-z0-9_-]{11}$/;
63
+ const MAX_FIELD_CHARS = 2800;
64
+
65
+ class Drop extends Error {
66
+ constructor(reason) {
67
+ super(reason);
68
+ this.reason = reason;
69
+ }
70
+ }
71
+
72
+ const isB64 = (v, max) =>
73
+ typeof v === "string" && v.length > 0 && v.length <= max && /^[A-Za-z0-9_-]+$/.test(v);
74
+
75
+ function parseItem(item) {
76
+ if (!item || typeof item !== "object") throw new Drop("shape");
77
+ const { deviceId, verb, runTag: tag, nonce, envelope, assertion } = item;
78
+ if (typeof deviceId !== "string" || !DEVICE_ID.test(deviceId)) throw new Drop("shape");
79
+ if (typeof verb !== "string" || !VERB_NAME.test(verb)) throw new Drop("shape");
80
+ if (typeof tag !== "string" || (tag !== "" && !RUN_TAG.test(tag))) throw new Drop("shape");
81
+ if (!isB64(nonce, 43)) throw new Drop("shape");
82
+ if (!envelope || !isFreshNonce(envelope.cn)) throw new Drop("nonce");
83
+ if (!envelope || typeof envelope !== "object") throw new Drop("shape");
84
+ if (
85
+ !isB64(envelope.n, 16) ||
86
+ !isB64(envelope.ct, Math.ceil((REQUEST_CT_MAX_BYTES * 4) / 3) + 4)
87
+ ) {
88
+ throw new Drop("size");
89
+ }
90
+ if (!assertion || typeof assertion !== "object") throw new Drop("shape");
91
+ for (const key of ["credentialId", "clientDataJSON", "authenticatorData", "signature"]) {
92
+ if (!isB64(assertion[key], MAX_FIELD_CHARS)) throw new Drop("shape");
93
+ }
94
+ let nonceBytes;
95
+ let ctBytes;
96
+ try {
97
+ nonceBytes = b64uDecode(nonce);
98
+ ctBytes = b64uDecode(envelope.ct);
99
+ } catch {
100
+ throw new Drop("shape");
101
+ }
102
+ if (nonceBytes.length !== 32) throw new Drop("shape");
103
+ if (ctBytes.length > REQUEST_CT_MAX_BYTES) throw new Drop("size");
104
+ return { deviceId, verb, runTag: tag, nonce: nonceBytes, envelope, assertion };
105
+ }
106
+
107
+ function checkAssertion(device, req) {
108
+ const { assertion } = req;
109
+ let presented;
110
+ let pinned;
111
+ try {
112
+ presented = b64uDecode(assertion.credentialId);
113
+ pinned = b64uDecode(device.credentialId);
114
+ } catch {
115
+ throw new Drop("assertion");
116
+ }
117
+ if (!equalBytes(presented, pinned)) throw new Drop("assertion");
118
+ const expected = b64uEncode(
119
+ verbChallenge({
120
+ nonce: req.nonce,
121
+ deviceId: req.deviceId,
122
+ machineId: device.machineId,
123
+ verb: req.verb,
124
+ runTag: req.runTag,
125
+ seq: req.envelope.seq,
126
+ envelope: req.envelope,
127
+ }),
128
+ );
129
+ try {
130
+ return verifyAssertion({
131
+ clientDataJSON: b64uDecode(assertion.clientDataJSON),
132
+ authenticatorData: b64uDecode(assertion.authenticatorData),
133
+ signature: b64uDecode(assertion.signature),
134
+ expectedChallenge: expected,
135
+ rp: { rpId: device.rpId, origin: device.origin },
136
+ publicKeyCose: b64uDecode(device.credentialPublicKey),
137
+ storedSignCount: device.lastCounter,
138
+ }).signCount;
139
+ } catch (err) {
140
+ if (err instanceof WebAuthnError || err instanceof WireError) {
141
+ throw new Drop(`assertion:${err.code}`);
142
+ }
143
+ throw err;
144
+ }
145
+ }
146
+
147
+ function commit(env, deviceId, seq, counter) {
148
+ return mutateDevices(env, (doc) => {
149
+ const d = doc.devices[deviceId];
150
+ if (!d) throw new Drop("unknown-device");
151
+ if (seq <= d.lastSeq) throw new Drop("replay");
152
+ if (!((counter === 0 && d.lastCounter === 0) || counter > d.lastCounter))
153
+ throw new Drop("counter");
154
+ d.lastSeq = seq;
155
+ d.lastCounter = counter;
156
+ });
157
+ }
158
+
159
+ function reserveReplySeq(env, deviceId) {
160
+ return mutateDevices(env, (doc) => {
161
+ const d = doc.devices[deviceId];
162
+ if (!d) throw new Drop("unknown-device");
163
+ const seq = d.nextReplySeq;
164
+ if (seq > SEQ_MAX) throw new Drop("reply-counter");
165
+ d.nextReplySeq = seq + 1;
166
+ return seq;
167
+ });
168
+ }
169
+
170
+ function sealReply(env, device, req, payload) {
171
+ const replySeq = reserveReplySeq(env, req.deviceId);
172
+ const header = {
173
+ dir: "m2p",
174
+ deviceId: req.deviceId,
175
+ machineId: device.machineId,
176
+ verb: req.verb,
177
+ seq: replySeq,
178
+ re: req.envelope.seq,
179
+ cn: "",
180
+ };
181
+ const key = b64uDecode(device.keys.m2p);
182
+ let envelope;
183
+ try {
184
+ envelope = seal(key, header, payload);
185
+ } catch (err) {
186
+ if (!(err instanceof WireError) || err.code !== "size") throw err;
187
+ envelope = seal(key, header, { v: WIRE_VERSION, ok: false, error: "too_large" });
188
+ }
189
+ return { deviceId: req.deviceId, verb: req.verb, envelope };
190
+ }
191
+
192
+ const refusal = (error) => ({ v: WIRE_VERSION, ok: false, error });
193
+
194
+ /**
195
+ * Handles one queued request. Resolves to { reply, outcome, reason } where
196
+ * `reply` is a sealed reply for the site to relay, or null when the request
197
+ * is dropped.
198
+ *
199
+ * @param {object} item one element of the poll answer's `envelopes`
200
+ * @param {{env: object, executor: object, nonces: object, unattended: () => boolean, now?: () => number}} ctx
201
+ */
202
+ export async function handleRequest(item, ctx) {
203
+ const { env } = ctx;
204
+ const now = ctx.now ?? Date.now;
205
+ let auditVerb = "";
206
+ let auditDevice = "";
207
+ try {
208
+ const req = parseItem(item);
209
+ auditVerb = req.verb;
210
+ auditDevice = req.deviceId;
211
+ const device = readDevices(env).devices[req.deviceId];
212
+ if (!device) throw new Drop("unknown-device");
213
+ const { envelope } = req;
214
+ if (envelope.v !== WIRE_VERSION) throw new Drop("version");
215
+ if (!Number.isInteger(envelope.seq) || envelope.seq < 1 || envelope.seq > SEQ_MAX) {
216
+ throw new Drop("shape");
217
+ }
218
+ if (envelope.seq <= device.lastSeq) throw new Drop("replay");
219
+ if (!ctx.nonces.holds(envelope.cn)) throw new Drop("nonce");
220
+
221
+ const counter = checkAssertion(device, req);
222
+
223
+ let payload;
224
+ try {
225
+ payload = open(
226
+ b64uDecode(device.keys.p2m),
227
+ {
228
+ dir: "p2m",
229
+ deviceId: req.deviceId,
230
+ machineId: device.machineId,
231
+ verb: req.verb,
232
+ seq: envelope.seq,
233
+ re: 0,
234
+ cn: envelope.cn,
235
+ },
236
+ envelope,
237
+ );
238
+ } catch (err) {
239
+ if (err instanceof WireError) throw new Drop(`open:${err.code}`);
240
+ throw err;
241
+ }
242
+ if (!ctx.nonces.consume(envelope.cn)) throw new Drop("nonce");
243
+ commit(env, req.deviceId, envelope.seq, counter);
244
+ const gap = envelope.seq > device.lastSeq + 1;
245
+
246
+ const answer = await decide(req, device, payload, ctx, now);
247
+ const reply = sealReply(env, device, req, answer.payload);
248
+ audit(env, {
249
+ device: req.deviceId,
250
+ verb: req.verb,
251
+ outcome: answer.payload.ok ? "ok" : "refused",
252
+ reason: answer.payload.ok ? (gap ? "gap" : "") : answer.payload.error,
253
+ });
254
+ return {
255
+ reply,
256
+ outcome: answer.payload.ok ? "ok" : "refused",
257
+ reason: answer.payload.error ?? "",
258
+ };
259
+ } catch (err) {
260
+ if (!(err instanceof Drop)) throw err;
261
+ audit(env, {
262
+ device: auditDevice,
263
+ verb: auditVerb,
264
+ outcome: "dropped",
265
+ reason: dropCode(err.reason),
266
+ });
267
+ return { reply: null, outcome: "dropped", reason: err.reason };
268
+ }
269
+ }
270
+
271
+ const dropCode = (reason) =>
272
+ String(reason)
273
+ .toLowerCase()
274
+ .replace(/[^a-z0-9:_-]/g, "-")
275
+ .slice(0, 40);
276
+
277
+ async function decide(req, device, payload, ctx, now) {
278
+ const isObject = payload && typeof payload === "object" && !Array.isArray(payload);
279
+ if (!isObject || payload.v !== WIRE_VERSION || payload.verb !== req.verb) {
280
+ return { payload: refusal("verb") };
281
+ }
282
+ const spec = verbSpec(payload.verb);
283
+ if (!spec) {
284
+ const known = Object.prototype.hasOwnProperty.call(CONTRACT.verbs, payload.verb);
285
+ return { payload: refusal(known ? "phase" : "verb") };
286
+ }
287
+ const allowedKeys = ["v", "verb", "args", "iat"];
288
+ if (!Object.keys(payload).every((k) => allowedKeys.includes(k))) {
289
+ return { payload: refusal("args") };
290
+ }
291
+ const checked = validateArgs(spec, payload.args === undefined ? {} : payload.args);
292
+ if (!checked.ok) return { payload: refusal("args") };
293
+ if (!Number.isFinite(payload.iat) || Math.abs(now() - payload.iat) > IAT_WINDOW_MS) {
294
+ return { payload: refusal("iat") };
295
+ }
296
+
297
+ if (spec.target === "run") {
298
+ const tag = runTag(b64uDecode(device.keys.tag), checked.args.run);
299
+ if (!equalBytes(Buffer.from(tag), Buffer.from(req.runTag)))
300
+ return { payload: refusal("run_tag") };
301
+ } else if (req.runTag !== "") {
302
+ return { payload: refusal("run_tag") };
303
+ }
304
+
305
+ if (spec.mutating && ctx.unattended()) return { payload: refusal("unattended") };
306
+
307
+ const run = ctx.executor[payload.verb];
308
+ if (typeof run !== "function") return { payload: refusal("phase") };
309
+ try {
310
+ const result = await run(checked.args, { deviceId: req.deviceId });
311
+ return { payload: { v: WIRE_VERSION, ok: true, result } };
312
+ } catch (err) {
313
+ const code =
314
+ typeof err?.code === "string" && /^[a-z_]{1,32}$/.test(err.code) ? err.code : "internal";
315
+ return { payload: refusal(code) };
316
+ }
317
+ }
@@ -0,0 +1,57 @@
1
+ /**
2
+ * handles.mjs - opaque run handles (wire specification 3.1).
3
+ *
4
+ * The phone never sees a run id. `list_runs` hands out a random handle per
5
+ * run, the other run verbs take it back, and this table maps it to the run
6
+ * for the device that was given it. A handle means nothing to another device,
7
+ * contains nothing from the computer and lives until the process restarts or
8
+ * the device is removed.
9
+ *
10
+ * @module pipeline/scripts/remote/handles
11
+ */
12
+
13
+ import { randomBytes } from "node:crypto";
14
+
15
+ export const HANDLE_PATTERN = /^[A-Za-z0-9_-]{1,64}$/;
16
+ const HANDLE_BYTES = 9;
17
+ const MAX_PER_DEVICE = 512;
18
+
19
+ export class HandleTable {
20
+ #byDevice = new Map();
21
+
22
+ /** The handle for `runId` on `deviceId`: the same one while it lives, a new random one otherwise. */
23
+ issue(deviceId, runId) {
24
+ let table = this.#byDevice.get(deviceId);
25
+ if (!table) {
26
+ table = { byHandle: new Map(), byRun: new Map() };
27
+ this.#byDevice.set(deviceId, table);
28
+ }
29
+ const existing = table.byRun.get(runId);
30
+ if (existing) return existing;
31
+ if (table.byHandle.size >= MAX_PER_DEVICE) {
32
+ const oldest = table.byHandle.keys().next().value;
33
+ table.byRun.delete(table.byHandle.get(oldest));
34
+ table.byHandle.delete(oldest);
35
+ }
36
+ const handle = randomBytes(HANDLE_BYTES).toString("base64url");
37
+ table.byHandle.set(handle, runId);
38
+ table.byRun.set(runId, handle);
39
+ return handle;
40
+ }
41
+
42
+ /** The run id behind `handle` for this device, or null: a raw run id never resolves. */
43
+ resolve(deviceId, handle) {
44
+ if (typeof handle !== "string" || !HANDLE_PATTERN.test(handle)) return null;
45
+ return this.#byDevice.get(deviceId)?.byHandle.get(handle) ?? null;
46
+ }
47
+
48
+ /** The devices that currently hold handles. */
49
+ devices() {
50
+ return [...this.#byDevice.keys()];
51
+ }
52
+
53
+ /** Forgets every handle of a device that was removed. */
54
+ drop(deviceId) {
55
+ this.#byDevice.delete(deviceId);
56
+ }
57
+ }
@@ -0,0 +1,186 @@
1
+ /**
2
+ * lifecycle.mjs - start, stop and report the background listener, in the
3
+ * same pattern the office server uses (office-control.mjs):
4
+ *
5
+ * - one 0600 record (listener.json) in the 0700 state directory names the
6
+ * pid and start time of the process this module started;
7
+ * - the process is spawned detached, so it outlives the terminal that
8
+ * started it, and it ends when the last device is forgotten, when the
9
+ * site says the feature is off, or when `stop` is called;
10
+ * - a process is signalled only when it is owned by this user, its command
11
+ * line names remote-listener.mjs, and its start time matches the record,
12
+ * so a reused pid is never signalled;
13
+ * - a second start finds the record alive and does nothing: one instance.
14
+ *
15
+ * @module pipeline/scripts/remote/lifecycle
16
+ */
17
+
18
+ import { spawn, spawnSync } from "node:child_process";
19
+ import { rmSync } from "node:fs";
20
+ import { dirname, join } from "node:path";
21
+ import { fileURLToPath } from "node:url";
22
+ import { withFileLockSync } from "../../lib/json-file-lock.mjs";
23
+ import { readRegularJson } from "../../lib/regular-file.mjs";
24
+ import { writeFileSafe } from "../../lib/safe-write.mjs";
25
+ import { audit, ensureDir, listenerFile, readDevices } from "./store.mjs";
26
+
27
+ const HERE = dirname(fileURLToPath(import.meta.url));
28
+ export const LISTENER_SCRIPT = join(HERE, "..", "remote-listener.mjs");
29
+ const START_SKEW_MS = 120 * 1000;
30
+ const READY_MS = 5000;
31
+ const STOP_MS = 5000;
32
+
33
+ /**
34
+ * The only variables the listener inherits. TLS verification switches
35
+ * (NODE_TLS_*), NODE_OPTIONS, proxy variables and the usage token are not
36
+ * among them: the listener reads the token from the credential store itself.
37
+ * NODE_EXTRA_CA_CERTS is an opt-in for a network that inspects TLS with its
38
+ * own certificate authority; it adds trust anchors and does not switch
39
+ * verification off.
40
+ */
41
+ export const LISTENER_ENV_ALLOW = [
42
+ "PATH",
43
+ "HOME",
44
+ "USER",
45
+ "LOGNAME",
46
+ "LANG",
47
+ "LC_ALL",
48
+ "TMPDIR",
49
+ "MA_AUTOPILOT_ROOT",
50
+ "MULTI_AGENT_PREFS",
51
+ "MULTI_AGENT_UNATTENDED",
52
+ "LOGS_ROOT",
53
+ "MA_UNATTENDED_RUN_ROOT",
54
+ "MA_AP_CLAUDE_BIN",
55
+ "MA_AP_CLAUDE_INSTALLED_BIN",
56
+ "MA_AP_AGENTS_JSON",
57
+ "NODE_EXTRA_CA_CERTS",
58
+ ];
59
+
60
+ export function listenerEnv(env) {
61
+ const out = {};
62
+ for (const key of LISTENER_ENV_ALLOW) {
63
+ if (typeof env[key] === "string") out[key] = env[key];
64
+ }
65
+ return out;
66
+ }
67
+
68
+ const alive = (pid) => {
69
+ try {
70
+ process.kill(pid, 0);
71
+ return true;
72
+ } catch (e) {
73
+ return e.code === "EPERM";
74
+ }
75
+ };
76
+
77
+ function psField(pid, field) {
78
+ const r = spawnSync("ps", ["-ww", "-o", `${field}=`, "-p", String(pid)], {
79
+ encoding: "utf8",
80
+ timeout: 5000,
81
+ });
82
+ return r.status === 0 ? r.stdout.trim() : "";
83
+ }
84
+
85
+ const pause = (ms) => new Promise((resolve) => globalThis.setTimeout(resolve, ms));
86
+
87
+ /** Whether `rec` names a live remote-listener.mjs process that started when the record says. */
88
+ export function isOurListener(rec) {
89
+ if (!rec || !Number.isInteger(rec.pid) || rec.pid <= 1 || !alive(rec.pid)) return false;
90
+ if (typeof rec.startedAt !== "string") return false;
91
+ if (!psField(rec.pid, "command").includes("remote-listener.mjs")) return false;
92
+ const began = Date.parse(psField(rec.pid, "lstart"));
93
+ const wrote = Date.parse(rec.startedAt);
94
+ if (!Number.isFinite(began) || !Number.isFinite(wrote)) return false;
95
+ return began <= wrote + 1000 && wrote - began <= START_SKEW_MS;
96
+ }
97
+
98
+ const readRecord = (env) => readRegularJson(listenerFile(env), null);
99
+
100
+ export function listenerStatus(env) {
101
+ const rec = readRecord(env);
102
+ const running = isOurListener(rec);
103
+ return { running, pid: running ? rec.pid : null, startedAt: running ? rec.startedAt : null };
104
+ }
105
+
106
+ /**
107
+ * Called by the listener process itself. Records this process as the
108
+ * instance unless another live listener already is one.
109
+ */
110
+ export function claimInstance(env) {
111
+ ensureDir(env);
112
+ return withFileLockSync(listenerFile(env), () => {
113
+ const rec = readRecord(env);
114
+ if (rec && rec.pid !== process.pid && isOurListener(rec)) return false;
115
+ writeFileSafe(
116
+ listenerFile(env),
117
+ `${JSON.stringify({ pid: process.pid, startedAt: new Date().toISOString() })}\n`,
118
+ { mode: 0o600 },
119
+ );
120
+ return true;
121
+ });
122
+ }
123
+
124
+ /** Removes the record when it still names this process. */
125
+ export function releaseInstance(env) {
126
+ const rec = readRecord(env);
127
+ if (rec && rec.pid === process.pid) rmSync(listenerFile(env), { force: true });
128
+ }
129
+
130
+ /** True while the record still names this process: `stop` and `--off` remove it. */
131
+ export const stillOwner = (env) => readRecord(env)?.pid === process.pid;
132
+
133
+ /** Starts the listener unless one is running. Resolves to { running, started }. */
134
+ export async function startListener(
135
+ env,
136
+ { script = LISTENER_SCRIPT, nodePath = process.execPath, readyMs = READY_MS } = {},
137
+ ) {
138
+ const current = listenerStatus(env);
139
+ if (current.running) return { running: true, started: false, pid: current.pid };
140
+ if (Object.keys(readDevices(env).devices).length === 0) {
141
+ return { running: false, started: false, pid: null };
142
+ }
143
+ ensureDir(env);
144
+ const child = spawn(nodePath, [script], {
145
+ env: listenerEnv(env),
146
+ detached: true,
147
+ stdio: "ignore",
148
+ });
149
+ child.unref();
150
+ const until = Date.now() + readyMs;
151
+ while (Date.now() < until) {
152
+ await pause(100);
153
+ const now = listenerStatus(env);
154
+ if (now.running) {
155
+ audit(env, { outcome: "listener-start" });
156
+ return { running: true, started: now.pid === child.pid, pid: now.pid };
157
+ }
158
+ }
159
+ return { running: false, started: false, pid: null };
160
+ }
161
+
162
+ /** Stops the listener this module started, if it is running. Resolves to { stopped }. */
163
+ export async function stopListener(env) {
164
+ const rec = readRecord(env);
165
+ let stopped = false;
166
+ if (isOurListener(rec)) {
167
+ try {
168
+ process.kill(rec.pid, "SIGTERM");
169
+ stopped = true;
170
+ } catch {
171
+ stopped = false;
172
+ }
173
+ const until = Date.now() + STOP_MS;
174
+ while (alive(rec.pid) && Date.now() < until) await pause(100);
175
+ if (alive(rec.pid) && isOurListener(rec)) {
176
+ try {
177
+ process.kill(rec.pid, "SIGKILL");
178
+ } catch {
179
+ /* gone between the check and the signal */
180
+ }
181
+ }
182
+ }
183
+ rmSync(listenerFile(env), { force: true });
184
+ if (stopped) audit(env, { outcome: "listener-stop" });
185
+ return { stopped };
186
+ }