kimi-plugin-cc 3.0.0 → 3.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.
Files changed (281) hide show
  1. package/.claude-plugin/marketplace.json +2 -2
  2. package/.claude-plugin/plugin.json +3 -14
  3. package/README.md +428 -572
  4. package/assets/logo.svg +6 -0
  5. package/cordis.patch.yml +18 -0
  6. package/dist/background-spawn.js +4 -2
  7. package/dist/cli-client.js +105 -66
  8. package/dist/commands/ask.js +27 -12
  9. package/dist/commands/cancel.js +4 -13
  10. package/dist/commands/cli-helpers.js +1 -1
  11. package/dist/commands/pursue.js +3 -2
  12. package/dist/commands/registry.js +7 -26
  13. package/dist/commands/repair-sessions.js +7 -4
  14. package/dist/commands/replay.js +4 -3
  15. package/dist/commands/rescue.js +17 -5
  16. package/dist/commands/review.js +18 -5
  17. package/dist/commands/setup.js +277 -262
  18. package/dist/commands/swarm.js +20 -7
  19. package/dist/companion.js +142 -18
  20. package/dist/help.js +11 -7
  21. package/dist/hook-escape.js +7 -16
  22. package/dist/hooks/approval-hook.js +1762 -124
  23. package/dist/hooks/approval-policy.js +15 -10
  24. package/dist/hooks/config-safety.js +15 -24
  25. package/dist/hooks/hook-timing.js +1 -1
  26. package/dist/hooks/install-paths.js +179 -107
  27. package/dist/hooks/install.js +44 -166
  28. package/dist/hooks/managed-block.js +44 -95
  29. package/dist/job-store.js +117 -49
  30. package/dist/jobs.js +53 -1
  31. package/dist/kimi-engine.js +68 -92
  32. package/dist/kimi-errors.js +1 -1
  33. package/dist/kimi-journal.js +3 -2
  34. package/dist/kimi-releases.js +28 -49
  35. package/dist/kimi-timeouts.js +1 -15
  36. package/dist/kimi-version-probe.js +24 -72
  37. package/dist/logging.js +12 -7
  38. package/dist/mcp/binding.js +13 -4
  39. package/dist/mcp/job-control.js +386 -89
  40. package/dist/mcp/launcher.js +1 -1
  41. package/dist/mcp/operations.js +387 -193
  42. package/dist/mcp/protocol.js +116 -27
  43. package/dist/mcp/skills.js +130 -0
  44. package/dist/mcp/stdio.js +15 -2
  45. package/dist/native-v2-preflight.js +127 -35
  46. package/dist/parsing.js +45 -11
  47. package/dist/paths.js +20 -10
  48. package/dist/plugin-data.js +28 -83
  49. package/dist/read-scope.js +2 -2
  50. package/dist/render.js +13 -38
  51. package/dist/session-references.js +216 -0
  52. package/dist/session-title.js +1 -1
  53. package/dist/surface-routing.js +92 -5
  54. package/dist/swarm-activation.js +26 -137
  55. package/dist/version.js +1 -1
  56. package/docs/migration.md +45 -227
  57. package/docs/models.md +24 -66
  58. package/docs/safety.md +195 -400
  59. package/docs/session-visibility.md +24 -14
  60. package/docs/swarm-recovery.md +26 -20
  61. package/dsh/index.json +54 -0
  62. package/mcp_config.json +10 -0
  63. package/package.json +23 -82
  64. package/plugin.json +19 -0
  65. package/plugins/kimi-codex/.codex-plugin/plugin.json +7 -7
  66. package/plugins/kimi-codex/.mcp.json +2 -3
  67. package/plugins/kimi-codex/dist/background-spawn.js +4 -2
  68. package/plugins/kimi-codex/dist/cli-client.js +105 -66
  69. package/plugins/kimi-codex/dist/commands/ask.js +27 -12
  70. package/plugins/kimi-codex/dist/commands/cancel.js +4 -13
  71. package/plugins/kimi-codex/dist/commands/cli-helpers.js +1 -1
  72. package/plugins/kimi-codex/dist/commands/pursue.js +3 -2
  73. package/plugins/kimi-codex/dist/commands/registry.js +7 -26
  74. package/plugins/kimi-codex/dist/commands/repair-sessions.js +7 -4
  75. package/plugins/kimi-codex/dist/commands/replay.js +4 -3
  76. package/plugins/kimi-codex/dist/commands/rescue.js +17 -5
  77. package/plugins/kimi-codex/dist/commands/review.js +18 -5
  78. package/plugins/kimi-codex/dist/commands/setup.js +277 -262
  79. package/plugins/kimi-codex/dist/commands/swarm.js +20 -7
  80. package/plugins/kimi-codex/dist/companion.js +142 -18
  81. package/plugins/kimi-codex/dist/help.js +11 -7
  82. package/plugins/kimi-codex/dist/hook-escape.js +7 -16
  83. package/plugins/kimi-codex/dist/hooks/approval-hook.js +1762 -124
  84. package/plugins/kimi-codex/dist/hooks/approval-policy.js +15 -10
  85. package/plugins/kimi-codex/dist/hooks/config-safety.js +15 -24
  86. package/plugins/kimi-codex/dist/hooks/hook-timing.js +1 -1
  87. package/plugins/kimi-codex/dist/hooks/install-paths.js +179 -107
  88. package/plugins/kimi-codex/dist/hooks/install.js +44 -166
  89. package/plugins/kimi-codex/dist/hooks/managed-block.js +44 -95
  90. package/plugins/kimi-codex/dist/job-store.js +117 -49
  91. package/plugins/kimi-codex/dist/jobs.js +53 -1
  92. package/plugins/kimi-codex/dist/kimi-engine.js +68 -92
  93. package/plugins/kimi-codex/dist/kimi-errors.js +1 -1
  94. package/plugins/kimi-codex/dist/kimi-journal.js +3 -2
  95. package/plugins/kimi-codex/dist/kimi-releases.js +28 -49
  96. package/plugins/kimi-codex/dist/kimi-timeouts.js +1 -15
  97. package/plugins/kimi-codex/dist/kimi-version-probe.js +24 -72
  98. package/plugins/kimi-codex/dist/logging.js +12 -7
  99. package/plugins/kimi-codex/dist/mcp/binding.js +13 -4
  100. package/plugins/kimi-codex/dist/mcp/job-control.js +386 -89
  101. package/plugins/kimi-codex/dist/mcp/launcher.js +1 -1
  102. package/plugins/kimi-codex/dist/mcp/operations.js +387 -193
  103. package/plugins/kimi-codex/dist/mcp/protocol.js +116 -27
  104. package/plugins/kimi-codex/dist/mcp/skills.js +130 -0
  105. package/plugins/kimi-codex/dist/mcp/stdio.js +15 -2
  106. package/plugins/kimi-codex/dist/native-v2-preflight.js +127 -35
  107. package/plugins/kimi-codex/dist/parsing.js +45 -11
  108. package/plugins/kimi-codex/dist/paths.js +20 -10
  109. package/plugins/kimi-codex/dist/plugin-data.js +28 -83
  110. package/plugins/kimi-codex/dist/read-scope.js +2 -2
  111. package/plugins/kimi-codex/dist/render.js +13 -38
  112. package/plugins/kimi-codex/dist/session-references.js +216 -0
  113. package/plugins/kimi-codex/dist/session-title.js +1 -1
  114. package/plugins/kimi-codex/dist/surface-routing.js +92 -5
  115. package/plugins/kimi-codex/dist/swarm-activation.js +26 -137
  116. package/plugins/kimi-codex/dist/version.js +1 -1
  117. package/plugins/kimi-codex/scripts/companion.sh +4 -15
  118. package/plugins/kimi-codex/skills/kimi/SKILL.md +77 -0
  119. package/plugins/kimi-codex/skills/kimi/agents/openai.yaml +6 -0
  120. package/scripts/companion.sh +4 -15
  121. package/skills/kimi/SKILL.md +77 -0
  122. package/skills/kimi/agents/openai.yaml +6 -0
  123. package/CHANGELOG.md +0 -1402
  124. package/agents/kimi-pursue.md +0 -93
  125. package/agents/kimi-review.md +0 -86
  126. package/agents/kimi-swarm.md +0 -88
  127. package/agents/kimi-task.md +0 -93
  128. package/commands/README.md +0 -14
  129. package/commands/cancel.md +0 -17
  130. package/commands/pursue.md +0 -41
  131. package/commands/replay.md +0 -13
  132. package/commands/result.md +0 -13
  133. package/commands/review.md +0 -40
  134. package/commands/setup.md +0 -25
  135. package/commands/status.md +0 -13
  136. package/commands/swarm.md +0 -45
  137. package/commands/task.md +0 -40
  138. package/dist/commands/review-gate.js +0 -391
  139. package/dist/config.js +0 -22
  140. package/dist/dsh/companion.js +0 -177
  141. package/dist/dsh/index.js +0 -167
  142. package/dist/hooks/review-gate-stop.js +0 -19
  143. package/dist/schemas/review-gate-output.js +0 -41
  144. package/docs/registry-releases.md +0 -228
  145. package/docs/upstream-2.4.1-certification.md +0 -54
  146. package/docs/upstream-2.5.0-certification.md +0 -52
  147. package/docs/upstream-2.5.1-certification.md +0 -47
  148. package/docs/upstream-2.5.2-certification.md +0 -40
  149. package/docs/upstream-2.5.3-certification.md +0 -73
  150. package/docs/upstream-2.6.0-certification.md +0 -65
  151. package/docs/upstream-2.6.2-certification.md +0 -144
  152. package/docs/upstream-2.6.3-certification.md +0 -100
  153. package/docs/upstream-2.7.2-certification.md +0 -113
  154. package/docs/upstream-2.7.3-certification.md +0 -95
  155. package/docs/windows-validation.md +0 -39
  156. package/hooks/README.md +0 -9
  157. package/hooks/hooks.json +0 -16
  158. package/plugins/kimi-codex/dist/commands/review-gate.js +0 -391
  159. package/plugins/kimi-codex/dist/config.js +0 -22
  160. package/plugins/kimi-codex/dist/dsh/companion.js +0 -177
  161. package/plugins/kimi-codex/dist/dsh/index.js +0 -167
  162. package/plugins/kimi-codex/dist/hooks/review-gate-stop.js +0 -19
  163. package/plugins/kimi-codex/dist/schemas/review-gate-output.js +0 -41
  164. package/plugins/kimi-codex/scripts/review-gate-hook.sh +0 -32
  165. package/plugins/kimi-codex/skills/kimi-cancel/SKILL.md +0 -25
  166. package/plugins/kimi-codex/skills/kimi-cancel/agents/openai.yaml +0 -6
  167. package/plugins/kimi-codex/skills/kimi-pursue/SKILL.md +0 -32
  168. package/plugins/kimi-codex/skills/kimi-pursue/agents/openai.yaml +0 -6
  169. package/plugins/kimi-codex/skills/kimi-replay/SKILL.md +0 -25
  170. package/plugins/kimi-codex/skills/kimi-replay/agents/openai.yaml +0 -6
  171. package/plugins/kimi-codex/skills/kimi-result/SKILL.md +0 -25
  172. package/plugins/kimi-codex/skills/kimi-result/agents/openai.yaml +0 -6
  173. package/plugins/kimi-codex/skills/kimi-review/SKILL.md +0 -35
  174. package/plugins/kimi-codex/skills/kimi-review/agents/openai.yaml +0 -6
  175. package/plugins/kimi-codex/skills/kimi-setup/SKILL.md +0 -35
  176. package/plugins/kimi-codex/skills/kimi-setup/agents/openai.yaml +0 -6
  177. package/plugins/kimi-codex/skills/kimi-status/SKILL.md +0 -25
  178. package/plugins/kimi-codex/skills/kimi-status/agents/openai.yaml +0 -6
  179. package/plugins/kimi-codex/skills/kimi-swarm/SKILL.md +0 -37
  180. package/plugins/kimi-codex/skills/kimi-swarm/agents/openai.yaml +0 -6
  181. package/plugins/kimi-codex/skills/kimi-task/SKILL.md +0 -37
  182. package/plugins/kimi-codex/skills/kimi-task/agents/openai.yaml +0 -6
  183. package/plugins/kimi-dsh/LICENSE +0 -201
  184. package/plugins/kimi-dsh/README.md +0 -84
  185. package/plugins/kimi-dsh/cordis.patch.yml +0 -45
  186. package/plugins/kimi-dsh/dist/background-spawn.js +0 -209
  187. package/plugins/kimi-dsh/dist/cli-cancellation.js +0 -43
  188. package/plugins/kimi-dsh/dist/cli-client.js +0 -1097
  189. package/plugins/kimi-dsh/dist/commands/ask.js +0 -269
  190. package/plugins/kimi-dsh/dist/commands/cancel.js +0 -177
  191. package/plugins/kimi-dsh/dist/commands/cli-helpers.js +0 -302
  192. package/plugins/kimi-dsh/dist/commands/models.js +0 -139
  193. package/plugins/kimi-dsh/dist/commands/pursue.js +0 -293
  194. package/plugins/kimi-dsh/dist/commands/recover-swarm.js +0 -140
  195. package/plugins/kimi-dsh/dist/commands/registry.js +0 -74
  196. package/plugins/kimi-dsh/dist/commands/repair-sessions.js +0 -266
  197. package/plugins/kimi-dsh/dist/commands/replay.js +0 -124
  198. package/plugins/kimi-dsh/dist/commands/rescue.js +0 -277
  199. package/plugins/kimi-dsh/dist/commands/result.js +0 -72
  200. package/plugins/kimi-dsh/dist/commands/review-gate.js +0 -391
  201. package/plugins/kimi-dsh/dist/commands/review.js +0 -217
  202. package/plugins/kimi-dsh/dist/commands/setup.js +0 -1465
  203. package/plugins/kimi-dsh/dist/commands/status.js +0 -27
  204. package/plugins/kimi-dsh/dist/commands/swarm.js +0 -823
  205. package/plugins/kimi-dsh/dist/commands/worker.js +0 -24
  206. package/plugins/kimi-dsh/dist/companion.js +0 -99
  207. package/plugins/kimi-dsh/dist/config.js +0 -22
  208. package/plugins/kimi-dsh/dist/dsh/companion.js +0 -177
  209. package/plugins/kimi-dsh/dist/dsh/index.js +0 -167
  210. package/plugins/kimi-dsh/dist/errors.js +0 -40
  211. package/plugins/kimi-dsh/dist/git.js +0 -216
  212. package/plugins/kimi-dsh/dist/help.js +0 -43
  213. package/plugins/kimi-dsh/dist/hook-escape.js +0 -71
  214. package/plugins/kimi-dsh/dist/hooks/approval-hook.js +0 -145
  215. package/plugins/kimi-dsh/dist/hooks/approval-policy.js +0 -295
  216. package/plugins/kimi-dsh/dist/hooks/config-safety.js +0 -641
  217. package/plugins/kimi-dsh/dist/hooks/hook-timing.js +0 -48
  218. package/plugins/kimi-dsh/dist/hooks/install-paths.js +0 -428
  219. package/plugins/kimi-dsh/dist/hooks/install.js +0 -405
  220. package/plugins/kimi-dsh/dist/hooks/managed-block.js +0 -729
  221. package/plugins/kimi-dsh/dist/hooks/review-gate-stop.js +0 -19
  222. package/plugins/kimi-dsh/dist/job-id.js +0 -12
  223. package/plugins/kimi-dsh/dist/job-store.js +0 -631
  224. package/plugins/kimi-dsh/dist/jobs.js +0 -212
  225. package/plugins/kimi-dsh/dist/kimi-command.js +0 -144
  226. package/plugins/kimi-dsh/dist/kimi-engine.js +0 -770
  227. package/plugins/kimi-dsh/dist/kimi-errors.js +0 -205
  228. package/plugins/kimi-dsh/dist/kimi-home.js +0 -15
  229. package/plugins/kimi-dsh/dist/kimi-journal.js +0 -41
  230. package/plugins/kimi-dsh/dist/kimi-releases.js +0 -144
  231. package/plugins/kimi-dsh/dist/kimi-timeouts.js +0 -52
  232. package/plugins/kimi-dsh/dist/kimi-version-probe.js +0 -198
  233. package/plugins/kimi-dsh/dist/logging.js +0 -22
  234. package/plugins/kimi-dsh/dist/mcp/binding.js +0 -58
  235. package/plugins/kimi-dsh/dist/mcp/job-control.js +0 -343
  236. package/plugins/kimi-dsh/dist/mcp/launcher.js +0 -263
  237. package/plugins/kimi-dsh/dist/mcp/operations.js +0 -333
  238. package/plugins/kimi-dsh/dist/mcp/protocol.js +0 -277
  239. package/plugins/kimi-dsh/dist/mcp/server.js +0 -8
  240. package/plugins/kimi-dsh/dist/mcp/stdio.js +0 -79
  241. package/plugins/kimi-dsh/dist/mcp/supervised-child.js +0 -15
  242. package/plugins/kimi-dsh/dist/mcp/tool-result.js +0 -7
  243. package/plugins/kimi-dsh/dist/mcp/workspace.js +0 -34
  244. package/plugins/kimi-dsh/dist/model-command.js +0 -34
  245. package/plugins/kimi-dsh/dist/native-v2-preflight.js +0 -596
  246. package/plugins/kimi-dsh/dist/package.json +0 -1
  247. package/plugins/kimi-dsh/dist/parsing.js +0 -554
  248. package/plugins/kimi-dsh/dist/paths.js +0 -35
  249. package/plugins/kimi-dsh/dist/plugin-data.js +0 -98
  250. package/plugins/kimi-dsh/dist/process-tree.js +0 -597
  251. package/plugins/kimi-dsh/dist/prompt-size.js +0 -18
  252. package/plugins/kimi-dsh/dist/read-scope.js +0 -435
  253. package/plugins/kimi-dsh/dist/render.js +0 -214
  254. package/plugins/kimi-dsh/dist/rescue-approval.js +0 -1242
  255. package/plugins/kimi-dsh/dist/schemas/review-gate-output.js +0 -41
  256. package/plugins/kimi-dsh/dist/session-recovery.js +0 -202
  257. package/plugins/kimi-dsh/dist/session-title.js +0 -313
  258. package/plugins/kimi-dsh/dist/stream-json.js +0 -344
  259. package/plugins/kimi-dsh/dist/surface-routing.js +0 -21
  260. package/plugins/kimi-dsh/dist/swarm-activation.js +0 -1194
  261. package/plugins/kimi-dsh/dist/swarm-policy.js +0 -74
  262. package/plugins/kimi-dsh/dist/swarm-recovery.js +0 -166
  263. package/plugins/kimi-dsh/dist/swarm-tool-policy.js +0 -146
  264. package/plugins/kimi-dsh/dist/types.js +0 -1
  265. package/plugins/kimi-dsh/dist/util.js +0 -28
  266. package/plugins/kimi-dsh/dist/vendor/shell-quote/LICENSE +0 -24
  267. package/plugins/kimi-dsh/dist/vendor/shell-quote/index.js +0 -1
  268. package/plugins/kimi-dsh/dist/vendor/shell-quote/parse.js +0 -229
  269. package/plugins/kimi-dsh/dist/vendor/smol-toml/LICENSE +0 -24
  270. package/plugins/kimi-dsh/dist/vendor/smol-toml/date.js +0 -156
  271. package/plugins/kimi-dsh/dist/vendor/smol-toml/error.js +0 -67
  272. package/plugins/kimi-dsh/dist/vendor/smol-toml/extract.js +0 -293
  273. package/plugins/kimi-dsh/dist/vendor/smol-toml/parse.js +0 -164
  274. package/plugins/kimi-dsh/dist/vendor/smol-toml/primitive.js +0 -151
  275. package/plugins/kimi-dsh/dist/vendor/smol-toml/struct.js +0 -156
  276. package/plugins/kimi-dsh/dist/vendor/smol-toml/util.js +0 -57
  277. package/plugins/kimi-dsh/dist/version.js +0 -7
  278. package/plugins/kimi-dsh/package.json +0 -78
  279. package/plugins/kimi-dsh/scripts/companion.sh +0 -37
  280. package/plugins/kimi-dsh/scripts/review-gate-hook.sh +0 -32
  281. package/scripts/review-gate-hook.sh +0 -32
@@ -1,74 +0,0 @@
1
- import { kimiReleaseHas } from "./kimi-releases.js";
2
- export const SWARM_POLICY_ENV = "KIMI_PLUGIN_CC_SWARM_POLICY";
3
- export const SWARM_WAVE_SIZE_ENV = "KIMI_PLUGIN_CC_SWARM_WAVE_SIZE";
4
- export const BOUNDED_SWARM_POLICY = "bounded-waves/1";
5
- // Native retry timeouts can return a wave before its child work settles. This
6
- // valid upstream timer exceeds the plugin's finite <=24h job deadline, so only
7
- // terminal whole-job cancellation can interrupt a wave. Environment 0 is ignored.
8
- export const SWARM_CHILD_TIMEOUT_MS = 2_147_483_647;
9
- export function usesBoundedSwarmPolicy(plan) {
10
- return plan.intendedEngine === "native-v2" &&
11
- kimiReleaseHas(plan.kimiVersion, "bounded-swarm") &&
12
- (plan.operationKind === "swarm" || plan.operationKind === "swarm-write");
13
- }
14
- function plainObject(value) {
15
- return value !== null && typeof value === "object" && !Array.isArray(value) &&
16
- (Object.getPrototypeOf(value) === Object.prototype || Object.getPrototypeOf(value) === null);
17
- }
18
- function nonemptyString(value) {
19
- return typeof value === "string" && value.trim().length > 0;
20
- }
21
- const SWARM_INPUT_KEYS = new Set([
22
- "description", "subagent_type", "prompt_template", "items", "fork", "resume_agent_ids", "model",
23
- ]);
24
- /** Stateless admission; repeated host hooks cannot consume or refund slots. */
25
- export function evaluateSwarmWaveInput(input, policy, waveSize) {
26
- const deny = (reason) => ({
27
- decision: "deny",
28
- reason: `kimi-plugin-cc safety hook: AgentSwarm denied: ${reason}`,
29
- });
30
- if (policy !== BOUNDED_SWARM_POLICY)
31
- return deny("missing or unrecognized swarm policy.");
32
- const width = typeof waveSize === "string" && /^[1-9][0-9]*$/.test(waveSize)
33
- ? Number(waveSize) : NaN;
34
- if (!Number.isSafeInteger(width) || width < 1)
35
- return deny("missing or invalid trusted wave size.");
36
- if (width === 1) {
37
- return deny("concurrency 1 uses one worker directly; complete the task yourself without delegation.");
38
- }
39
- if (!plainObject(input))
40
- return deny("arguments must be an object.");
41
- if (Reflect.ownKeys(input).some((key) => typeof key !== "string" || !SWARM_INPUT_KEYS.has(key))) {
42
- return deny("unrecognized arguments.");
43
- }
44
- if (!nonemptyString(input.description))
45
- return deny("description must be a nonempty string.");
46
- for (const key of ["subagent_type", "prompt_template"]) {
47
- if (input[key] !== undefined && !nonemptyString(input[key]))
48
- return deny(`${key} must be a nonempty string.`);
49
- }
50
- if (input.model !== undefined && typeof input.model !== "string")
51
- return deny("model must be a string.");
52
- if (input.fork !== undefined && input.fork !== false)
53
- return deny("forked subagents are not supported.");
54
- if (input.items !== undefined && (!Array.isArray(input.items) || !input.items.every(nonemptyString))) {
55
- return deny("items must be an array of nonempty strings.");
56
- }
57
- if (input.resume_agent_ids !== undefined && (!plainObject(input.resume_agent_ids) ||
58
- Reflect.ownKeys(input.resume_agent_ids).some((key) => typeof key !== "string" ||
59
- !nonemptyString(key) || !nonemptyString(input.resume_agent_ids[key])))) {
60
- return deny("resume_agent_ids must map nonempty agent IDs to nonempty prompts.");
61
- }
62
- const fresh = Array.isArray(input.items) ? input.items.length : 0;
63
- const resumed = plainObject(input.resume_agent_ids) ? Object.keys(input.resume_agent_ids).length : 0;
64
- const total = fresh + resumed;
65
- if (total === 0)
66
- return deny("a wave must contain at least one new or resumed entry.");
67
- if (total > width) {
68
- return deny(`wave has ${total} new and resumed entries, exceeding the limit ${width}; split the work into sequential waves of at most ${width} entries and wait for each wave to finish.`);
69
- }
70
- if (fresh === 1 && resumed === 0) {
71
- return deny("fresh-only waves require at least two entries; regroup targets into disjoint entries within the wave limit, or resume an existing child for the remaining work.");
72
- }
73
- return { decision: "allow" };
74
- }
@@ -1,166 +0,0 @@
1
- import { RuntimeError } from "./errors.js";
2
- import { sleep } from "./util.js";
3
- import { collectDescendantIdentities, collectProcessGroupsIdentities, probeProcessIdentity, revalidateProcessIdentities } from "./process-tree.js";
4
- export function recordRecoveryEvent(store, record, event) {
5
- record.complete = false;
6
- if (event.kind === "session") {
7
- record.session = { sessionId: event.sessionId, workspaceId: event.workspaceId };
8
- // Write-ahead: this must commit before the profile mutation is attempted.
9
- record.sessionDirty = true;
10
- }
11
- else if (event.kind === "disabled") {
12
- record.sessionDirty = false;
13
- }
14
- else if (event.kind.endsWith("-spawn")) {
15
- record.launches.push({ kind: event.kind === "web-spawn" ? "web" : "print", pending: true, identities: [], quiescent: false, uncertain: false });
16
- }
17
- else {
18
- const kind = event.kind.startsWith("web-") ? "web" : "print";
19
- const launch = [...record.launches].reverse().find((entry) => entry.kind === kind);
20
- if (!launch)
21
- throw recoveryError("Missing durable launch intent.");
22
- if (event.kind === "web-exit" || event.kind === "print-exit") {
23
- launch.quiescent = true;
24
- launch.pending = false;
25
- }
26
- else if (event.kind === "print-processes-snapshot") {
27
- const root = launch.identities[0];
28
- if (!root)
29
- throw recoveryError("The print root identity was not durably recorded before its process snapshot.");
30
- // The root remains the recovery anchor after exit. Complete bounded
31
- // snapshots replace historical descendants; an incomplete observation
32
- // cannot discard an identity whose exit has not been proven.
33
- const previous = new Map(launch.identities.map((identity) => [processIdentityKey(identity), identity]));
34
- const current = event.identities.map((identity) => previous.get(processIdentityKey(identity)) ?? identity);
35
- const all = event.complete ? [root, ...current] : [...launch.identities, ...current];
36
- launch.identities = [...new Map(all.map((identity) => [processIdentityKey(identity), identity])).values()];
37
- launch.pending = false;
38
- launch.uncertain = !event.complete;
39
- launch.boundedSnapshot = true;
40
- }
41
- else if ("identities" in event) {
42
- const all = [...launch.identities, ...event.identities];
43
- launch.identities = [...new Map(all.map((identity) => [`${identity.pid}:${identity.startToken}:${identity.processGroupId}`, identity])).values()];
44
- launch.pending = launch.identities.length === 0;
45
- launch.uncertain ||= !event.complete;
46
- }
47
- }
48
- store.saveSwarmRecovery(record.jobId, record);
49
- }
50
- function processIdentityKey(identity) {
51
- // A changed process group is not a new ownership grant for the same process.
52
- return `${identity.pid}:${identity.startToken}`;
53
- }
54
- export function finishRecoveryRecord(store, record) {
55
- record.complete = !record.sessionDirty && record.launches.every((entry) => entry.quiescent)
56
- && (record.workspaceRoot === null || record.patchPath !== null);
57
- store.saveSwarmRecovery(record.jobId, record);
58
- }
59
- export function recoveryError(message) {
60
- return new RuntimeError("SWARM_RECOVERY_REQUIRED", message, "swarm.recovery");
61
- }
62
- export async function assertRecoveryOwnerGone(record) {
63
- if (!record.owner || process.platform === "win32")
64
- throw recoveryError("No durable, verifiable owner identity; recovery requires manual inspection on this host.");
65
- const probe = await probeProcessIdentity(record.ownerPid);
66
- if (!probe.complete)
67
- throw recoveryError("Cannot verify the original companion's identity.");
68
- if (probe.identity?.startToken === record.owner.startToken && !/^[ZX]/i.test(probe.identity.state)) {
69
- throw recoveryError("The original companion is still alive. Use cancel for a running job, not recovery.");
70
- }
71
- }
72
- /**
73
- * Older Linux records may retain ps start tokens while current snapshots use
74
- * /proc start ticks. Prove both representations current around the known identity
75
- * read; never accept a member based on PID/PGID equality alone.
76
- */
77
- export async function validateRecoveryGroupMembers(known, members, validate = revalidateProcessIdentities) {
78
- const membership = await validate(members);
79
- const ownership = await validate(known);
80
- const membershipAfter = await validate(membership.identities);
81
- for (const proof of [membership, ownership, membershipAfter]) {
82
- if (!proof.complete || proof.groupChanged?.length)
83
- throw recoveryError("Process ownership or group membership is uncertain.");
84
- }
85
- for (const member of membershipAfter.identities) {
86
- const owner = ownership.identities.find((id) => id.pid === member.pid && id.processGroupId === member.processGroupId);
87
- const crossNamespace = owner && ((owner.startToken.startsWith("proc:") && member.startToken.startsWith("ps:")) ||
88
- (owner.startToken.startsWith("ps:") && member.startToken.startsWith("proc:")));
89
- if (!owner || (owner.startToken !== member.startToken && !crossNamespace)) {
90
- throw recoveryError("An unrecorded process survives in the recorded group; refusing group cleanup.");
91
- }
92
- }
93
- return ownership.identities;
94
- }
95
- export async function inspectRecoveryLaunchProcesses(launch, validate = revalidateProcessIdentities, collect = collectProcessGroupsIdentities) {
96
- let known = launch.identities;
97
- if (launch.kind === "print" && launch.boundedSnapshot === true) {
98
- const live = await validate(known);
99
- if (!live.complete || live.groupChanged?.length) {
100
- throw recoveryError("Process ownership or group membership is uncertain.");
101
- }
102
- // The saved root remains first for ancestry recovery, but an exited root
103
- // grants no ownership of its numeric group after that group is reused.
104
- known = live.identities;
105
- if (known.length === 0)
106
- return [];
107
- }
108
- const members = await collect(known.map((identity) => identity.processGroupId));
109
- if (members === undefined)
110
- throw recoveryError("Process group membership is unreadable.");
111
- return validateRecoveryGroupMembers(known, members, validate);
112
- }
113
- /** Never signal an unproven group, PID replacement, or changed-PGID process. */
114
- export async function recoverLaunch(launch, persist, signal) {
115
- if (launch.quiescent)
116
- return;
117
- if (launch.pending || launch.uncertain || launch.identities.length === 0) {
118
- throw recoveryError("Launch ownership was not fully recorded before interruption; manual inspection is required. No process was signalled.");
119
- }
120
- const root = launch.identities[0];
121
- const rootProbe = await probeProcessIdentity(root.pid);
122
- if (!rootProbe.complete)
123
- throw recoveryError("Process identity probe is incomplete.");
124
- if (rootProbe.identity?.startToken === root.startToken) {
125
- if (rootProbe.identity.processGroupId !== root.processGroupId)
126
- throw recoveryError("The recorded root changed process groups; refusing to signal it.");
127
- const descendants = await collectDescendantIdentities(root.pid);
128
- // Revalidate the ancestry anchor after collection before retaining new identities.
129
- const after = await probeProcessIdentity(root.pid);
130
- if (!after.complete || after.identity?.startToken !== root.startToken || after.identity.processGroupId !== root.processGroupId) {
131
- throw recoveryError("Process ownership changed during recovery inspection.");
132
- }
133
- launch.identities = [...new Map([...launch.identities, ...descendants].map((id) => [`${id.pid}:${id.startToken}:${id.processGroupId}`, id])).values()];
134
- persist();
135
- }
136
- const inspect = () => inspectRecoveryLaunchProcesses(launch);
137
- for (const [killSignal, waitMs] of [["SIGTERM", 1500], ["SIGKILL", 500]]) {
138
- signal?.throwIfAborted();
139
- for (const identity of await inspect()) {
140
- signal?.throwIfAborted();
141
- const current = await revalidateProcessIdentities([identity]);
142
- if (!current.complete || current.groupChanged?.length)
143
- throw recoveryError("Process identity changed before signalling.");
144
- if (current.identities.length) {
145
- try {
146
- process.kill(identity.pid, killSignal);
147
- }
148
- catch (error) {
149
- if (error.code !== "ESRCH")
150
- throw recoveryError("Unable to stop the recorded process.");
151
- }
152
- }
153
- }
154
- const deadline = Date.now() + waitMs;
155
- do {
156
- signal?.throwIfAborted();
157
- if ((await inspect()).length === 0) {
158
- launch.quiescent = true;
159
- persist();
160
- return;
161
- }
162
- await sleep(25);
163
- } while (Date.now() < deadline);
164
- }
165
- throw recoveryError("Recorded processes did not become quiescent; recovery remains pending.");
166
- }
@@ -1,146 +0,0 @@
1
- import { randomUUID } from "node:crypto";
2
- import { constants } from "node:fs";
3
- import { link, lstat, mkdir, open, realpath, unlink } from "node:fs/promises";
4
- import path from "node:path";
5
- import { RuntimeError } from "./errors.js";
6
- const POLICY_CONTENT = `${JSON.stringify({ disabledTools: ["TaskStop"] })}\n`;
7
- const POLICY_MAX_BYTES = 4096;
8
- const SAFE_ID = /^[A-Za-z0-9][A-Za-z0-9_-]{0,255}$/;
9
- /**
10
- * Called only for our fresh, stopped, journal-proven session before its first
11
- * print turn. TaskStop is already denied by the managed hook; disabling it in
12
- * native policy also makes Bash's allowBackground false for every child,
13
- * including its automatic foreground-timeout detachment path.
14
- */
15
- export async function installBoundedSwarmToolPolicy(kimiHome, identity, signal) {
16
- const directories = [];
17
- let candidatePath;
18
- let candidateIdentity;
19
- try {
20
- checkSignal(signal);
21
- if (!SAFE_ID.test(identity.sessionId) || !SAFE_ID.test(identity.workspaceId)) {
22
- throw policyFailure("invalid-session-identity");
23
- }
24
- const canonicalHome = await realpath(kimiHome);
25
- let current = canonicalHome;
26
- for (const segment of [undefined, "sessions", identity.workspaceId, identity.sessionId]) {
27
- if (segment !== undefined)
28
- current = path.join(current, segment);
29
- directories.push(await directoryIdentity(current));
30
- checkSignal(signal);
31
- }
32
- const policyDir = path.join(current, "tool-policy");
33
- await assertDirectoriesUnchanged(directories);
34
- await mkdir(policyDir, { mode: 0o700 }).catch((error) => {
35
- if (error.code !== "EEXIST")
36
- throw error;
37
- });
38
- directories.push(await directoryIdentity(policyDir));
39
- const statePath = path.join(policyDir, "state.json");
40
- // No merge or replacement: this is a fresh-session construction, not an
41
- // operator-policy editor. link() below closes this absence-check race.
42
- const existing = await lstat(statePath).catch((error) => {
43
- if (error.code === "ENOENT")
44
- return undefined;
45
- throw error;
46
- });
47
- if (existing !== undefined)
48
- throw policyFailure("policy-already-exists");
49
- checkSignal(signal);
50
- await assertDirectoriesUnchanged(directories);
51
- candidatePath = path.join(policyDir, `.state.${process.pid}.${randomUUID()}.tmp`);
52
- const candidate = await open(candidatePath, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | (constants.O_NOFOLLOW ?? 0), 0o600);
53
- try {
54
- const stats = await candidate.stat({ bigint: true });
55
- candidateIdentity = { dev: stats.dev, ino: stats.ino };
56
- if (!stats.isFile())
57
- throw policyFailure("candidate-not-regular");
58
- if (process.platform !== "win32")
59
- await candidate.chmod(0o600);
60
- await candidate.writeFile(POLICY_CONTENT, "utf8");
61
- await candidate.sync();
62
- }
63
- finally {
64
- await candidate.close();
65
- }
66
- checkSignal(signal);
67
- await assertDirectoriesUnchanged(directories);
68
- // A hard link publishes the complete synced inode atomically and refuses
69
- // an existing destination, unlike rename(), which could replace policy.
70
- await link(candidatePath, statePath);
71
- await verifyPublishedPolicy(statePath, candidateIdentity);
72
- await assertDirectoriesUnchanged(directories);
73
- checkSignal(signal);
74
- }
75
- catch (error) {
76
- if (signal?.aborted)
77
- throw policyFailure("cancelled", true);
78
- if (error instanceof RuntimeError)
79
- throw error;
80
- throw policyFailure("policy-installation-failed");
81
- }
82
- finally {
83
- // Never unlink a replacement or follow a replaced ancestor while cleaning
84
- // up our private candidate. An uncertain path remains as failure evidence.
85
- if (candidatePath !== undefined && candidateIdentity !== undefined) {
86
- try {
87
- await assertDirectoriesUnchanged(directories);
88
- const stats = await lstat(candidatePath, { bigint: true });
89
- if (stats.isFile() && sameIdentity(stats, candidateIdentity))
90
- await unlink(candidatePath);
91
- }
92
- catch { /* Preserve uncertain paths. */ }
93
- }
94
- }
95
- }
96
- async function directoryIdentity(directory) {
97
- const stats = await lstat(directory, { bigint: true });
98
- if (!stats.isDirectory() || stats.isSymbolicLink() || await realpath(directory) !== directory) {
99
- throw policyFailure("unsafe-session-directory");
100
- }
101
- return { path: directory, dev: stats.dev, ino: stats.ino };
102
- }
103
- async function assertDirectoriesUnchanged(directories) {
104
- for (const directory of directories) {
105
- const current = await directoryIdentity(directory.path);
106
- if (!sameIdentity(current, directory))
107
- throw policyFailure("session-directory-changed");
108
- }
109
- }
110
- async function verifyPublishedPolicy(statePath, expected) {
111
- const file = await open(statePath, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0) | (constants.O_NONBLOCK ?? 0));
112
- try {
113
- const before = await file.stat({ bigint: true });
114
- if (!before.isFile() || before.size > BigInt(POLICY_MAX_BYTES) || !sameIdentity(before, expected)) {
115
- throw policyFailure("published-policy-invalid");
116
- }
117
- const bytes = Buffer.alloc(Number(before.size));
118
- let offset = 0;
119
- while (offset < bytes.length) {
120
- const { bytesRead } = await file.read(bytes, offset, bytes.length - offset, offset);
121
- if (bytesRead === 0)
122
- break;
123
- offset += bytesRead;
124
- }
125
- const after = await file.stat({ bigint: true });
126
- const named = await lstat(statePath, { bigint: true });
127
- if (offset !== bytes.length || bytes.toString("utf8") !== POLICY_CONTENT ||
128
- before.size !== after.size || !sameIdentity(after, expected) ||
129
- !named.isFile() || !sameIdentity(named, expected)) {
130
- throw policyFailure("published-policy-changed");
131
- }
132
- }
133
- finally {
134
- await file.close();
135
- }
136
- }
137
- function sameIdentity(a, b) {
138
- return a.dev === b.dev && a.ino === b.ino;
139
- }
140
- function checkSignal(signal) {
141
- if (signal?.aborted)
142
- throw policyFailure("cancelled", true);
143
- }
144
- function policyFailure(reason, cancelled = false) {
145
- return new RuntimeError("SWARM_ACTIVATION_FAILED", "The fresh swarm session could not install its native tool restriction; refusing the model turn.", "swarm-activation.tool-policy", { details: { reason, ...(cancelled ? { cancelled: true } : {}) } });
146
- }
@@ -1 +0,0 @@
1
- export {};
@@ -1,28 +0,0 @@
1
- /** Small helpers shared across the runtime. Imports nothing. */
2
- // Uses the global timer on purpose: tests observe globalThis.setTimeout.
3
- export function sleep(ms) {
4
- return new Promise((resolve) => setTimeout(resolve, ms));
5
- }
6
- /** Collapse whitespace and cut to `max` characters, ending in an ellipsis when cut. */
7
- export function shorten(text, max) {
8
- const normalized = text.replace(/\s+/g, " ").trim();
9
- if (normalized.length <= max) {
10
- return normalized;
11
- }
12
- return `${normalized.slice(0, Math.max(0, max - 1)).trimEnd()}…`;
13
- }
14
- /**
15
- * Where a smol-toml parse failed. Its own message quotes the neighbouring
16
- * source lines, and lines of kimi-code's config can hold credentials, so that
17
- * message must never reach an error, log or artifact.
18
- */
19
- export function tomlErrorLocation(error) {
20
- // `codeblock` marks a smol-toml TomlError; plain Errors also carry line/column under Bun.
21
- const { line, column, codeblock } = (typeof error === "object" && error !== null ? error : {});
22
- return typeof codeblock === "string" && typeof line === "number" && typeof column === "number"
23
- ? `syntax error at line ${line}, column ${column}`
24
- : "syntax error";
25
- }
26
- export function isRecord(value) {
27
- return typeof value === "object" && value !== null && !Array.isArray(value);
28
- }
@@ -1,24 +0,0 @@
1
- The MIT License
2
-
3
- Copyright (c) 2013 James Halliday (mail@substack.net)
4
-
5
- Permission is hereby granted, free of charge,
6
- to any person obtaining a copy of this software and
7
- associated documentation files (the "Software"), to
8
- deal in the Software without restriction, including
9
- without limitation the rights to use, copy, modify,
10
- merge, publish, distribute, sublicense, and/or sell
11
- copies of the Software, and to permit persons to whom
12
- the Software is furnished to do so,
13
- subject to the following conditions:
14
-
15
- The above copyright notice and this permission notice
16
- shall be included in all copies or substantial portions of the Software.
17
-
18
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
19
- EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
20
- OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
21
- IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR
22
- ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
23
- TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
24
- SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
@@ -1 +0,0 @@
1
- export { parse } from "./parse.js";
@@ -1,229 +0,0 @@
1
- // @ts-nocheck
2
- // Vendored from shell-quote 1.8.3 with the upstream 1.9.0 linear-finalization fix.
3
- // MIT, James Halliday. See ./LICENSE and ./README.md for provenance.
4
- 'use strict';
5
- // '<(' is process substitution operator and
6
- // can be parsed the same as control operator
7
- var CONTROL = '(?:' + [
8
- '\\|\\|',
9
- '\\&\\&',
10
- ';;',
11
- '\\|\\&',
12
- '\\<\\(',
13
- '\\<\\<\\<',
14
- '>>',
15
- '>\\&',
16
- '<\\&',
17
- '[&;()|<>]'
18
- ].join('|') + ')';
19
- var controlRE = new RegExp('^' + CONTROL + '$');
20
- var META = '|&;()<> \\t';
21
- var SINGLE_QUOTE = '"((\\\\"|[^"])*?)"';
22
- var DOUBLE_QUOTE = '\'((\\\\\'|[^\'])*?)\'';
23
- var hash = /^#$/;
24
- var SQ = "'";
25
- var DQ = '"';
26
- var DS = '$';
27
- var TOKEN = '';
28
- var mult = 0x100000000; // Math.pow(16, 8);
29
- for (var i = 0; i < 4; i++) {
30
- TOKEN += (mult * Math.random()).toString(16);
31
- }
32
- var startsWithToken = new RegExp('^' + TOKEN);
33
- function matchAll(s, r) {
34
- var origIndex = r.lastIndex;
35
- var matches = [];
36
- var matchObj;
37
- while ((matchObj = r.exec(s))) {
38
- matches.push(matchObj);
39
- if (r.lastIndex === matchObj.index) {
40
- r.lastIndex += 1;
41
- }
42
- }
43
- r.lastIndex = origIndex;
44
- return matches;
45
- }
46
- function getVar(env, pre, key) {
47
- var r = typeof env === 'function' ? env(key) : env[key];
48
- if (typeof r === 'undefined' && key != '') {
49
- r = '';
50
- }
51
- else if (typeof r === 'undefined') {
52
- r = '$';
53
- }
54
- if (typeof r === 'object') {
55
- return pre + TOKEN + JSON.stringify(r) + TOKEN;
56
- }
57
- return pre + r;
58
- }
59
- function parseInternal(string, env, opts) {
60
- if (!opts) {
61
- opts = {};
62
- }
63
- var BS = opts.escape || '\\';
64
- var BAREWORD = '(\\' + BS + '[\'"' + META + ']|[^\\s\'"' + META + '])+';
65
- var chunker = new RegExp([
66
- '(' + CONTROL + ')', // control chars
67
- '(' + BAREWORD + '|' + SINGLE_QUOTE + '|' + DOUBLE_QUOTE + ')+'
68
- ].join('|'), 'g');
69
- var matches = matchAll(string, chunker);
70
- if (matches.length === 0) {
71
- return [];
72
- }
73
- if (!env) {
74
- env = {};
75
- }
76
- var commented = false;
77
- return matches.map(function (match) {
78
- var s = match[0];
79
- if (!s || commented) {
80
- return void undefined;
81
- }
82
- if (controlRE.test(s)) {
83
- return { op: s };
84
- }
85
- // Hand-written scanner/parser for Bash quoting rules:
86
- //
87
- // 1. inside single quotes, all characters are printed literally.
88
- // 2. inside double quotes, all characters are printed literally
89
- // except variables prefixed by '$' and backslashes followed by
90
- // either a double quote or another backslash.
91
- // 3. outside of any quotes, backslashes are treated as escape
92
- // characters and not printed (unless they are themselves escaped)
93
- // 4. quote context can switch mid-token if there is no whitespace
94
- // between the two quote contexts (e.g. all'one'"token" parses as
95
- // "allonetoken")
96
- var quote = false;
97
- var esc = false;
98
- var out = '';
99
- var isGlob = false;
100
- var i;
101
- function parseEnvVar() {
102
- i += 1;
103
- var varend;
104
- var varname;
105
- var char = s.charAt(i);
106
- if (char === '{') {
107
- i += 1;
108
- if (s.charAt(i) === '}') {
109
- throw new Error('Bad substitution: ' + s.slice(i - 2, i + 1));
110
- }
111
- varend = s.indexOf('}', i);
112
- if (varend < 0) {
113
- throw new Error('Bad substitution: ' + s.slice(i));
114
- }
115
- varname = s.slice(i, varend);
116
- i = varend;
117
- }
118
- else if ((/[*@#?$!_-]/).test(char)) {
119
- varname = char;
120
- i += 1;
121
- }
122
- else {
123
- var slicedFromI = s.slice(i);
124
- varend = slicedFromI.match(/[^\w\d_]/);
125
- if (!varend) {
126
- varname = slicedFromI;
127
- i = s.length;
128
- }
129
- else {
130
- varname = slicedFromI.slice(0, varend.index);
131
- i += varend.index - 1;
132
- }
133
- }
134
- return getVar(env, '', varname);
135
- }
136
- for (i = 0; i < s.length; i++) {
137
- var c = s.charAt(i);
138
- isGlob = isGlob || (!quote && (c === '*' || c === '?'));
139
- if (esc) {
140
- out += c;
141
- esc = false;
142
- }
143
- else if (quote) {
144
- if (c === quote) {
145
- quote = false;
146
- }
147
- else if (quote == SQ) {
148
- out += c;
149
- }
150
- else { // Double quote
151
- if (c === BS) {
152
- i += 1;
153
- c = s.charAt(i);
154
- if (c === DQ || c === BS || c === DS) {
155
- out += c;
156
- }
157
- else {
158
- out += BS + c;
159
- }
160
- }
161
- else if (c === DS) {
162
- out += parseEnvVar();
163
- }
164
- else {
165
- out += c;
166
- }
167
- }
168
- }
169
- else if (c === DQ || c === SQ) {
170
- quote = c;
171
- }
172
- else if (controlRE.test(c)) {
173
- return { op: s };
174
- }
175
- else if (hash.test(c)) {
176
- commented = true;
177
- var commentObj = { comment: string.slice(match.index + i + 1) };
178
- if (out.length) {
179
- return [out, commentObj];
180
- }
181
- return [commentObj];
182
- }
183
- else if (c === BS) {
184
- esc = true;
185
- }
186
- else if (c === DS) {
187
- out += parseEnvVar();
188
- }
189
- else {
190
- out += c;
191
- }
192
- }
193
- if (isGlob) {
194
- return { op: 'glob', pattern: out };
195
- }
196
- return out;
197
- }).reduce(function (prev, arg) {
198
- if (typeof arg === 'undefined') {
199
- return prev;
200
- }
201
- [].concat(arg).forEach(function (entry) {
202
- prev[prev.length] = entry;
203
- });
204
- return prev;
205
- }, []);
206
- }
207
- export function parse(s, env, opts) {
208
- var mapped = parseInternal(s, env, opts);
209
- if (typeof env !== 'function') {
210
- return mapped;
211
- }
212
- return mapped.reduce(function (acc, value) {
213
- if (typeof value === 'object') {
214
- acc[acc.length] = value;
215
- return acc;
216
- }
217
- var xs = value.split(RegExp('(' + TOKEN + '.*?' + TOKEN + ')', 'g'));
218
- if (xs.length === 1) {
219
- acc[acc.length] = xs[0];
220
- return acc;
221
- }
222
- xs.filter(Boolean).forEach(function (x) {
223
- acc[acc.length] = startsWithToken.test(x)
224
- ? JSON.parse(x.split(TOKEN)[1])
225
- : x;
226
- });
227
- return acc;
228
- }, []);
229
- }