@mmerterden/multi-agent-pipeline 23.3.0 → 23.5.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 (239) hide show
  1. package/CHANGELOG.md +73 -0
  2. package/README.md +27 -8
  3. package/README.tr.md +28 -9
  4. package/SECURITY.md +16 -0
  5. package/docs/adr/0008-installer-modularization-and-secret-leak-defense.md +1 -1
  6. package/docs/adr/0010-own-code-graph.md +299 -8
  7. package/docs/architecture.md +3 -3
  8. package/docs/ecosystem.md +10 -10
  9. package/docs/engineering.md +4 -4
  10. package/docs/facts.json +8 -8
  11. package/docs/features.md +5 -5
  12. package/docs/performance.md +17 -17
  13. package/install/_dev-only-files.mjs +9 -0
  14. package/install/_platform-filter.mjs +2 -55
  15. package/install/claude.mjs +28 -2
  16. package/install/codex.mjs +1 -3
  17. package/install/copilot.mjs +4 -8
  18. package/install/templates/claude-hooks.json +32 -1
  19. package/manifest.json +236 -167
  20. package/package.json +11 -3
  21. package/pipeline/commands/multi-agent/SKILL.md +1 -1
  22. package/pipeline/commands/multi-agent/design-check/SKILL.md +3 -2
  23. package/pipeline/commands/multi-agent/diff-explain/SKILL.md +3 -3
  24. package/pipeline/commands/multi-agent/graph/SKILL.md +57 -24
  25. package/pipeline/commands/multi-agent/pair/SKILL.md +92 -0
  26. package/pipeline/commands/multi-agent/prune-prompts/SKILL.md +1 -1
  27. package/pipeline/commands/multi-agent/search/SKILL.md +7 -1
  28. package/pipeline/commands/multi-agent/status/SKILL.md +4 -0
  29. package/pipeline/commands/multi-agent/sync/SKILL.md +3 -3
  30. package/pipeline/contract/CHANGELOG.md +63 -0
  31. package/pipeline/contract/README.md +1 -0
  32. package/pipeline/contract/build.mjs +13 -1
  33. package/pipeline/contract/fixtures/error-invalid-request.json +1 -1
  34. package/pipeline/contract/fixtures/error-unauthorized.json +1 -1
  35. package/pipeline/contract/fixtures/runs-awaiting-question.json +4 -1
  36. package/pipeline/contract/fixtures/runs-empty.json +1 -1
  37. package/pipeline/contract/fixtures/runs-failed.json +4 -1
  38. package/pipeline/contract/fixtures/runs-old-schema.json +3 -0
  39. package/pipeline/contract/fixtures/runs-pr-opened-redacted.json +4 -1
  40. package/pipeline/contract/fixtures/runs-pr-opened.json +4 -1
  41. package/pipeline/contract/fixtures/runs-running.json +4 -1
  42. package/pipeline/contract/manifest.json +41 -15
  43. package/pipeline/contract/types/index.d.ts +81 -3
  44. package/pipeline/lib/detach-self.mjs +95 -0
  45. package/pipeline/lib/public-mcp-servers.mjs +33 -0
  46. package/pipeline/lib/rotated-log.mjs +93 -0
  47. package/pipeline/lib/stack-detect.sh +1 -1
  48. package/pipeline/lib/tls-trust.mjs +29 -0
  49. package/pipeline/lib/usage-lifecycle.mjs +9 -11
  50. package/pipeline/lib/usage-names.generated.mjs +613 -0
  51. package/pipeline/lib/usage-run-key.mjs +235 -0
  52. package/pipeline/lib/usage-vocab.mjs +210 -0
  53. package/pipeline/multi-agent-refs/analysis/intake.md +2 -2
  54. package/pipeline/multi-agent-refs/analysis/render.md +1 -1
  55. package/pipeline/multi-agent-refs/channels/generator.md +4 -5
  56. package/pipeline/multi-agent-refs/cross-cli-contract.md +3 -3
  57. package/pipeline/multi-agent-refs/design-check/init-inventory.md +11 -1
  58. package/pipeline/multi-agent-refs/design-check/scope-and-ledger.md +1 -1
  59. package/pipeline/multi-agent-refs/features/code-graph.md +146 -11
  60. package/pipeline/multi-agent-refs/features/code-intelligence.md +16 -14
  61. package/pipeline/multi-agent-refs/features/dev-critic.md +7 -7
  62. package/pipeline/multi-agent-refs/features/model-fallback.md +6 -4
  63. package/pipeline/multi-agent-refs/features/remote-control.md +253 -0
  64. package/pipeline/multi-agent-refs/features/review-delta.md +1 -1
  65. package/pipeline/multi-agent-refs/features/review-file-set.md +3 -3
  66. package/pipeline/multi-agent-refs/features/review-multi-repo.md +1 -1
  67. package/pipeline/multi-agent-refs/features/session-brief.md +42 -0
  68. package/pipeline/multi-agent-refs/features/skill-conformance.md +3 -3
  69. package/pipeline/multi-agent-refs/features/usage-reporting.md +255 -27
  70. package/pipeline/multi-agent-refs/help/en.md +3 -2
  71. package/pipeline/multi-agent-refs/help/tr.md +3 -2
  72. package/pipeline/multi-agent-refs/knowledge.md +1 -1
  73. package/pipeline/multi-agent-refs/orchestrator/dispatcher.md +2 -2
  74. package/pipeline/multi-agent-refs/phases/operations.md +2 -2
  75. package/pipeline/multi-agent-refs/phases/phase-0-init.md +13 -12
  76. package/pipeline/multi-agent-refs/phases/phase-1-plan.md +4 -4
  77. package/pipeline/multi-agent-refs/phases/phase-3-review.md +2 -0
  78. package/pipeline/multi-agent-refs/phases/phase-5-report.md +1 -1
  79. package/pipeline/multi-agent-refs/platform-parity.md +2 -2
  80. package/pipeline/multi-agent-refs/wiki-capture.md +3 -17
  81. package/pipeline/office/index.html +1309 -236
  82. package/pipeline/office/toolkit.json +1 -1
  83. package/pipeline/rules/outside-the-pipeline.md +1 -1
  84. package/pipeline/schemas/activity.schema.json +23 -0
  85. package/pipeline/schemas/agent-state.schema.json +6 -1
  86. package/pipeline/schemas/code-graph-calls.schema.json +254 -0
  87. package/pipeline/schemas/code-graph-docs.schema.json +223 -0
  88. package/pipeline/schemas/code-graph-infra.schema.json +227 -0
  89. package/pipeline/schemas/code-graph.schema.json +2 -2
  90. package/pipeline/schemas/examples/design-check-config.json +27 -0
  91. package/pipeline/schemas/learning-curve.schema.json +67 -0
  92. package/pipeline/schemas/mcp-health.schema.json +96 -0
  93. package/pipeline/schemas/office-jobs.json +69 -2
  94. package/pipeline/schemas/office-jobs.schema.json +8 -1
  95. package/pipeline/schemas/phases.json +5 -0
  96. package/pipeline/schemas/phases.schema.json +8 -0
  97. package/pipeline/schemas/prefs.schema.json +46 -12
  98. package/pipeline/schemas/runs-index.schema.json +17 -0
  99. package/pipeline/schemas/toolkit-path-params.json +78 -8
  100. package/pipeline/scripts/README.md +1 -0
  101. package/pipeline/scripts/_code-graph.mjs +184 -103
  102. package/pipeline/scripts/_contract-core.mjs +1 -1
  103. package/pipeline/scripts/_contract-routes-office.mjs +33 -0
  104. package/pipeline/scripts/_diff-impact.mjs +21 -2
  105. package/pipeline/scripts/_graph-sidecars.mjs +372 -0
  106. package/pipeline/scripts/_http-post.mjs +103 -115
  107. package/pipeline/scripts/_safe-read.mjs +57 -0
  108. package/pipeline/scripts/_skill-practices.mjs +26 -0
  109. package/pipeline/scripts/_strip-code.mjs +380 -0
  110. package/pipeline/scripts/activity-snapshot.mjs +13 -1
  111. package/pipeline/scripts/aggregate-metrics.mjs +3 -5
  112. package/pipeline/scripts/build-stack-plugins.mjs +1 -47
  113. package/pipeline/scripts/call-graph/index.mjs +78 -0
  114. package/pipeline/scripts/call-graph/lang/cpp.mjs +308 -0
  115. package/pipeline/scripts/call-graph/lang/csharp.mjs +130 -0
  116. package/pipeline/scripts/call-graph/lang/go.mjs +303 -0
  117. package/pipeline/scripts/call-graph/lang/java.mjs +370 -0
  118. package/pipeline/scripts/call-graph/lang/kotlin.mjs +397 -0
  119. package/pipeline/scripts/call-graph/lang/python.mjs +399 -0
  120. package/pipeline/scripts/call-graph/lang/rust.mjs +345 -0
  121. package/pipeline/scripts/call-graph/lang/shared.mjs +230 -0
  122. package/pipeline/scripts/call-graph/lang/swift.mjs +432 -0
  123. package/pipeline/scripts/call-graph/lang/typescript.mjs +692 -0
  124. package/pipeline/scripts/call-graph/lex.mjs +396 -0
  125. package/pipeline/scripts/call-graph/platform.mjs +86 -0
  126. package/pipeline/scripts/call-graph/profiles.mjs +89 -0
  127. package/pipeline/scripts/call-graph/resolve.mjs +1125 -0
  128. package/pipeline/scripts/call-graph/scan.mjs +267 -0
  129. package/pipeline/scripts/code-graph-rules/android.json +7 -2
  130. package/pipeline/scripts/code-graph-rules/cpp.json +99 -0
  131. package/pipeline/scripts/code-graph-rules/csharp.json +102 -0
  132. package/pipeline/scripts/code-graph-rules/go.json +2 -1
  133. package/pipeline/scripts/code-graph-rules/ios.json +3 -1
  134. package/pipeline/scripts/code-graph-rules/java.json +76 -0
  135. package/pipeline/scripts/code-graph-rules/node.json +7 -2
  136. package/pipeline/scripts/code-graph-rules/python.json +6 -2
  137. package/pipeline/scripts/code-graph-rules/rust.json +105 -0
  138. package/pipeline/scripts/contract-server.mjs +3 -0
  139. package/pipeline/scripts/design-check-config.mjs +205 -0
  140. package/pipeline/scripts/feedback-send.mjs +26 -26
  141. package/pipeline/scripts/gate-ledger.mjs +2 -1
  142. package/pipeline/scripts/gen-facts.mjs +1 -2
  143. package/pipeline/scripts/gen-usage-names.mjs +124 -0
  144. package/pipeline/scripts/graph-affected.mjs +109 -20
  145. package/pipeline/scripts/graph-build.mjs +95 -15
  146. package/pipeline/scripts/graph-export.mjs +272 -0
  147. package/pipeline/scripts/graph-hint.mjs +15 -2
  148. package/pipeline/scripts/graph-query.mjs +305 -26
  149. package/pipeline/scripts/graph-report.mjs +187 -1
  150. package/pipeline/scripts/health-report.mjs +3 -4
  151. package/pipeline/scripts/infra/docs.mjs +317 -0
  152. package/pipeline/scripts/infra/extract.mjs +998 -0
  153. package/pipeline/scripts/infra/graph.mjs +245 -0
  154. package/pipeline/scripts/infra/yaml-lite.mjs +311 -0
  155. package/pipeline/scripts/job-launch.mjs +67 -2
  156. package/pipeline/scripts/learning-curve.mjs +288 -178
  157. package/pipeline/scripts/log-metric.sh +10 -1
  158. package/pipeline/scripts/mcp-health.mjs +309 -0
  159. package/pipeline/scripts/note-agent-event.mjs +3 -4
  160. package/pipeline/scripts/note-command-use.mjs +333 -0
  161. package/pipeline/scripts/note-command-use.sh +126 -0
  162. package/pipeline/scripts/note-mcp-call.sh +89 -0
  163. package/pipeline/scripts/note-mcp-failure.mjs +272 -1
  164. package/pipeline/scripts/note-session.sh +62 -3
  165. package/pipeline/scripts/note-skill-use.mjs +58 -2
  166. package/pipeline/scripts/office-build.mjs +115 -1
  167. package/pipeline/scripts/office-memory.mjs +14 -5
  168. package/pipeline/scripts/pair.mjs +333 -0
  169. package/pipeline/scripts/pre-push-check.sh +1 -1
  170. package/pipeline/scripts/remote/cbor.mjs +128 -0
  171. package/pipeline/scripts/remote/contract.mjs +98 -0
  172. package/pipeline/scripts/remote/handler.mjs +330 -0
  173. package/pipeline/scripts/remote/handles.mjs +57 -0
  174. package/pipeline/scripts/remote/lifecycle.mjs +186 -0
  175. package/pipeline/scripts/remote/listener.mjs +204 -0
  176. package/pipeline/scripts/remote/lockout.mjs +103 -0
  177. package/pipeline/scripts/remote/nonces.mjs +61 -0
  178. package/pipeline/scripts/remote/pairing.mjs +519 -0
  179. package/pipeline/scripts/remote/qr-encode.mjs +459 -0
  180. package/pipeline/scripts/remote/store.mjs +191 -0
  181. package/pipeline/scripts/remote/transport.mjs +211 -0
  182. package/pipeline/scripts/remote/verbs.json +70 -0
  183. package/pipeline/scripts/remote/verbs.mjs +217 -0
  184. package/pipeline/scripts/remote/webauthn.mjs +169 -0
  185. package/pipeline/scripts/remote/wire.mjs +364 -0
  186. package/pipeline/scripts/remote-listener.mjs +83 -0
  187. package/pipeline/scripts/route-learn.mjs +4 -4
  188. package/pipeline/scripts/run-kill.mjs +1 -1
  189. package/pipeline/scripts/run-write.mjs +13 -2
  190. package/pipeline/scripts/runs-index.mjs +30 -3
  191. package/pipeline/scripts/search-logs.sh +9 -0
  192. package/pipeline/scripts/session-brief.mjs +458 -0
  193. package/pipeline/scripts/session-brief.sh +130 -0
  194. package/pipeline/scripts/skill-usage.mjs +16 -5
  195. package/pipeline/scripts/test-gap-rules/cpp.json +25 -0
  196. package/pipeline/scripts/test-gap-rules/csharp.json +20 -0
  197. package/pipeline/scripts/test-gap-rules/java.json +20 -0
  198. package/pipeline/scripts/test-gap-rules/rust.json +14 -0
  199. package/pipeline/scripts/token-budget-report.mjs +3 -2
  200. package/pipeline/scripts/uninstall.mjs +29 -0
  201. package/pipeline/scripts/usage-access.mjs +16 -31
  202. package/pipeline/scripts/usage-health.mjs +31 -62
  203. package/pipeline/scripts/usage-register-beacon.mjs +11 -22
  204. package/pipeline/scripts/usage-register.mjs +39 -29
  205. package/pipeline/scripts/usage-report.mjs +579 -178
  206. package/pipeline/scripts/validate-code-graph.mjs +361 -111
  207. package/pipeline/scripts/write-state.mjs +39 -0
  208. package/pipeline/skills/.skill-manifest.json +21 -17
  209. package/pipeline/skills/.skills-index.json +13 -2
  210. package/pipeline/skills/shared/README.md +5 -4
  211. package/pipeline/skills/shared/core/multi-agent-design-check/SKILL.md +1 -1
  212. package/pipeline/skills/shared/core/multi-agent-diff-explain/SKILL.md +3 -3
  213. package/pipeline/skills/shared/core/multi-agent-graph/SKILL.md +55 -21
  214. package/pipeline/skills/shared/core/multi-agent-pair/SKILL.md +41 -0
  215. package/pipeline/skills/shared/core/multi-agent-prune-prompts/SKILL.md +1 -1
  216. package/pipeline/skills/shared/core/multi-agent-sync/SKILL.md +3 -3
  217. package/pipeline/skills/shared/external/app-store-optimization/SKILL.md +2 -3
  218. package/pipeline/skills/shared/external/app-store-optimization/references/keyword-research-methodology.md +2 -2
  219. package/pipeline/skills/shared/external/app-store-optimization/references/product-page-variants.md +2 -2
  220. package/pipeline/skills/shared/external/app-store-review/SKILL.md +11 -4
  221. package/pipeline/skills/shared/external/build-settings-audit/SKILL.md +1 -1
  222. package/pipeline/skills/shared/external/build-time-benchmark/SKILL.md +5 -5
  223. package/pipeline/skills/shared/external/build-time-fixes/SKILL.md +5 -5
  224. package/pipeline/skills/shared/external/build-time-optimizer/SKILL.md +6 -6
  225. package/pipeline/skills/shared/external/free-llm-apis/references/providers.md +1 -0
  226. package/pipeline/skills/shared/external/ios-coding-standard/references/STANDARD.md +2 -2
  227. package/pipeline/skills/shared/external/ios-haptics/references/core-haptics.md +1 -1
  228. package/pipeline/skills/shared/external/localization-reuse-map/references/publish-and-snapshot.md +1 -1
  229. package/pipeline/skills/shared/external/package-build-audit/SKILL.md +3 -3
  230. package/pipeline/skills/shared/external/reverse-engineer-own-app/SKILL.md +2 -3
  231. package/pipeline/skills/shared/external/swift-compile-hotspots/SKILL.md +2 -2
  232. package/pipeline/skills/shared/external/weatherkit/SKILL.md +5 -6
  233. package/pipeline/skills/skills-index.md +3 -2
  234. package/docs/FIGMA_PIPELINE.md +0 -137
  235. package/pipeline/lib/identifier-scan.mjs +0 -156
  236. package/pipeline/scripts/_renamed-skills.mjs +0 -164
  237. package/pipeline/scripts/publish-staged.mjs +0 -324
  238. package/pipeline/skills/renamed.json +0 -30
  239. package/pipeline/skills/shared/external/ios-coding-standard/scripts/check_structure.py +0 -765
@@ -0,0 +1,98 @@
1
+ /**
2
+ * contract.mjs - the fixed verb contract shared with the phone, and the
3
+ * argument validation every verb passes before anything runs.
4
+ *
5
+ * verbs.json is the shared contract: it holds the contract version, the
6
+ * active phase and, per verb, its phase, whether it mutates, whether it
7
+ * targets a run and an argument schema. A verb exists only if it is in the
8
+ * file and its phase is at or below the phase this computer implements
9
+ * (IMPLEMENTED_PHASE), whatever the file says is active: the site cannot
10
+ * raise it.
11
+ *
12
+ * @module pipeline/scripts/remote/contract
13
+ */
14
+
15
+ import { readFileSync } from "node:fs";
16
+
17
+ export const CONTRACT = JSON.parse(readFileSync(new URL("./verbs.json", import.meta.url), "utf8"));
18
+
19
+ /** The highest verb phase this implementation executes. */
20
+ export const IMPLEMENTED_PHASE = 1;
21
+
22
+ const VERB_NAME = /^[a-z][a-z0-9_]{0,31}$/;
23
+
24
+ /**
25
+ * The verb's spec when it is a contract verb whose phase is at or below both
26
+ * the contract's active phase and the implemented phase, else null.
27
+ */
28
+ export function verbSpec(name, contract = CONTRACT) {
29
+ if (typeof name !== "string" || !VERB_NAME.test(name)) return null;
30
+ if (!Object.prototype.hasOwnProperty.call(contract.verbs, name)) return null;
31
+ const spec = contract.verbs[name];
32
+ if (spec.phase > contract.activePhase || spec.phase > IMPLEMENTED_PHASE) return null;
33
+ return spec;
34
+ }
35
+
36
+ /**
37
+ * Checks an argument object against a verb's schema. Unknown keys, wrong
38
+ * types and out-of-range values are refused; defaults are filled in.
39
+ *
40
+ * @returns {{ok: true, args: Record<string, string|number>} | {ok: false, error: string}}
41
+ */
42
+ export function validateArgs(spec, input) {
43
+ if (!input || typeof input !== "object" || Array.isArray(input)) {
44
+ return { ok: false, error: "args" };
45
+ }
46
+ for (const key of Object.keys(input)) {
47
+ if (!Object.prototype.hasOwnProperty.call(spec.args, key)) {
48
+ return { ok: false, error: `unknown:${key}` };
49
+ }
50
+ }
51
+ const out = {};
52
+ for (const [key, arg] of Object.entries(spec.args)) {
53
+ const value = input[key];
54
+ if (value === undefined) {
55
+ if (arg.required) return { ok: false, error: `missing:${key}` };
56
+ if (arg.default !== undefined) out[key] = arg.default;
57
+ continue;
58
+ }
59
+ if (arg.type === "string") {
60
+ if (typeof value !== "string" || value.length === 0)
61
+ return { ok: false, error: `type:${key}` };
62
+ if (arg.maxLength !== undefined && value.length > arg.maxLength) {
63
+ return { ok: false, error: `length:${key}` };
64
+ }
65
+ if (arg.pattern && !new RegExp(arg.pattern).test(value)) {
66
+ return { ok: false, error: `pattern:${key}` };
67
+ }
68
+ } else if (arg.type === "idlist") {
69
+ if (!Array.isArray(value) || value.length < arg.minItems || value.length > arg.maxItems) {
70
+ return { ok: false, error: `length:${key}` };
71
+ }
72
+ const pattern = new RegExp(arg.pattern);
73
+ if (!value.every((item) => typeof item === "string" && pattern.test(item))) {
74
+ return { ok: false, error: `pattern:${key}` };
75
+ }
76
+ if (new Set(value).size !== value.length) return { ok: false, error: `duplicate:${key}` };
77
+ out[key] = [...value];
78
+ continue;
79
+ } else if (arg.type === "integer") {
80
+ if (
81
+ typeof value !== "number" ||
82
+ !Number.isInteger(value) ||
83
+ value < arg.min ||
84
+ value > arg.max
85
+ ) {
86
+ return { ok: false, error: `range:${key}` };
87
+ }
88
+ } else if (arg.type === "enum") {
89
+ if (typeof value !== "string" || !arg.values.includes(value)) {
90
+ return { ok: false, error: `enum:${key}` };
91
+ }
92
+ } else {
93
+ return { ok: false, error: `schema:${key}` };
94
+ }
95
+ out[key] = value;
96
+ }
97
+ return { ok: true, args: out };
98
+ }
@@ -0,0 +1,330 @@
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
+ run: issuedHandle(ctx.executor, req.deviceId, answer.run),
252
+ outcome: answer.payload.ok ? "ok" : "refused",
253
+ reason: answer.payload.ok ? (gap ? "gap" : "") : answer.payload.error,
254
+ });
255
+ return {
256
+ reply,
257
+ outcome: answer.payload.ok ? "ok" : "refused",
258
+ reason: answer.payload.error ?? "",
259
+ };
260
+ } catch (err) {
261
+ if (!(err instanceof Drop)) throw err;
262
+ audit(env, {
263
+ device: auditDevice,
264
+ verb: auditVerb,
265
+ outcome: "dropped",
266
+ reason: dropCode(err.reason),
267
+ });
268
+ return { reply: null, outcome: "dropped", reason: err.reason };
269
+ }
270
+ }
271
+
272
+ /**
273
+ * The run value of a verb for the audit line: only a handle this device was
274
+ * given by the executor's table, never a raw run id or anything else the
275
+ * phone sent.
276
+ */
277
+ function issuedHandle(executor, deviceId, handle) {
278
+ if (typeof handle !== "string" || !executor?.handles) return "";
279
+ return executor.handles.resolve(deviceId, handle) === null ? "" : handle;
280
+ }
281
+
282
+ const dropCode = (reason) =>
283
+ String(reason)
284
+ .toLowerCase()
285
+ .replace(/[^a-z0-9:_-]/g, "-")
286
+ .slice(0, 40);
287
+
288
+ async function decide(req, device, payload, ctx, now) {
289
+ const isObject = payload && typeof payload === "object" && !Array.isArray(payload);
290
+ if (!isObject || payload.v !== WIRE_VERSION || payload.verb !== req.verb) {
291
+ return { payload: refusal("verb") };
292
+ }
293
+ const spec = verbSpec(payload.verb);
294
+ if (!spec) {
295
+ const known = Object.prototype.hasOwnProperty.call(CONTRACT.verbs, payload.verb);
296
+ return { payload: refusal(known ? "phase" : "verb") };
297
+ }
298
+ const allowedKeys = ["v", "verb", "args", "iat"];
299
+ if (!Object.keys(payload).every((k) => allowedKeys.includes(k))) {
300
+ return { payload: refusal("args") };
301
+ }
302
+ const checked = validateArgs(spec, payload.args === undefined ? {} : payload.args);
303
+ if (!checked.ok) return { payload: refusal("args") };
304
+ if (!Number.isFinite(payload.iat) || Math.abs(now() - payload.iat) > IAT_WINDOW_MS) {
305
+ return { payload: refusal("iat") };
306
+ }
307
+
308
+ let run = "";
309
+ if (spec.target === "run") {
310
+ const tag = runTag(b64uDecode(device.keys.tag), checked.args.run);
311
+ if (!equalBytes(Buffer.from(tag), Buffer.from(req.runTag)))
312
+ return { payload: refusal("run_tag") };
313
+ run = checked.args.run;
314
+ } else if (req.runTag !== "") {
315
+ return { payload: refusal("run_tag") };
316
+ }
317
+
318
+ if (spec.mutating && ctx.unattended()) return { payload: refusal("unattended"), run };
319
+
320
+ const execute = ctx.executor[payload.verb];
321
+ if (typeof execute !== "function") return { payload: refusal("phase"), run };
322
+ try {
323
+ const result = await execute(checked.args, { deviceId: req.deviceId });
324
+ return { payload: { v: WIRE_VERSION, ok: true, result }, run };
325
+ } catch (err) {
326
+ const code =
327
+ typeof err?.code === "string" && /^[a-z_]{1,32}$/.test(err.code) ? err.code : "internal";
328
+ return { payload: refusal(code), run };
329
+ }
330
+ }
@@ -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
+ }