token-goat 2.9.28 → 2.9.30

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 (134) hide show
  1. package/README.md +36 -40
  2. package/SECURITY.md +28 -10
  3. package/THIRD_PARTY_NOTICES.md +40 -3
  4. package/dist/native/linux-arm64/tg-hook +0 -0
  5. package/dist/native/linux-x64/tg-hook +0 -0
  6. package/dist/ort-wasm-simd-threaded.mjs +59 -0
  7. package/dist/token-goat-chunk-3CHUNJ2O.mjs +53 -0
  8. package/dist/token-goat-chunk-3Z5S4KGM.mjs +918 -0
  9. package/dist/token-goat-chunk-4FVIAHSI.mjs +211 -0
  10. package/dist/{token-goat-chunk-66LODAUT.mjs → token-goat-chunk-4JJS54TR.mjs} +4 -3
  11. package/dist/token-goat-chunk-4LCCNRTG.mjs +313 -0
  12. package/dist/token-goat-chunk-54K3EUV3.mjs +35 -0
  13. package/dist/token-goat-chunk-56EIMS3E.mjs +159 -0
  14. package/dist/token-goat-chunk-5BCIJXMO.mjs +609 -0
  15. package/dist/token-goat-chunk-5KDMCMF2.mjs +362 -0
  16. package/dist/token-goat-chunk-5RG5SBL6.mjs +221 -0
  17. package/dist/{token-goat-chunk-RRNZMM3A.mjs → token-goat-chunk-5Y6ZYL6U.mjs} +21 -2
  18. package/dist/{token-goat-chunk-NILVK7XM.mjs → token-goat-chunk-64FBPDTK.mjs} +12 -6
  19. package/dist/{token-goat-chunk-LEG3JNJ6.mjs → token-goat-chunk-664RTTUV.mjs} +31 -15
  20. package/dist/token-goat-chunk-67TQJ76B.mjs +57 -0
  21. package/dist/token-goat-chunk-6QMAS7AB.mjs +42 -0
  22. package/dist/token-goat-chunk-7BXSNBY5.mjs +253 -0
  23. package/dist/{token-goat-chunk-F7QZRIWM.mjs → token-goat-chunk-7F2UBPD3.mjs} +42 -35
  24. package/dist/{token-goat-chunk-CC2PYJM7.mjs → token-goat-chunk-7IN2MKDS.mjs} +718 -595
  25. package/dist/token-goat-chunk-7NADEDKJ.mjs +124 -0
  26. package/dist/{token-goat-chunk-6SGLIPQB.mjs → token-goat-chunk-A3CK6N5Z.mjs} +621 -72
  27. package/dist/{token-goat-chunk-HXNAC4ZF.mjs → token-goat-chunk-AFLYLHDH.mjs} +48 -33
  28. package/dist/token-goat-chunk-AM5V6GSX.mjs +367 -0
  29. package/dist/{token-goat-chunk-I7CB3X4K.mjs → token-goat-chunk-APGZXSPS.mjs} +44 -148
  30. package/dist/{token-goat-chunk-BJBRGPBX.mjs → token-goat-chunk-ARDNEC2U.mjs} +11 -7
  31. package/dist/token-goat-chunk-ATCPY7EQ.mjs +134 -0
  32. package/dist/token-goat-chunk-B2RZZCSS.mjs +354 -0
  33. package/dist/{token-goat-chunk-QM76S6YS.mjs → token-goat-chunk-B45VMIIH.mjs} +6 -5
  34. package/dist/token-goat-chunk-BPGCUMR7.mjs +30 -0
  35. package/dist/{token-goat-chunk-GGLEE35R.mjs → token-goat-chunk-C63JQV5K.mjs} +49 -10
  36. package/dist/{token-goat-chunk-RJH64KQH.mjs → token-goat-chunk-COBQGL5S.mjs} +2661 -2440
  37. package/dist/token-goat-chunk-COTXZHTS.mjs +39 -0
  38. package/dist/token-goat-chunk-CYCEYAEO.mjs +265 -0
  39. package/dist/token-goat-chunk-CZ3LUXYZ.mjs +4115 -0
  40. package/dist/token-goat-chunk-DZX2YDPT.mjs +15 -0
  41. package/dist/token-goat-chunk-E3OQX2XT.mjs +824 -0
  42. package/dist/token-goat-chunk-EFHMMIGP.mjs +68 -0
  43. package/dist/token-goat-chunk-ETBHVDB6.mjs +328 -0
  44. package/dist/token-goat-chunk-EVMZJ27Z.mjs +147 -0
  45. package/dist/token-goat-chunk-EXKGNHEG.mjs +2096 -0
  46. package/dist/{token-goat-chunk-6Z5ULNE5.mjs → token-goat-chunk-FBNQNSJK.mjs} +2490 -4957
  47. package/dist/{token-goat-chunk-NMTKNYGF.mjs → token-goat-chunk-FNFBKLRD.mjs} +74 -9
  48. package/dist/{token-goat-chunk-XI2VFAV6.mjs → token-goat-chunk-FZ3NEW5O.mjs} +33 -19
  49. package/dist/token-goat-chunk-G5PJ7AGM.mjs +36 -0
  50. package/dist/{token-goat-chunk-VE27HPIF.mjs → token-goat-chunk-GFBSN7BD.mjs} +30 -398
  51. package/dist/{token-goat-chunk-L45ZQRT7.mjs → token-goat-chunk-GOLEOXZP.mjs} +780 -786
  52. package/dist/token-goat-chunk-H2K3QP6H.mjs +24 -0
  53. package/dist/token-goat-chunk-H2PHHGM5.mjs +188 -0
  54. package/dist/token-goat-chunk-HAVAOB3S.mjs +87 -0
  55. package/dist/token-goat-chunk-HG45AF2B.mjs +2228 -0
  56. package/dist/{token-goat-chunk-CBMY2FGI.mjs → token-goat-chunk-HOJLCGDP.mjs} +17113 -15554
  57. package/dist/{token-goat-chunk-HUDC5GS5.mjs → token-goat-chunk-HYBFA5X3.mjs} +120 -19
  58. package/dist/token-goat-chunk-IVALLT3S.mjs +48 -0
  59. package/dist/token-goat-chunk-IVE6U7KV.mjs +53 -0
  60. package/dist/{token-goat-chunk-UBUKHVYW.mjs → token-goat-chunk-IVKIZWAB.mjs} +3 -3
  61. package/dist/{token-goat-chunk-4JMWPWCS.mjs → token-goat-chunk-JB6QN6VF.mjs} +6 -4
  62. package/dist/{token-goat-chunk-Q4S3UQGO.mjs → token-goat-chunk-JDHE26RP.mjs} +10 -3
  63. package/dist/{token-goat-chunk-7R2XYKC5.mjs → token-goat-chunk-JDU3EXSU.mjs} +14 -10
  64. package/dist/token-goat-chunk-JDWCRD6M.mjs +253 -0
  65. package/dist/{token-goat-chunk-XBESNWEX.mjs → token-goat-chunk-JN4XMLSD.mjs} +7 -4
  66. package/dist/token-goat-chunk-JTQQGXZH.mjs +733 -0
  67. package/dist/token-goat-chunk-KKUFXAPD.mjs +25 -0
  68. package/dist/token-goat-chunk-KQNZDCBD.mjs +47 -0
  69. package/dist/{token-goat-chunk-4RN64ZND.mjs → token-goat-chunk-KWPNJBDH.mjs} +28 -3
  70. package/dist/token-goat-chunk-LOBGHXPB.mjs +242 -0
  71. package/dist/token-goat-chunk-MKPF4CL5.mjs +37 -0
  72. package/dist/token-goat-chunk-MNWKPRAL.mjs +13 -0
  73. package/dist/{token-goat-chunk-YWSP6IU7.mjs → token-goat-chunk-N2NMER56.mjs} +25 -15
  74. package/dist/token-goat-chunk-NYKZLXMK.mjs +218 -0
  75. package/dist/token-goat-chunk-OJBNYTJP.mjs +3087 -0
  76. package/dist/token-goat-chunk-P4QMM4WK.mjs +295 -0
  77. package/dist/token-goat-chunk-PD5VKH46.mjs +184 -0
  78. package/dist/token-goat-chunk-PEPTHRFF.mjs +129 -0
  79. package/dist/{token-goat-chunk-VWZKZPSR.mjs → token-goat-chunk-PU7V3FD6.mjs} +8752 -11098
  80. package/dist/token-goat-chunk-PY533T7F.mjs +46 -0
  81. package/dist/token-goat-chunk-Q5VTGRH7.mjs +761 -0
  82. package/dist/{token-goat-chunk-IHKZ3QNA.mjs → token-goat-chunk-QCLDAQTS.mjs} +33 -19
  83. package/dist/{token-goat-chunk-LKSXAMJB.mjs → token-goat-chunk-QSBRTGM2.mjs} +9 -2
  84. package/dist/{token-goat-chunk-4STDIGYC.mjs → token-goat-chunk-RC35RBUL.mjs} +7 -5
  85. package/dist/{token-goat-chunk-D5ICEPSB.mjs → token-goat-chunk-RHXKCZX3.mjs} +887 -507
  86. package/dist/{token-goat-chunk-RSS3TLXU.mjs → token-goat-chunk-RZRTDST7.mjs} +17 -7
  87. package/dist/{token-goat-chunk-MAMQPC43.mjs → token-goat-chunk-SJHWVNDQ.mjs} +15 -21
  88. package/dist/token-goat-chunk-SMVRN2HU.mjs +188 -0
  89. package/dist/{token-goat-chunk-EL7M26WP.mjs → token-goat-chunk-SQSSNQPE.mjs} +2100 -1442
  90. package/dist/{token-goat-chunk-OZRSREKR.mjs → token-goat-chunk-T4FK7VOV.mjs} +3 -3
  91. package/dist/token-goat-chunk-U4N3BN2W.mjs +92 -0
  92. package/dist/token-goat-chunk-UA5V6P3P.mjs +122 -0
  93. package/dist/{token-goat-chunk-XKY4VKJ4.mjs → token-goat-chunk-UQ5UK2T7.mjs} +15 -4
  94. package/dist/token-goat-chunk-USILZ3T3.mjs +53 -0
  95. package/dist/token-goat-chunk-VES7EL7O.mjs +205 -0
  96. package/dist/{token-goat-chunk-M56BWPBN.mjs → token-goat-chunk-VL3YIFHZ.mjs} +550 -49
  97. package/dist/{token-goat-chunk-IZXKVT4A.mjs → token-goat-chunk-VPBBTSJR.mjs} +362 -128
  98. package/dist/{token-goat-chunk-F2ARFHLJ.mjs → token-goat-chunk-W3QCJS6G.mjs} +10 -2
  99. package/dist/{token-goat-chunk-FSTWAOW6.mjs → token-goat-chunk-WY3L4DVT.mjs} +11 -5
  100. package/dist/{token-goat-chunk-OSUFN2FV.mjs → token-goat-chunk-XB5KKOCG.mjs} +5 -25
  101. package/dist/token-goat-chunk-XKI4SEMX.mjs +66 -0
  102. package/dist/token-goat-chunk-XU4P6Z24.mjs +133 -0
  103. package/dist/{token-goat-chunk-6CCQDAYY.mjs → token-goat-chunk-Y776AENC.mjs} +138 -33
  104. package/dist/token-goat-chunk-YARZFCZS.mjs +359 -0
  105. package/dist/{token-goat-chunk-EEIDFMEM.mjs → token-goat-chunk-YZAAZU2S.mjs} +12 -3
  106. package/dist/{token-goat-chunk-E3K3BTEQ.mjs → token-goat-chunk-Z44YO3QZ.mjs} +12 -6
  107. package/dist/token-goat-chunk-Z57YODA2.mjs +35 -0
  108. package/dist/{token-goat-chunk-DA43OE7L.mjs → token-goat-chunk-ZCDTCVIS.mjs} +49 -30
  109. package/dist/token-goat-chunk-ZEJVMUQH.mjs +48 -0
  110. package/dist/{token-goat-chunk-BGHSSJUA.mjs → token-goat-chunk-ZFOBKUWH.mjs} +1 -1
  111. package/dist/token-goat-chunk-ZMBL6UVV.mjs +110 -0
  112. package/dist/{token-goat-chunk-SJEKA7Y2.mjs → token-goat-chunk-ZQSJMO2R.mjs} +381 -201
  113. package/dist/token-goat-hook-client.cjs +539 -0
  114. package/dist/token-goat-hook-client.mjs +26 -0
  115. package/dist/token-goat-hook.mjs +48 -28
  116. package/dist/token-goat.core.mjs +10 -45
  117. package/docs/C4_RUNTIME_ARCHITECTURE.md +3 -3
  118. package/docs/cli.md +82 -47
  119. package/docs/install.md +58 -23
  120. package/docs/security.md +7 -7
  121. package/package.json +17 -7
  122. package/scripts/verify-native-dist.mjs +386 -0
  123. package/dist/token-goat-chunk-4JJBFT7V.mjs +0 -20
  124. package/dist/token-goat-chunk-5NNYIUGV.mjs +0 -143
  125. package/dist/token-goat-chunk-6DQNNFJ6.mjs +0 -294
  126. package/dist/token-goat-chunk-7MAFDRVR.mjs +0 -47
  127. package/dist/token-goat-chunk-BCN2YQC6.mjs +0 -32
  128. package/dist/token-goat-chunk-D7GHQKQD.mjs +0 -30
  129. package/dist/token-goat-chunk-GMOUBOX4.mjs +0 -386
  130. package/dist/token-goat-chunk-IFORDBGC.mjs +0 -192
  131. package/dist/token-goat-chunk-JXK2HQXS.mjs +0 -318
  132. package/dist/token-goat-chunk-L7SDVGBT.mjs +0 -430
  133. package/dist/token-goat-chunk-MMLMALWK.mjs +0 -1381
  134. package/dist/token-goat-chunk-MVSWBNMD.mjs +0 -1985
@@ -0,0 +1,211 @@
1
+ import { createRequire as __cjsRequire } from 'node:module';
2
+ const require = __cjsRequire(import.meta.url);
3
+ import {
4
+ loadConfig
5
+ } from "./token-goat-chunk-7IN2MKDS.mjs";
6
+ import {
7
+ growsExponentially,
8
+ hasNestedQuantifier
9
+ } from "./token-goat-chunk-GOLEOXZP.mjs";
10
+ import {
11
+ init_define_import_meta_env
12
+ } from "./token-goat-chunk-A37V4PBF.mjs";
13
+
14
+ // src/secret_redact.ts
15
+ init_define_import_meta_env();
16
+ var SECRET_PATTERNS = [
17
+ // Anthropic keys share OpenAI's "sk-" prefix but are more specific ("sk-ant-"), so they're matched first — the generic OpenAI pattern's negative lookahead below is defense in depth, not the sole guard.
18
+ ["anthropic_api_key", /sk-ant-[A-Za-z0-9_-]{20,}/g],
19
+ // Modern (post-2024, now the default) OpenAI project keys: "sk-proj-" followed by a long base64url-ish body that legitimately contains '-' and '_' -- the generic pattern below deliberately excludes those characters (hyphenated prose would false-fire), so this needs its own entry with the more specific prefix matched first, like sk-ant- above.
20
+ ["openai_project_key", /sk-proj-[A-Za-z0-9_-]{20,}/g],
21
+ ["openai_api_key", /sk-(?!ant-|proj-)[A-Za-z0-9]{20,}/g],
22
+ ["aws_access_key", /AKIA[0-9A-Z]{16}/g],
23
+ // Fine-grained PATs ("github_pat_...") are matched before the classic gh[oprsu]_ pattern so the full token is always consumed as one match -- a fine-grained token's own body can contain '_' and could otherwise partially match the classic pattern.
24
+ ["github_token", /github_pat_[A-Za-z0-9_]{22,}/g],
25
+ ["github_token", /gh[oprsu]_[A-Za-z0-9]{36,}/g],
26
+ // xapp- is Slack's app-level token (Socket Mode), a bearer credential in its own right that the xox[baprs]- prefix does not cover. It gets its own entry rather than joining the alternation above because it needs the full segmented shape (xapp-<ver>-<app id>-<digits>- <hex>) to be safe: a bare /xapp-[A-Za-z0-9-]+/ redacted ordinary identifiers like "xapp-config" and the css class "xapp-container", mangling normal source. The xox* prefixes are distinctive enough on their own; "xapp-" is not.
27
+ ["slack_token", /xox[baprs]-[A-Za-z0-9-]+/g],
28
+ ["slack_token", /xapp-\d-[A-Za-z0-9]{6,}-\d{8,}-[A-Za-z0-9]{16,}/g],
29
+ // Matches the full block (BEGIN marker through its matching END marker), not just the header -- the actual secret material is the base64 body between them, so redacting only the header line would leave the key bytes themselves fully readable in the cached blob. The body is lazy and additionally refuses to cross a following BEGIN marker. Both halves matter. The laziness bounds a successful match at the very next END marker; the negative lookahead bounds a *failing* one, because a BEGIN with no END of its own would otherwise scan to end-of-input, and a blob full of such markers made the pass quadratic -- 6 ms, 20 ms and 78 ms for 2000, 4000 and 8000 of them, four times the work for twice the input, the same shape as the lookbehind incident described above. Private key blocks do not nest, so refusing to cross a BEGIN costs nothing in correctness. The algorithm and ` BLOCK` groups are backreferenced in the END marker rather than repeated, so a BEGIN only ever pairs with its own END spelling. Written as two independent optional groups, `BEGIN PGP PRIVATE KEY` would happily close on a distant `END RSA PRIVATE KEY BLOCK` and redact everything in between. A non-participating group backreferences as the empty string in JS, which is exactly what the unprefixed `BEGIN PRIVATE KEY` form needs. The algorithm list covers every armored private-key header openssl, ssh-keygen and gpg actually emit, not just the ones a first draft happened to think of. ENCRYPTED is the PKCS#8 passphrase-protected form (`openssl genpkey -aes256`, `ssh-keygen -m PKCS8`) and is the most common shape of all; DSA is legacy but still written verbatim; PGP carries the ` BLOCK` suffix, which is why that suffix is optional here. All three used to fall through to disk in full. An encrypted key is still key material: the passphrase can be attacked offline once the bytes are cached, so it is redacted like any other. PuTTY `.ppk` files are deliberately not matched. They have no END marker -- the private section is a `Private-Lines: N` count followed by exactly N base64 lines -- so bounding a match would take a stateful parse rather than a regex, on a path that runs over every command output. A regex guess at where the body ends is exactly the over-eager match this module's header warns against.
30
+ ["private_key_block", /-----BEGIN (RSA |DSA |EC |OPENSSH |ENCRYPTED |PGP )?PRIVATE KEY( BLOCK)?-----(?:(?!-----BEGIN )[\s\S])*?-----END \1PRIVATE KEY\2-----/g],
31
+ // Redacts only the token itself, not the "Authorization: Bearer " prefix -- the lookbehind anchors on the header name and scheme so the surrounding request-log line stays readable, matching how AWS_ACCESS_KEY_ID=... above keeps its own prefix intact. The optional quotes on either side of the colon are what let this see a header carried in JSON rather than in raw wire format. Without them the lookbehind demanded the colon sit directly against the header name and the scheme directly against the space, so a body like {"Authorization": "Bearer <token>"} -- the shape any logged fetch or MCP result arrives in -- matched nothing and the token was cached verbatim. `token` is the second scheme spelling in wide use -- it is what curl and gh examples pass for GitHub and many other APIs -- and an opaque value behind it carries exactly the same authority as one behind `Bearer`. The trailing gap is `{1,8}` rather than a single space for the same reason every other gap in this lookbehind already is: a hand-aligned or reformatted header ("Authorization: Bearer <token>") is ordinary, and demanding exactly one space there made this the one position in the pattern that a second space defeated.
32
+ ["auth_bearer_token", /(?<=Authorization["']?[ \t]{0,8}:[ \t]{0,8}["']?[ \t]{0,8}(?:Bearer|token)[ \t]{1,8})[A-Za-z0-9\-._~+/]{10,}=*/gi],
33
+ ["auth_basic_token", /(?<=Authorization["']?[ \t]{0,8}:[ \t]{0,8}["']?[ \t]{0,8}Basic[ \t]{1,8})[A-Za-z0-9+/]{6,}=*/gi],
34
+ // JWTs have no distinctive prefix of their own, but the base64url encoding of the smallest realistic header ('{"alg":' or similar) always starts with "eyJ", so that's the practical anchor here -- each of the three dot-separated segments requires a minimum length to avoid matching a short, coincidentally dotted token. The trailing `={0,2}` on each segment is what makes a padded token match. Base64url as the JWT spec defines it drops the `=` padding, but producers that reach for a plain base64 encoder emit it anyway, and a `=` in the header or payload segment used to defeat the match outright: not a partial redaction, but none at all, so the entire token was printed. `=` cannot appear anywhere except the end of a segment, since it is not one of the characters the segment body allows, so accepting it here cannot widen the match onto anything else.
35
+ ["jwt", /eyJ[A-Za-z0-9_-]{10,}={0,2}\.[A-Za-z0-9_-]{10,}={0,2}\.[A-Za-z0-9_-]{10,}={0,2}/g],
36
+ ["npm_token", /npm_[A-Za-z0-9]{36}/g],
37
+ // rk_live_ (restricted keys) share the sk_live_/sk_test_ secret-key shape and risk level, so one pattern covers all three rather than adding a near-duplicate entry.
38
+ ["stripe_key", /(?:sk_live_|sk_test_|rk_live_)[A-Za-z0-9]{20,}/g],
39
+ ["google_api_key", /AIza[A-Za-z0-9_-]{35}/g],
40
+ // Presigned-url signatures: AWS SigV4 (X-Amz-Signature), Google Cloud Storage (X-Goog-Signature), and Azure blob SAS (sig). These are bearer credentials in query-string clothing -- anyone holding the whole url can read or write the object until it expires, and none of the prefix-anchored patterns above match them because the signature is a bare hex or base64 blob with no distinctive prefix of its own. The '[?&]' anchor and the 16-char floor are what make the short, generic 'sig' name safe to key on: a prose or code mention of "sig" never sits directly after a query separator followed by that much opaque token.
41
+ ["presigned_signature", /(?<=[?&](?:X-Amz-Signature|X-Goog-Signature|sig)=)[A-Za-z0-9%+/=_-]{16,}/gi],
42
+ // A password inside a connection url. `postgres://user:hunter2@db.internal` carries the credential in the authority section, where there is no `key=value` separator for the generic pattern below to anchor on, so a DATABASE_URL echoed by a failing migration or a psql error went through untouched. The anchors are what keep this narrow: a scheme's `://`, a userinfo segment, the colon, and a following `@`. `http://host:8080/path` has no `@` and is left alone; so is any url without credentials. The password class admits `:` and `@` (RFC 3986 lets userinfo carry the first, and a sloppy producer leaves the second unencoded), so the greedy run backtracks to the LAST `@` before the host; it still stops at whitespace, `/`, quotes and angle brackets, which keeps a quoted JSON neighbour or a following email out of the match. The username may be empty, because redis-py, Celery and most broker clients write a password-only url as `redis://:password@host:6379/0`, and it may hold an unencoded `@`, because a username that is itself an email address arrives that way; it still excludes `:` so the first colon after the scheme is the one that starts the password.
43
+ ["url_credentials", /(?<=:\/\/[^\s:/]{0,64}:)[^\s/"'`<>]{1,256}(?=@)/g],
44
+ // Azure storage account connection strings (`DefaultEndpointsProtocol=https;AccountName=...; AccountKey=<base64>==;EndpointSuffix=core.windows.net`) carry a full read/write key to the account in the AccountKey field, and none of the generic patterns above catch it: generic_secret_assignment's keyword list (password|passwd|secret|api[_-]?key| access[_-]?token|refresh[_-]?token|id[_-]?token) has nothing that matches "AccountKey", and an unanchored base64-shape pattern was deliberately rejected -- this module's header already warns that a bare high-entropy-blob heuristic false-fires on ordinary code, JSON and log output, and an 88-char base64 value is exactly the shape a hash, a compiled asset digest or a generated id can also take. Anchoring on the literal `AccountKey=` field name instead keeps the match specific to this one connection-string field. The value class is base64 proper (letters, digits, `+`, `/`, trailing `=` padding) and none of those characters include `;`, so the match terminates on its own at the `;` that starts the next `Name=` field -- unlike generic_secret_assignment's separator characters (`& ; # , :`), which double as ordinary credential characters and need a lookahead to tell the two roles apart, `;` is never valid base64 and needs no such lookahead here. The lookbehind keeps `AccountKey=` itself in the output, matching auth_bearer_token and presigned_signature above, so `;EndpointSuffix=core.windows.net` after it stays fully readable too. `SharedAccessKey` is the same credential one Azure service over: Service Bus, Event Hubs and Relay spell it that way (`Endpoint=sb://ns.servicebus.windows.net/;SharedAccessKeyName=Root; SharedAccessKey=<base64>`) and it carries the same authority over that namespace that AccountKey does over a storage account. `SharedAccessKeyName` is a plain identifier rather than a secret, and never matches: the separator in the lookbehind sits directly against the key name, so the `Name` in between stops it dead. The separator is spelled the way auth_bearer_token above spells its own, for the same reasons that comment records having learned the hard way. Optional quotes on either side of it, so the JSON and YAML forms a logged MCP result or api response actually arrives in are matched rather than stopped dead at the opening quote. A bounded gap rather than exactly one space, so a hand-aligned or reformatted `AccountKey = ...` in an appsettings file is not the single variant that defeats the whole pattern. Case-insensitive for the same reason presigned_signature is. The leading word boundary is what keeps the widened name from reaching into the middle of a longer identifier such as `myaccountkey=`.
45
+ ["azure_storage_key", /(?<=\b(?:AccountKey|SharedAccessKey)["']?[ \t]{0,8}[:=][ \t]{0,8}["']?)[A-Za-z0-9+/]{40,}=*/gi],
46
+ // Generic key=value assignments in .env-file and connection-string/query-string shape. The lookbehind again redacts only the value, and the value's character class deliberately excludes whitespace, '&', ';', '#', quote characters, and '[' ']' ':' -- that exclusion is what stops this from swallowing the rest of the line (a trailing comment or the next key=value pair) or the remainder of a query string past the matched parameter, which is exactly the kind of over-eager match this module's own design note above warns broad heuristics produce. The '[' ']' ':' exclusion also matters because this pattern runs last: an earlier pattern's own "OPENAI_API_KEY=[REDACTED:openai_project_key]" replacement text contains "API_KEY=" too, and without excluding those characters this pattern would re-match and double-redact its own placeholder. The length has a lower bound only (no upper bound): capping it at 64 used to leave the tail of any longer secret unredacted in plain text, which is worse than no redaction because it looks handled. A single negated-class quantifier like this cannot backtrack catastrophically -- there is no nested or overlapping quantifier for the engine to explore multiple ways of matching, so removing the upper bound does not introduce a ReDoS risk. Quotes are permitted around the separator, but never inside the value class. A quoted value is the ordinary way secrets are written -- .env files, JSON, YAML, TOML all quote by default -- and the lookbehind used to stop dead at the opening quote, so `API_KEY="..."` passed through in full while the bare `API_KEY=...` was caught. The closing quote of the key name blocked it from the other side too, which is what kept every JSON body unredacted. Keeping quotes out of the value class is still what stops the match running past the closing quote. The keyword may be a prefix of a longer key name rather than the whole of it, so the trailing identifier class below is load-bearing: without it the lookbehind required the keyword to sit immediately before the separator, and AWS_SECRET_ACCESS_KEY=, SECRET_KEY=, and DB_PASSWORD_HASH= all passed through in full. That class matches identifier characters only, so prose that merely mentions a keyword still never reaches a separator and stays unredacted. api[_-]?key covers the apikey and api-key spellings too. `& ; # , :` play two incompatible roles. They separate one field from the next (a query string, a cookie header, an inline env list), and they are also perfectly ordinary credential characters. Rejecting them outright got the first role right and the second badly wrong: the match stopped at the first one and left everything after it in plain text, so `password=corr&horse&battery` redacted four characters and printed the rest, and `DB_PASSWORD=Aa1:xyz` matched nothing at all because the run before the `:` was under the four-character floor. A tail left sitting in the open is the outcome this module's header calls worse than no redaction, because it reads as handled. So the separator role is decided by what follows rather than assumed: one of these characters ends the value only when the next thing along is another `name=` / `name:` pair, which is what an actual field separator is always followed by. `,OTHER=public` and `; other=1` still end it; the `&` in the middle of a passphrase does not. Whitespace, quotes and brackets are unchanged -- they end a value unconditionally, which is also what keeps this pattern from re-matching the `[REDACTED:...]` placeholder it just wrote.
47
+ ["generic_secret_assignment", /(?<=(?:password|passwd|secret|api[_-]?key|access[_-]?token|refresh[_-]?token|id[_-]?token)[a-z0-9_-]{0,64}["']?[ \t]{0,8}[:=][ \t]{0,8}["']?)(?:\\[^\n]|[^\s\\&;#,:'"[\]{}]|[&;#,:](?![ \t]*[A-Za-z_][A-Za-z0-9_.-]*[ \t]*[:=])){4,}/gi]
48
+ ];
49
+ function countRedactionPlaceholders(text) {
50
+ return text.match(/\[REDACTED:[a-z0-9_]+\]/g)?.length ?? 0;
51
+ }
52
+ var MAX_CUSTOM_PATTERNS = 64;
53
+ var MAX_CUSTOM_PATTERN_LENGTH = 512;
54
+ var ZERO_WIDTH_PROBES = ["", "a b"];
55
+ function matchesZeroWidth(compiled) {
56
+ return ZERO_WIDTH_PROBES.some((probe) => Array.from(probe.matchAll(compiled)).some((m) => m[0].length === 0));
57
+ }
58
+ var customCache = null;
59
+ function compileCustomPatterns(sources) {
60
+ const key = JSON.stringify(sources);
61
+ if (customCache !== null && customCache.key === key) {
62
+ return { patterns: customCache.patterns, problems: customCache.problems };
63
+ }
64
+ const patterns = [];
65
+ const problems = [];
66
+ const written = sources.map((raw) => raw.trim()).filter((source) => source.length > 0);
67
+ for (const source of written.slice(0, MAX_CUSTOM_PATTERNS)) {
68
+ if (source.length > MAX_CUSTOM_PATTERN_LENGTH) {
69
+ problems.push({ pattern: source.slice(0, 60), reason: `longer than ${MAX_CUSTOM_PATTERN_LENGTH} characters` });
70
+ continue;
71
+ }
72
+ if (hasNestedQuantifier(source)) {
73
+ problems.push({
74
+ pattern: source,
75
+ reason: "repeats a group that already repeats, which can take exponential time to match"
76
+ });
77
+ continue;
78
+ }
79
+ let compiled;
80
+ try {
81
+ compiled = new RegExp(source, "g");
82
+ } catch (e) {
83
+ problems.push({ pattern: source, reason: e instanceof Error ? e.message : "is not a valid regular expression" });
84
+ continue;
85
+ }
86
+ if (matchesZeroWidth(compiled)) {
87
+ problems.push({
88
+ pattern: source,
89
+ reason: "matches the empty string, so it would replace every position in the text"
90
+ });
91
+ continue;
92
+ }
93
+ if (growsExponentially(compiled)) {
94
+ problems.push({
95
+ pattern: source,
96
+ reason: "its running time doubles as the text grows, which can stall the process on a short input"
97
+ });
98
+ continue;
99
+ }
100
+ patterns.push(compiled);
101
+ }
102
+ if (written.length > MAX_CUSTOM_PATTERNS) {
103
+ problems.push({
104
+ pattern: `(${written.length} entries)`,
105
+ reason: `only the first ${MAX_CUSTOM_PATTERNS} custom patterns are used`
106
+ });
107
+ }
108
+ customCache = { key, patterns, problems };
109
+ return { patterns, problems };
110
+ }
111
+ var STRICT_CANDIDATE = /[A-Za-z0-9+/_-]{24,}={0,2}/g;
112
+ function entropyBitsPerChar(s) {
113
+ const counts = /* @__PURE__ */ new Map();
114
+ for (const ch of s) counts.set(ch, (counts.get(ch) ?? 0) + 1);
115
+ let bits = 0;
116
+ for (const n of counts.values()) {
117
+ const p = n / s.length;
118
+ bits -= p * Math.log2(p);
119
+ }
120
+ return bits;
121
+ }
122
+ function characterClasses(s) {
123
+ let n = 0;
124
+ if (/[a-z]/.test(s)) n++;
125
+ if (/[A-Z]/.test(s)) n++;
126
+ if (/[0-9]/.test(s)) n++;
127
+ if (/[+/=_-]/.test(s)) n++;
128
+ return n;
129
+ }
130
+ function looksLikeCredential(s) {
131
+ return characterClasses(s) >= 3 && entropyBitsPerChar(s) >= 3.5;
132
+ }
133
+ var RECALL_TUNED_KIND = "generic_secret_assignment";
134
+ function matchesAnywhere(pattern, text) {
135
+ pattern.lastIndex = 0;
136
+ const hit = pattern.test(text);
137
+ pattern.lastIndex = 0;
138
+ return hit;
139
+ }
140
+ function matchesNonEmpty(compiled, text) {
141
+ compiled.lastIndex = 0;
142
+ for (const match of text.matchAll(compiled)) {
143
+ if (match[0].length > 0) return true;
144
+ }
145
+ return false;
146
+ }
147
+ function hasPreciseSecret(text, config = loadConfig()) {
148
+ for (const [kind, pattern] of SECRET_PATTERNS) {
149
+ if (kind === RECALL_TUNED_KIND) continue;
150
+ if (matchesAnywhere(pattern, text)) return true;
151
+ }
152
+ for (const custom of compileCustomPatterns(config.redaction.custom_patterns).patterns) {
153
+ if (matchesNonEmpty(custom, text)) return true;
154
+ }
155
+ if (config.redaction.strict) {
156
+ for (const candidate of text.match(STRICT_CANDIDATE) ?? []) {
157
+ if (looksLikeCredential(candidate)) return true;
158
+ }
159
+ }
160
+ return false;
161
+ }
162
+ function redactSecrets(text, config = loadConfig()) {
163
+ let count = 0;
164
+ let out = text;
165
+ for (const [kind, pattern] of SECRET_PATTERNS) {
166
+ out = out.replace(pattern, () => {
167
+ count++;
168
+ return `[REDACTED:${kind}]`;
169
+ });
170
+ }
171
+ for (const pattern of compileCustomPatterns(config.redaction.custom_patterns).patterns) {
172
+ out = out.replace(pattern, (match) => {
173
+ if (match.length === 0) return match;
174
+ count++;
175
+ return "[REDACTED:custom]";
176
+ });
177
+ }
178
+ if (config.redaction.strict) {
179
+ out = out.replace(STRICT_CANDIDATE, (candidate) => {
180
+ if (!looksLikeCredential(candidate)) return candidate;
181
+ count++;
182
+ return "[REDACTED:high_entropy]";
183
+ });
184
+ }
185
+ return { text: out, count };
186
+ }
187
+ var CONTROL_ESCAPES = new Map(
188
+ Array.from({ length: 32 }, (_, code) => {
189
+ const ch = String.fromCharCode(code);
190
+ return [ch, JSON.stringify(ch).slice(1, -1)];
191
+ })
192
+ );
193
+ var CONTROL_CHARACTER_OF_ESCAPE = new Map([...CONTROL_ESCAPES].map(([ch, escape]) => [escape, ch]));
194
+ var JSON_ESCAPE = /\\(?:u[0-9a-fA-F]{4}|[^u])/g;
195
+ var SURROGATE_ESCAPE = /^\\u[dD][89a-fA-F][0-9a-fA-F]{2}$/;
196
+ var DECODED_CHARACTER = /[\u0000-\u001f]|[\ud800-\udbff](?![\udc00-\udfff])|(?<![\ud800-\udbff])[\udc00-\udfff]/g;
197
+ function decodeEscape(escape) {
198
+ return CONTROL_CHARACTER_OF_ESCAPE.get(escape) ?? (SURROGATE_ESCAPE.test(escape) ? String.fromCharCode(Number.parseInt(escape.slice(2), 16)) : escape);
199
+ }
200
+ function redactSerializedJson(json) {
201
+ const result = redactSecrets(json.replace(JSON_ESCAPE, decodeEscape));
202
+ return { text: result.text.replace(DECODED_CHARACTER, (ch) => CONTROL_ESCAPES.get(ch) ?? JSON.stringify(ch).slice(1, -1)), count: result.count };
203
+ }
204
+
205
+ export {
206
+ countRedactionPlaceholders,
207
+ compileCustomPatterns,
208
+ hasPreciseSecret,
209
+ redactSecrets,
210
+ redactSerializedJson
211
+ };
@@ -10,13 +10,14 @@ import {
10
10
  stripMultilineStringSpan,
11
11
  stripNestedBlockCommentSpan,
12
12
  stripStringLiterals
13
- } from "./token-goat-chunk-M56BWPBN.mjs";
13
+ } from "./token-goat-chunk-VL3YIFHZ.mjs";
14
14
  import {
15
15
  init_define_import_meta_env
16
16
  } from "./token-goat-chunk-A37V4PBF.mjs";
17
17
 
18
18
  // src/languages/swift.ts
19
19
  init_define_import_meta_env();
20
+ var SWIFT_STRIP = { swiftInterpolation: true };
20
21
  var IDENT_START = "A-Za-z_\\u00C0-\\uFFFF";
21
22
  var IDENT_CONT = "A-Za-z0-9_\\u00C0-\\uFFFF";
22
23
  var IDENT = `(?:\`[^\`]+\`|[${IDENT_START}][${IDENT_CONT}]*)`;
@@ -134,7 +135,7 @@ function extractSwift(content, filePath) {
134
135
  const line = stripLineComment(blockStripped).trimEnd();
135
136
  const stripped = line.trim();
136
137
  if (!stripped) {
137
- const braceLine2 = stripRegexLiterals(stripStringLiterals(line));
138
+ const braceLine2 = stripRegexLiterals(stripStringLiterals(line, SWIFT_STRIP));
138
139
  braceDepth += (braceLine2.match(/\{/g) ?? []).length - (braceLine2.match(/\}/g) ?? []).length;
139
140
  continue;
140
141
  }
@@ -172,7 +173,7 @@ function extractSwift(content, filePath) {
172
173
  } else if (frame === null && braceDepth === 0) {
173
174
  pushMembers(line, void 0, lineNum, stripped.slice(0, 200));
174
175
  }
175
- const braceLine = stripRegexLiterals(stripStringLiterals(line));
176
+ const braceLine = stripRegexLiterals(stripStringLiterals(line, SWIFT_STRIP));
176
177
  for (const ch of braceLine) {
177
178
  if (ch === "{") {
178
179
  braceDepth++;
@@ -0,0 +1,313 @@
1
+ import { createRequire as __cjsRequire } from 'node:module';
2
+ const require = __cjsRequire(import.meta.url);
3
+ import {
4
+ copyFromSharedCache,
5
+ downloadPinned
6
+ } from "./token-goat-chunk-PD5VKH46.mjs";
7
+ import "./token-goat-chunk-SMVRN2HU.mjs";
8
+ import {
9
+ loadConfig
10
+ } from "./token-goat-chunk-7IN2MKDS.mjs";
11
+ import "./token-goat-chunk-U4N3BN2W.mjs";
12
+ import {
13
+ registerReset
14
+ } from "./token-goat-chunk-YZAAZU2S.mjs";
15
+ import "./token-goat-chunk-IVE6U7KV.mjs";
16
+ import {
17
+ atomicWriteText,
18
+ ensureDirSync
19
+ } from "./token-goat-chunk-GOLEOXZP.mjs";
20
+ import "./token-goat-chunk-AM5V6GSX.mjs";
21
+ import "./token-goat-chunk-FNFBKLRD.mjs";
22
+ import {
23
+ ensureDataDirPrivate
24
+ } from "./token-goat-chunk-VES7EL7O.mjs";
25
+ import {
26
+ init_define_import_meta_env
27
+ } from "./token-goat-chunk-A37V4PBF.mjs";
28
+
29
+ // src/embed_runtime_web.ts
30
+ init_define_import_meta_env();
31
+ import { createHash } from "node:crypto";
32
+ import * as fs from "node:fs";
33
+ import { createRequire } from "node:module";
34
+ import * as path from "node:path";
35
+ import { fileURLToPath, pathToFileURL } from "node:url";
36
+ import { createGunzip } from "node:zlib";
37
+ var _require = createRequire(import.meta.url);
38
+ var ORT_WEB_TARBALL = {
39
+ name: "onnxruntime-web-1.30.0.tgz",
40
+ sha256: "d2228df7e4616bc3348bf504ee888f3bec43789a273f0a63f3e68d203ce3bf71",
41
+ bytes: 33106585
42
+ };
43
+ var ORT_WEB_GLUE = {
44
+ name: "ort-wasm-simd-threaded.mjs",
45
+ sha256: "e13f7f94fc51b4ca72b12faeb1ee95f4ace6dfbc8939bc718aabdc0a27c4299b",
46
+ bytes: 24381
47
+ };
48
+ var TARBALL_MEMBER = "package/dist/ort-wasm-simd-threaded.wasm";
49
+ var BACKEND_START_FAILED = "no available backend found";
50
+ var _webLoad = null;
51
+ var _inFlightWasm = null;
52
+ var _placeFailures = /* @__PURE__ */ new WeakSet();
53
+ function readVerified(filePath, file) {
54
+ const info = fs.lstatSync(filePath, { throwIfNoEntry: false });
55
+ if (!info?.isFile() || info.size !== file.bytes) return null;
56
+ const bytes = fs.readFileSync(filePath);
57
+ if (bytes.length !== file.bytes) return null;
58
+ return createHash("sha256").update(bytes).digest("hex") === file.sha256 ? bytes : null;
59
+ }
60
+ function ensureWasmBinary(host) {
61
+ if (_inFlightWasm === null) {
62
+ _inFlightWasm = (async () => {
63
+ try {
64
+ return await placeWasmBinary(host);
65
+ } finally {
66
+ _inFlightWasm = null;
67
+ }
68
+ })();
69
+ }
70
+ return _inFlightWasm;
71
+ }
72
+ async function placeWasmBinary(host) {
73
+ ensureDataDirPrivate();
74
+ const { dir, version, wasm } = host;
75
+ const target = path.join(dir, wasm.name);
76
+ const cached = readVerified(target, wasm);
77
+ if (cached) return cached;
78
+ fs.rmSync(target, { force: true });
79
+ ensureDirSync(dir);
80
+ const shared = host.sharedDir;
81
+ if (shared && await copyFromSharedCache(shared, wasm, target)) {
82
+ const copied = readVerified(target, wasm);
83
+ if (copied) return copied;
84
+ }
85
+ if (loadConfig().network.offline) {
86
+ throw new Error(
87
+ `Offline mode is on (network.offline): refusing to download the WebAssembly inference runtime (onnxruntime-web ${version}). Copy ${wasm.name} from that package's dist/ into ${dir} on a connected machine to use semantic search here.`
88
+ );
89
+ }
90
+ console.warn(
91
+ `Downloading the embedding runtime, once (onnxruntime-web ${version} from registry.npmjs.org, ${Math.round(ORT_WEB_TARBALL.bytes / 1024 / 1024)} MB, keeping its ${Math.round(wasm.bytes / 1024 / 1024)} MB ${wasm.name}) into ${dir}`
92
+ );
93
+ const archive = path.join(dir, ORT_WEB_TARBALL.name);
94
+ try {
95
+ await downloadPinned(tarballUrl(), ORT_WEB_TARBALL, archive);
96
+ await extractTarMember(archive, TARBALL_MEMBER, wasm, target);
97
+ } finally {
98
+ fs.rmSync(archive, { force: true, maxRetries: 20, retryDelay: 25 });
99
+ }
100
+ if (shared) host.publish(shared, wasm, target);
101
+ const placed = readVerified(target, wasm);
102
+ if (!placed) throw new Error(`${target} did not verify after extraction`);
103
+ return placed;
104
+ }
105
+ function tarballUrl() {
106
+ return `https://registry.npmjs.org/onnxruntime-web/-/${ORT_WEB_TARBALL.name}`;
107
+ }
108
+ var ExactReader = class {
109
+ constructor(source) {
110
+ this.source = source;
111
+ }
112
+ source;
113
+ chunks = [];
114
+ buffered = 0;
115
+ ended = false;
116
+ async fill(n) {
117
+ while (this.buffered < n && !this.ended) {
118
+ const next = await this.source.next();
119
+ if (next.done === true) {
120
+ this.ended = true;
121
+ break;
122
+ }
123
+ this.chunks.push(next.value);
124
+ this.buffered += next.value.length;
125
+ }
126
+ }
127
+ /** Exactly `n` bytes, or fewer only when the input ends first. */
128
+ async read(n) {
129
+ await this.fill(n);
130
+ const all = this.chunks.length === 1 ? this.chunks[0] : Buffer.concat(this.chunks);
131
+ const out = all.subarray(0, n);
132
+ const rest = all.subarray(out.length);
133
+ this.chunks = rest.length > 0 ? [rest] : [];
134
+ this.buffered = rest.length;
135
+ return out;
136
+ }
137
+ /** Discard exactly `n` bytes without holding them, or throw if the input ends first. */
138
+ async skip(n) {
139
+ let left = n;
140
+ while (left > 0) {
141
+ if (this.buffered === 0) await this.fill(1);
142
+ const head = this.chunks[0];
143
+ if (head === void 0) throw new Error("archive ended inside an entry");
144
+ if (head.length <= left) {
145
+ this.chunks.shift();
146
+ this.buffered -= head.length;
147
+ left -= head.length;
148
+ } else {
149
+ this.chunks[0] = head.subarray(left);
150
+ this.buffered -= left;
151
+ left = 0;
152
+ }
153
+ }
154
+ }
155
+ };
156
+ function tarString(block, start, length) {
157
+ const field = block.subarray(start, start + length);
158
+ const end = field.indexOf(0);
159
+ return field.subarray(0, end === -1 ? field.length : end).toString("utf8");
160
+ }
161
+ function tarOctal(block, start, length) {
162
+ if ((block[start] & 128) !== 0) throw new Error("tar header uses a base-256 number, which this reader does not support");
163
+ const text = tarString(block, start, length).trim();
164
+ const value = text === "" ? 0 : Number.parseInt(text, 8);
165
+ if (!Number.isSafeInteger(value) || value < 0) throw new Error(`tar header holds an invalid number: ${JSON.stringify(text)}`);
166
+ return value;
167
+ }
168
+ function paxPath(data) {
169
+ let at = 0;
170
+ let found = null;
171
+ while (at < data.length) {
172
+ const space = data.indexOf(32, at);
173
+ if (space === -1) break;
174
+ const length = Number.parseInt(data.subarray(at, space).toString("latin1"), 10);
175
+ if (!Number.isSafeInteger(length) || length <= 0 || at + length > data.length) break;
176
+ const record = data.subarray(space + 1, at + length - 1).toString("utf8");
177
+ const eq = record.indexOf("=");
178
+ if (eq !== -1 && record.slice(0, eq) === "path") found = record.slice(eq + 1);
179
+ at += length;
180
+ }
181
+ return found;
182
+ }
183
+ async function extractTarMember(archive, member, file, target) {
184
+ const raw = fs.createReadStream(archive);
185
+ const gunzip = createGunzip();
186
+ raw.on("error", (e) => gunzip.destroy(e));
187
+ raw.pipe(gunzip);
188
+ const reader = new ExactReader(gunzip[Symbol.asyncIterator]());
189
+ try {
190
+ let nextName = null;
191
+ for (; ; ) {
192
+ const header = await reader.read(512);
193
+ if (header.length < 512) throw new Error(`${archive} ended before its end-of-archive marker, without ${member}`);
194
+ if (header.every((b) => b === 0)) throw new Error(`${archive} has no ${member}`);
195
+ let sum = 0;
196
+ for (let i = 0; i < 512; i++) sum += i >= 148 && i < 156 ? 32 : header[i];
197
+ if (sum !== tarOctal(header, 148, 8)) throw new Error(`${archive} has a tar header with a bad checksum`);
198
+ const size = tarOctal(header, 124, 12);
199
+ const padding = (512 - size % 512) % 512;
200
+ const type = header[156] === 0 ? "0" : String.fromCharCode(header[156]);
201
+ let name = tarString(header, 0, 100);
202
+ if (header.subarray(257, 263).toString("latin1") === "ustar\0") {
203
+ const prefix = tarString(header, 345, 155);
204
+ if (prefix !== "") name = `${prefix}/${name}`;
205
+ }
206
+ if (nextName !== null) {
207
+ name = nextName;
208
+ nextName = null;
209
+ }
210
+ if (type === "x" || type === "L") {
211
+ const data = await reader.read(size);
212
+ if (data.length < size) throw new Error(`${archive} ended inside an extended header`);
213
+ await reader.skip(padding);
214
+ nextName = type === "x" ? paxPath(data) : tarString(data, 0, data.length);
215
+ continue;
216
+ }
217
+ if ((type === "0" || type === "7") && name === member) {
218
+ if (size !== file.bytes) throw new Error(`${member} is ${size} bytes in ${archive}, expected the pinned ${file.bytes}`);
219
+ const data = await reader.read(size);
220
+ if (data.length !== file.bytes) throw new Error(`${archive} ended inside ${member}`);
221
+ const digest = createHash("sha256").update(data).digest("hex");
222
+ if (digest !== file.sha256) throw new Error(`${member} has sha256 ${digest}, expected the pinned ${file.sha256}`);
223
+ const temp = `${target}.${process.pid}.partial`;
224
+ try {
225
+ fs.writeFileSync(temp, data);
226
+ fs.renameSync(temp, target);
227
+ } catch (e) {
228
+ fs.rmSync(temp, { force: true, maxRetries: 20, retryDelay: 25 });
229
+ throw e;
230
+ }
231
+ return;
232
+ }
233
+ await reader.skip(size + padding);
234
+ }
235
+ } finally {
236
+ raw.destroy();
237
+ gunzip.destroy();
238
+ }
239
+ }
240
+ function verifiedGlueUrl(version) {
241
+ const beside = fileURLToPath(new URL(`./${ORT_WEB_GLUE.name}`, import.meta.url));
242
+ const file = fs.existsSync(beside) ? beside : _require.resolve(`onnxruntime-web/${ORT_WEB_GLUE.name}`);
243
+ if (readVerified(file, ORT_WEB_GLUE) === null) {
244
+ throw new Error(`${file} is not the ${ORT_WEB_GLUE.name} onnxruntime-web ${version} ships (pinned sha256 ${ORT_WEB_GLUE.sha256})`);
245
+ }
246
+ return pathToFileURL(file).href;
247
+ }
248
+ function loadWebRuntime(threads, host) {
249
+ if (_webLoad !== null) return _webLoad;
250
+ const pending = (async () => {
251
+ const ort = await import("./token-goat-chunk-EXKGNHEG.mjs");
252
+ if (ort.env.versions.web !== host.version) {
253
+ throw new Error(`the bundled onnxruntime-web is ${ort.env.versions.web ?? "unknown"}, but its binary is pinned for ${host.version}`);
254
+ }
255
+ const glue = verifiedGlueUrl(host.version);
256
+ const binary = await ensureWasmBinary(host).catch((e) => {
257
+ if (typeof e === "object" && e !== null) _placeFailures.add(e);
258
+ throw e;
259
+ });
260
+ ort.env.wasm.wasmBinary = binary;
261
+ ort.env.wasm.wasmPaths = { mjs: glue };
262
+ ort.env.wasm.numThreads = threads;
263
+ return ort;
264
+ })();
265
+ _webLoad = pending;
266
+ pending.catch(() => {
267
+ if (_webLoad === pending) _webLoad = null;
268
+ });
269
+ return pending;
270
+ }
271
+ async function createWebSession(modelPath, threads, host) {
272
+ let ort;
273
+ try {
274
+ ort = await loadWebRuntime(threads, host);
275
+ } catch (e) {
276
+ if (typeof e === "object" && e !== null && _placeFailures.has(e)) throw host.failed(e, false);
277
+ throw startFailed(e, host);
278
+ }
279
+ let session;
280
+ try {
281
+ session = await ort.InferenceSession.create(modelPath, { intraOpNumThreads: threads, interOpNumThreads: 1 });
282
+ } catch (e) {
283
+ if (e instanceof Error && e.message.startsWith(BACKEND_START_FAILED)) throw startFailed(e, host);
284
+ throw e;
285
+ }
286
+ try {
287
+ const recorded = JSON.parse(fs.readFileSync(host.startFailure.path, "utf8"));
288
+ if (recorded.key === host.startFailure.key) fs.rmSync(host.startFailure.path, { force: true });
289
+ } catch {
290
+ }
291
+ return { session, Tensor: ort.Tensor };
292
+ }
293
+ function startFailed(e, host) {
294
+ const message = e instanceof Error ? e.message : String(e);
295
+ try {
296
+ ensureDirSync(path.dirname(host.startFailure.path));
297
+ atomicWriteText(host.startFailure.path, JSON.stringify({ key: host.startFailure.key, message, at: Date.now() }));
298
+ } catch {
299
+ return host.failed(e, false);
300
+ }
301
+ return host.failed(e, true);
302
+ }
303
+ registerReset(() => {
304
+ _webLoad = null;
305
+ _inFlightWasm = null;
306
+ });
307
+ export {
308
+ ORT_WEB_GLUE,
309
+ ORT_WEB_TARBALL,
310
+ createWebSession,
311
+ ensureWasmBinary,
312
+ extractTarMember
313
+ };
@@ -0,0 +1,35 @@
1
+ import { createRequire as __cjsRequire } from 'node:module';
2
+ const require = __cjsRequire(import.meta.url);
3
+ import {
4
+ detectHarness
5
+ } from "./token-goat-chunk-U4N3BN2W.mjs";
6
+ import {
7
+ init_define_import_meta_env
8
+ } from "./token-goat-chunk-A37V4PBF.mjs";
9
+
10
+ // src/delivery_cap.ts
11
+ init_define_import_meta_env();
12
+ var CLAUDE_CODE_BASH_OUTPUT_CAP_BYTES = 2e4;
13
+ var CLAUDE_CODE_PERSISTED_PREVIEW_BYTES = 2048;
14
+ function bashOutputCapBytes(harness = detectHarness()) {
15
+ return harness === "claudecode" ? CLAUDE_CODE_BASH_OUTPUT_CAP_BYTES : null;
16
+ }
17
+ function clipToDeliveryCap(text, reserveBytes) {
18
+ const cap = bashOutputCapBytes();
19
+ const room = cap === null ? null : cap - reserveBytes;
20
+ if (room === null || room <= 0 || Buffer.byteLength(text, "utf-8") <= room) return { text, clipped: false };
21
+ const sliced = Buffer.from(text, "utf-8").subarray(0, room).toString("utf-8");
22
+ const lastNewline = sliced.lastIndexOf("\n");
23
+ return { text: lastNewline > 0 ? sliced.slice(0, lastNewline) : sliced, clipped: true };
24
+ }
25
+ function deliveredOutputBytes(originalBytes, harness) {
26
+ const cap = bashOutputCapBytes(harness);
27
+ if (cap === null) return Math.max(0, originalBytes);
28
+ if (originalBytes <= cap) return Math.max(0, originalBytes);
29
+ return CLAUDE_CODE_PERSISTED_PREVIEW_BYTES;
30
+ }
31
+
32
+ export {
33
+ clipToDeliveryCap,
34
+ deliveredOutputBytes
35
+ };