@humain/humain-code 0.8.1 → 0.8.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +36 -0
- package/dist/bundle/chunks/{chunk-E7OBH44W.js → chunk-2XD7TLKB.js} +6 -6
- package/dist/bundle/chunks/{chunk-3CGMVKHA.js → chunk-3E37CJCE.js} +1 -1
- package/dist/bundle/chunks/{chunk-ROFZVEFN.js → chunk-4GB7A76U.js} +77 -72
- package/dist/bundle/chunks/{chunk-P2Y2H7SD.js → chunk-6JTCRCNF.js} +2 -2
- package/dist/bundle/chunks/{chunk-6TTMNQXI.js → chunk-7LSTTCSC.js} +145 -120
- package/dist/bundle/chunks/{chunk-QRRVZYTG.js → chunk-AW24RHGJ.js} +2 -2
- package/dist/bundle/chunks/{chunk-7X6DNT45.js → chunk-B3ZLWVDA.js} +8 -6
- package/dist/bundle/chunks/{chunk-APNPBT7Y.js → chunk-BRSLXHED.js} +1 -1
- package/dist/bundle/chunks/{chunk-KONLZKPL.js → chunk-E4VUW4RI.js} +1 -1
- package/dist/bundle/chunks/{chunk-NICPFMOP.js → chunk-JKX5EGOT.js} +1 -1
- package/dist/bundle/chunks/{chunk-D3KYOSQY.js → chunk-JSHKS7VH.js} +1 -1
- package/dist/bundle/chunks/{chunk-SXOIQWNX.js → chunk-JX6YIPNK.js} +1 -1
- package/dist/bundle/chunks/{chunk-WBSGWISD.js → chunk-M5TVWJ5T.js} +5 -4
- package/dist/bundle/chunks/{chunk-XZ7FTBXS.js → chunk-MUN4ZZZP.js} +1189 -1195
- package/dist/bundle/chunks/{chunk-CQ2CE3RB.js → chunk-QFDZEUFU.js} +2 -2
- package/dist/bundle/chunks/{chunk-DD5UT56Y.js → chunk-R2KD2HFT.js} +67 -66
- package/dist/bundle/chunks/chunk-S2US54IU.js +37 -0
- package/dist/bundle/chunks/{chunk-IMUFBWEK.js → chunk-T2ZGMEMV.js} +42 -41
- package/dist/bundle/chunks/{chunk-FQ4KS5S4.js → chunk-UZOIHLNU.js} +1 -1
- package/dist/bundle/chunks/{chunk-6YVORXTX.js → chunk-VSXVZVBE.js} +253 -232
- package/dist/bundle/chunks/{chunk-P42E6YY6.js → chunk-ZAHVC5V2.js} +206 -194
- package/dist/bundle/chunks/{chunk-DJG2WUNM.js → chunk-ZSWU5KKA.js} +1 -1
- package/dist/bundle/chunks/{compat-SRCNS6OQ.js → compat-4ILE5BEC.js} +1 -1
- package/dist/bundle/chunks/{dist-TRAK7EXI.js → dist-I6CI3CG5.js} +6 -6
- package/dist/bundle/chunks/{dist-4OMLHRJE.js → dist-NXHRL2KY.js} +1 -1
- package/dist/bundle/chunks/{easter-egg-3d-VVUF3C3X.js → easter-egg-3d-VZC5WOYV.js} +1 -1
- package/dist/bundle/chunks/{entry-SRYLSS5P.js → entry-6XDR2IDE.js} +1 -1
- package/dist/bundle/chunks/{execute-I3WGGPWL.js → execute-6MEJJF2T.js} +2 -2
- package/dist/bundle/chunks/{flow-implementer-4KO3Q4B5.js → flow-implementer-XOP4MG5X.js} +4 -4
- package/dist/bundle/chunks/{inprocess-TOBRVK4C.js → inprocess-MBKFGDM2.js} +4 -4
- package/dist/bundle/chunks/{interactive-mode-BJJKPBXD.js → interactive-mode-3322RQEH.js} +2 -2
- package/dist/bundle/chunks/{session-picker-4JQEGLDD.js → session-picker-EYKCMFQR.js} +1 -1
- package/dist/bundle/chunks/{startup-ui-AKTA4NDP.js → startup-ui-7ODOR34R.js} +2 -2
- package/dist/bundle/chunks/{trace-command-7ORDQ3JS.js → trace-command-VM7FBWPE.js} +4 -4
- package/dist/bundle/chunks/{virtual-modules-3CT5BMBA.js → virtual-modules-47MGUPYN.js} +8 -8
- package/dist/bundle/cli-runtime.js +3 -3
- package/dist/bundle/index.js +8 -8
- package/dist/bundle/rpc-entry.js +3 -3
- package/dist/coordination/adapter/delivery.d.ts +27 -0
- package/dist/coordination/adapter/delivery.d.ts.map +1 -1
- package/dist/coordination/adapter/delivery.js +164 -4
- package/dist/coordination/adapter/delivery.js.map +1 -1
- package/dist/coordination/adapter/index.d.ts.map +1 -1
- package/dist/coordination/adapter/index.js +31 -5
- package/dist/coordination/adapter/index.js.map +1 -1
- package/dist/coordination/adapter/presence.d.ts +5 -0
- package/dist/coordination/adapter/presence.d.ts.map +1 -1
- package/dist/coordination/adapter/presence.js +25 -3
- package/dist/coordination/adapter/presence.js.map +1 -1
- package/dist/coordination/adapter/question-routing.d.ts +7 -0
- package/dist/coordination/adapter/question-routing.d.ts.map +1 -0
- package/dist/coordination/adapter/question-routing.js +40 -0
- package/dist/coordination/adapter/question-routing.js.map +1 -0
- package/dist/coordination/adapter/receipts.d.ts +7 -0
- package/dist/coordination/adapter/receipts.d.ts.map +1 -1
- package/dist/coordination/adapter/receipts.js +25 -2
- package/dist/coordination/adapter/receipts.js.map +1 -1
- package/dist/coordination/adapter/tool.d.ts +19 -3
- package/dist/coordination/adapter/tool.d.ts.map +1 -1
- package/dist/coordination/adapter/tool.js +93 -19
- package/dist/coordination/adapter/tool.js.map +1 -1
- package/dist/coordination/client/client.d.ts +2 -2
- package/dist/coordination/client/client.d.ts.map +1 -1
- package/dist/coordination/client/client.js +4 -0
- package/dist/coordination/client/client.js.map +1 -1
- package/dist/coordination/transport/protocol.d.ts.map +1 -1
- package/dist/coordination/transport/protocol.js +23 -0
- package/dist/coordination/transport/protocol.js.map +1 -1
- package/dist/coordination/transport/types.d.ts +11 -1
- package/dist/coordination/transport/types.d.ts.map +1 -1
- package/dist/coordination/transport/types.js.map +1 -1
- package/dist/core/model-resolver.js +2 -2
- package/dist/core/model-resolver.js.map +1 -1
- package/dist/core/model-runtime.d.ts.map +1 -1
- package/dist/core/model-runtime.js +14 -8
- package/dist/core/model-runtime.js.map +1 -1
- package/dist/core/oauth-account-pool.d.ts +14 -0
- package/dist/core/oauth-account-pool.d.ts.map +1 -1
- package/dist/core/oauth-account-pool.js +166 -14
- package/dist/core/oauth-account-pool.js.map +1 -1
- package/dist/core/run-outcome.d.ts +1 -1
- package/dist/core/run-outcome.d.ts.map +1 -1
- package/dist/core/run-outcome.js +2 -2
- package/dist/core/run-outcome.js.map +1 -1
- package/dist/core/run-preflight.d.ts.map +1 -1
- package/dist/core/run-preflight.js +15 -8
- package/dist/core/run-preflight.js.map +1 -1
- package/dist/core/settings-manager.d.ts +4 -0
- package/dist/core/settings-manager.d.ts.map +1 -1
- package/dist/core/settings-manager.js +17 -0
- package/dist/core/settings-manager.js.map +1 -1
- package/dist/core/settings-schema.d.ts +2 -0
- package/dist/core/settings-schema.d.ts.map +1 -1
- package/dist/core/settings-schema.js +10 -0
- package/dist/core/settings-schema.js.map +1 -1
- package/dist/extensions/usage/index.js +5 -5
- package/dist/extensions/usage/index.js.map +1 -1
- package/dist/humain/gateway/client.d.ts.map +1 -1
- package/dist/humain/gateway/client.js +36 -9
- package/dist/humain/gateway/client.js.map +1 -1
- package/dist/humain/gateway/http.d.ts.map +1 -1
- package/dist/humain/gateway/http.js +26 -6
- package/dist/humain/gateway/http.js.map +1 -1
- package/dist/humain/gateway/provider.d.ts.map +1 -1
- package/dist/humain/gateway/provider.js +9 -2
- package/dist/humain/gateway/provider.js.map +1 -1
- package/dist/humain/hcode/facade.d.ts +12 -1
- package/dist/humain/hcode/facade.d.ts.map +1 -1
- package/dist/humain/hcode/facade.js +35 -8
- package/dist/humain/hcode/facade.js.map +1 -1
- package/dist/humain/hcode/login-copy.d.ts.map +1 -1
- package/dist/humain/hcode/login-copy.js +10 -0
- package/dist/humain/hcode/login-copy.js.map +1 -1
- package/dist/main.d.ts.map +1 -1
- package/dist/main.js +2 -0
- package/dist/main.js.map +1 -1
- package/dist/modes/interactive/components/settings-selector.d.ts +6 -0
- package/dist/modes/interactive/components/settings-selector.d.ts.map +1 -1
- package/dist/modes/interactive/components/settings-selector.js +26 -0
- package/dist/modes/interactive/components/settings-selector.js.map +1 -1
- package/dist/modes/interactive/components/status-indicator.d.ts +35 -1
- package/dist/modes/interactive/components/status-indicator.d.ts.map +1 -1
- package/dist/modes/interactive/components/status-indicator.js +179 -3
- package/dist/modes/interactive/components/status-indicator.js.map +1 -1
- package/dist/modes/interactive/components/working-indicator-engine.d.ts +32 -0
- package/dist/modes/interactive/components/working-indicator-engine.d.ts.map +1 -0
- package/dist/modes/interactive/components/working-indicator-engine.js +112 -0
- package/dist/modes/interactive/components/working-indicator-engine.js.map +1 -0
- package/dist/modes/interactive/fullscreen.d.ts +13 -0
- package/dist/modes/interactive/fullscreen.d.ts.map +1 -0
- package/dist/modes/interactive/fullscreen.js +25 -0
- package/dist/modes/interactive/fullscreen.js.map +1 -0
- package/dist/modes/interactive/interactive-mode.d.ts +4 -1
- package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
- package/dist/modes/interactive/interactive-mode.js +117 -19
- package/dist/modes/interactive/interactive-mode.js.map +1 -1
- package/dist/modes/interactive/theme/humain-dark.json +5 -4
- package/dist/modes/interactive/theme/humain-light.json +6 -5
- package/docs/cli.md +6 -0
- package/docs/coordination.md +16 -4
- package/docs/development.md +7 -0
- package/docs/environment-variables.md +2 -1
- package/docs/providers.md +19 -5
- package/docs/settings.md +20 -0
- package/docs/usage.md +2 -0
- package/npm-shrinkwrap.json +2 -2
- package/package.json +1 -1
- package/schemas/settings.schema.json +29 -0
- package/dist/bundle/chunks/chunk-UEW6TUSP.js +0 -36
- package/dist/bundle/chunks/chunk-YPZPCHNV.js +0 -3
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url);
|
|
2
|
-
import{FirstTimeSetupComponent,getDefaultThemeName}from"./chunk-
|
|
3
|
-
setRegisteredThemes,setTerminalColors,setTheme}from"./chunk-
|
|
2
|
+
import{FirstTimeSetupComponent,getDefaultThemeName}from"./chunk-JX6YIPNK.js";import{ExtensionInputComponent,ExtensionSelectorComponent,requestTerminalColors}from"./chunk-ZSWU5KKA.js";import{KeybindingsManager,areExperimentalFeaturesEnabled,flushStdout}from"./chunk-UZOIHLNU.js";import{DefaultPackageManager,SettingsManager,resolveHcodeEnvironment}from"./chunk-T2ZGMEMV.js";import{DEFAULT_THEME_NAME,getTerminalTheme,initTheme,loadThemeFromPath,markTerminalColorsPending,resolveThemeSetting,
|
|
3
|
+
setRegisteredThemes,setTerminalColors,setTheme}from"./chunk-E4VUW4RI.js";import{ProcessTerminal,TuiMainScreen,setCapabilityOverrides,setKeybindings}from"./chunk-M5TVWJ5T.js";import{APP_NAME,CONFIG_DIR_NAME,ENV_AGENT_DIR,FIRST_TIME_SETUP_ENABLED,PACKAGE_NAME,getAgentDir,getSettingsPath,stripBom}from"./chunk-VFLVWPLZ.js";import{existsSync,readFileSync}from"fs";var OFFICIAL_PACKAGE_NAME="@humain/humain-code",OFFICIAL_APP_NAME="humain-terminal",OFFICIAL_CONFIG_DIR_NAME=".humain-terminal";function isOfficialDistribution({packageName,appName,configDirName}){return packageName===OFFICIAL_PACKAGE_NAME&&appName===OFFICIAL_APP_NAME&&configDirName===OFFICIAL_CONFIG_DIR_NAME}function loadThemes(resources){let themes=[],seen=new Set;for(let resource of resources)if(resource.enabled)try{let loadedTheme=loadThemeFromPath(resource.path);if(loadedTheme.name){if(seen.
|
|
4
4
|
has(loadedTheme.name))continue;seen.add(loadedTheme.name)}themes.push(loadedTheme)}catch{}return themes}async function loadStartupThemes(settingsManager){let globalSettingsManager=SettingsManager.inMemory(settingsManager.getGlobalSettings(),{projectTrusted:!1}),resolvedPaths=await new DefaultPackageManager({cwd:process.cwd(),agentDir:getAgentDir(),settingsManager:globalSettingsManager}).resolve(async()=>"skip");return loadThemes(resolvedPaths.themes)}async function createStartupTui(settingsManager){
|
|
5
5
|
setCapabilityOverrides(settingsManager.getTerminalCapabilityOverrides()),setRegisteredThemes(await loadStartupThemes(settingsManager)),markTerminalColorsPending(),initTheme(resolveThemeSetting(settingsManager.getThemeSetting(),getTerminalTheme())??DEFAULT_THEME_NAME),setKeybindings(KeybindingsManager.create());let ui=new TuiMainScreen(new ProcessTerminal,settingsManager.getShowHardwareCursor(),getAgentDir());return ui.setClearOnShrink(settingsManager.getClearOnShrink()),ui}function startStartupTui(ui,settingsManager){
|
|
6
6
|
ui.start();let themeSetting=settingsManager.getThemeSetting();queryStartupTerminalColors(ui,()=>{setTheme(resolveThemeSetting(themeSetting,getTerminalTheme())??DEFAULT_THEME_NAME)})}function queryStartupTerminalColors(ui,onColors){requestTerminalColors(ui,colors=>{setTerminalColors(colors),onColors(),ui.invalidate(),ui.requestRender()})}async function clearStartupTui(ui){ui.clear(),ui.requestRender(),await new Promise(resolve=>setTimeout(resolve,25))}function shouldRunFirstTimeSetupForDistribution(metadata){
|
|
@@ -50,7 +50,69 @@ this.path);await mkdir2(directory,{recursive:!0,mode:448});let temp=join2(direct
|
|
|
50
50
|
`,"utf8"),await handle.sync()}catch(error){throw await handle.close().catch(()=>{}),await unlink2(temp).catch(()=>{}),error}await handle.close();try{await chmod2(temp,384),await rename(temp,this.path)}catch(error){throw await unlink2(temp).catch(()=>{}),error}}},systemTraceCredentialProbes={platform:process.platform,env:process.env,findExecutable(name){let candidates=name.startsWith("/")?[name]:(process.env.PATH??"").split(delimiter).filter(entry=>entry.startsWith("/")).map(entry=>join2(entry,name));
|
|
51
51
|
for(let candidate of candidates)try{if(!existsSync(candidate))continue;return accessSync(candidate,constants2.X_OK),candidate}catch{}}};function createDefaultTraceCredentialStore(options={}){let probes=options.probes??systemTraceCredentialProbes,run=options.run??spawnCommand;if(probes.platform==="darwin"){let security=probes.findExecutable("/usr/bin/security");if(security)return new KeychainTraceCredentialStore(run,security,options.lockDirectory)}else if(probes.platform==="linux"){let secretTool=probes.
|
|
52
52
|
findExecutable("secret-tool");if(secretTool&&probes.env.DBUS_SESSION_BUS_ADDRESS)return new SecretServiceTraceCredentialStore(secretTool,run,options.lockDirectory)}if(options.allowFileStore)return new FileTraceCredentialStore(options.filePath);throw new TraceCredentialStoreError("No OS credential store is available for trace client tokens (macOS Keychain or Linux Secret Service via secret-tool). To store them in a 0600 file under the agent directory instead, opt in explicitly with allowFileStore\
|
|
53
|
-
.")}
|
|
53
|
+
.")}var TRACE_REDACTION_POLICY_ID="cli-default",TRACE_REDACTION_POLICY_VERSION="1",REDACTED="[REDACTED]",TRUNCATED="[TRUNCATED]",CIRCULAR="[Circular]",DEFAULT_MAX_NODES=1e5,DEFAULT_MAX_DEPTH=DH_PAYLOAD_MAX_DEPTH,MAX_SECRETS=256,MAX_SECRET_CHARS=1024*1024,MAX_TEXT_CHARS=8e6,MIN_SECRET_LENGTH=8,CAPACITY_EXCEEDED="redaction_capacity_exceeded",SENSITIVE_KEY_NAME=/^(?:authorization|proxy-authorization|cookie|set-cookie|password|passwd|pwd|secret|client[-_]?secret|token|access[-_]?token|refresh[-_]?token|id[-_]?token|api[-_ ]?key|x-api-key|private[-_]?key|credentials?|session|bearer|aws[-_]?secret[-_]?access[-_]?key)$/i,
|
|
54
|
+
SENSITIVE_ENV_NAME=/(KEY|TOKEN|SECRET|PASSWORD|CREDENTIAL|AUTH)/i,FORBIDDEN_KEYS=new Set(["__proto__","constructor","prototype"]),PATH_SEGMENT=/^[A-Za-z0-9_-]+$/,FIELD_PATH_MAX=256,SECRET_PATTERNS=[/-----BEGIN [A-Z ]*PRIVATE KEY-----[\s\S]*?(?:-----END [A-Z ]*PRIVATE KEY-----|$)/g,/\bBearer\s+[A-Za-z0-9._~+/=-]{8,}/gi,/\beyJ[A-Za-z0-9_-]{5,}\.[A-Za-z0-9_-]{5,}\.[A-Za-z0-9_-]*/g,/\b(?:sk-ant-[A-Za-z0-9_-]{16,}|sk-[A-Za-z0-9_-]{20,}|gh[pousr]_[A-Za-z0-9]{20,}|github_pat_[A-Za-z0-9_]{20,}|glpat-[A-Za-z0-9_-]{16,}|xox[abpr]-[A-Za-z0-9-]{10,}|A[KS]IA[0-9A-Z]{16}|AIza[0-9A-Za-z_-]{35})/g],
|
|
55
|
+
ASSIGNMENT_PATTERN=/(\b[A-Za-z0-9_-]{0,32}(?:password|passwd|pwd|secret|token|api[_-]?key|access[_-]?key|credential)[A-Za-z0-9_-]{0,32}["']?[ \t]*[=:][ \t]*)("[^"]*"|'[^']*'|[^\s"',;&]+)/gi;function isSensitiveKey(key){if(SENSITIVE_KEY_NAME.test(key))return!0;let segments=key.split(/[-_.\s]+|(?<=[a-z0-9])(?=[A-Z])/).filter(segment=>segment!=="").map(segment=>segment.toLowerCase());for(let start=1;start<segments.length&&start<8;start++)if(SENSITIVE_KEY_NAME.test(segments.slice(start).join("_")))return!0;
|
|
56
|
+
return!1}var SENSITIVE_WORDS="authorization|cookie|password|passwd|pwd|secret|token|api[-_ ]?key|apikey|access[-_]?key|private[-_]?key|credentials?|session|bearer",SENSITIVE_QUICK=new RegExp(SENSITIVE_WORDS,"i"),SENSITIVE_ASSIGNMENT=new RegExp(`(?:${SENSITIVE_WORDS})[A-Za-z0-9_.-]{0,32}(?:\\\\?["'])?[ ]*[:=]`,"i"),KEY_ESCAPE=/\\(?:u([0-9a-fA-F]{4})|U([0-9a-fA-F]{8})|x([0-9a-fA-F]{2})|([0abtnvfre "/\\N_LP\t]))|''/g,KEY_ESCAPE_QUICK=/\\[uUx]/,YAML_ESCAPES={0:"\0",a:"\x07",b:"\b",t:" "," ":" ",n:`\
|
|
57
|
+
|
|
58
|
+
`,v:"\v",f:"\f",r:"\r",e:"\x1B"," ":" ",'"':'"',"/":"/","\\":"\\",N:"\x85",_:"\xA0",L:"\u2028",P:"\u2029"},MAX_CONTINUATION_LINES=200,MAX_ANCHORS=256,MAX_HEREDOCS=MAX_CONTINUATION_LINES,ANCHOR_SCAN_BUDGET=4*1024*1024,ALREADY_REDACTED=/^\[REDACTED\][\s,;}\])"']*$/,BLOCK_SCALAR=/^[|>](?:[+-]\d?|\d[+-]?)?[ \t]*(?:#.*)?$/,YAML_PROPERTIES=/^(?:[!&]\S*[ \t]*)+/,DIFF_HEADER=/^(?:@@|\+\+\+|---)/m,HEREDOC=/(?<!<)<<([-~]?)[ \t]*(?:'([^'\r\n]{1,64})'|"([^"\r\n]{1,64})"|\\?([A-Za-z_][A-Za-z0-9_]{0,63}))(?=$|[\s;|&()<>])/g,
|
|
59
|
+
HEREDOC_START=/(?<!<)<<(?!<)/g,EXPLICIT_KEY_PREFIX=/^[\t +-]*\?[ \t]+/,EXPLICIT_VALUE=/^[\t +-]*:(?=[ \t]|$)[ \t]*/,ANCHOR_DEFINITION=/(?:^|[\s[{,])&([^\s,[\]{}]{1,128})/g,ALIAS_REFERENCE=/(?:^|[\s[{,])\*([^\s,[\]{}]{1,128})/g,BRACKET_TOKENS=new Set(["(","[","{","$(","${"]),MAX_REDACTION_SPANS=1e5;function decodeKeyEscape(match){if(match[1]!==void 0)return String.fromCharCode(Number.parseInt(match[1],16));if(match[2]!==void 0){let codePoint=Number.parseInt(match[2],16);return codePoint<=1114111?
|
|
60
|
+
String.fromCodePoint(codePoint):void 0}return match[3]!==void 0?String.fromCharCode(Number.parseInt(match[3],16)):match[4]!==void 0?YAML_ESCAPES[match[4]]:"'"}function normalizeKeyText(line){KEY_ESCAPE.lastIndex=0;let match=KEY_ESCAPE.exec(line);if(match===null)return{text:line,offsets:void 0};let text="",offsets=[],last=0,append=(chunk,origin,verbatim)=>{for(let index=0;index<chunk.length;index++)offsets.push(verbatim?origin+index:origin);text+=chunk};for(;match!==null;match=KEY_ESCAPE.exec(line)){
|
|
61
|
+
let decoded=decodeKeyEscape(match);decoded!==void 0&&(append(line.slice(last,match.index),last,!0),append(decoded,match.index,!1),last=match.index+match[0].length)}return append(line.slice(last),last,!0),offsets.push(line.length),{text,offsets}}function isMarker(char,spaceIsMarker){return char==="+"||char==="-"||spaceIsMarker&&char===" "}function startsWithMarker(line,diff){let first=line[0];return diff?isMarker(first,!0):first==="+"||first==="-"&&line.length>1&&!/\s/.test(line[1]??"")}function lineIndent(line,strip,dashIsDeeper){
|
|
62
|
+
let index=strip&&isMarker(line[0],!0)?1:0,indent=0;for(;index<line.length;index++){let char=line[index];if(char===" ")indent++;else if(char===" ")indent+=2;else break}return dashIsDeeper&&line[index]==="-"&&(index+1===line.length||/\s/.test(line[index+1]??""))&&indent++,indent}function isBlankLine(line,strip){return line.trim()===""||strip&&isMarker(line[0],!0)&&line.slice(1).trim()===""}function newScan(mode){return{stack:[],mode}}function pushExpansion(text,index,stack,quotes){let next=text[index+
|
|
63
|
+
1];return next==="("||next==="{"||quotes&&(next==="'"||next==='"')?(stack.push(`$${next}`),1):0}function opensBracket(char,top,mode){return mode==="flow"?!0:char==="("?top==="$("||top==="(":char==="{"?mode==="prefix"||top==="${":mode==="prefix"}function scanValue(text,state){let stack=state.stack;for(let index=0;index<text.length;index++){let top=stack[stack.length-1],char=text[index];if(top==="'")char==="'"&&(text[index+1]==="'"?index++:stack.pop());else if(top==="`")char==="\\"?index++:char===
|
|
64
|
+
"`"&&stack.pop();else if(top==='"""'||top==="'''")char==="\\"?index++:char===top[0]&&text.startsWith(top,index)&&(stack.pop(),index+=2);else if(top==="$'")char==="\\"?index++:char==="'"&&stack.pop();else if(top==='"'||top==='$"')char==="\\"?index++:char==='"'?stack.pop():char==="$"&&(index+=pushExpansion(text,index,stack,!1));else if(char==="\\")index++;else if(char==="#"&&top===void 0&&state.mode!=="prefix"){let before=text[index-1];if(index===0||before===" "||before===" ")return}else if(char===
|
|
65
|
+
'"'||char==="'"){let triple=char.repeat(3);text.startsWith(triple,index)?(stack.push(triple),index+=2):stack.push(char)}else char==="`"?stack.push(char):char==="$"?index+=pushExpansion(text,index,stack,!0):char==="("||char==="["||char==="{"?opensBracket(char,top,state.mode)&&stack.push(char):(char===")"&&(top==="$("||top==="(")||char==="}"&&(top==="${"||top==="{")||char==="]"&&top==="[")&&stack.pop()}}function findHeredocs(line){if(!line.includes("<<"))return[];let heredocs=[];HEREDOC.lastIndex=
|
|
66
|
+
0;for(let match=HEREDOC.exec(line);match!==null;match=HEREDOC.exec(line)){let word=match[2]??match[3]??match[4]??"";if(word.trim()==="")return;if(heredocs.length>=MAX_HEREDOCS)throw new Error(CAPACITY_EXCEEDED);heredocs.push({word,mode:match[1]??""})}let openers=0;for(let _match of line.matchAll(HEREDOC_START))if(++openers>MAX_HEREDOCS)throw new Error(CAPACITY_EXCEEDED);if(openers===heredocs.length)return heredocs}function matchHeredocTerminator(active,heredoc,line){let text=line,marker="",first=text[0];
|
|
67
|
+
active.strip&&first!==void 0&&(active.diff?isMarker(first,!0):first===active.marker)&&(marker=first,text=text.slice(1)),text.endsWith("\r")&&(text=text.slice(0,-1));let start=0;if(heredoc.mode!==""){let allowed=heredoc.mode==="-"?" ":" ";for(;start<text.length&&allowed.includes(text[start]??"");)start++}return text.length-start===heredoc.word.length&&text.startsWith(heredoc.word,start)?`${marker}${heredoc.word}`:void 0}function locateAssignment(line){let key=normalizeKeyText(line),match=SENSITIVE_ASSIGNMENT.
|
|
68
|
+
exec(key.text);if(match===null)return;let toOriginal=index=>key.offsets===void 0?index:key.offsets[index]??line.length,value=line.slice(toOriginal(match.index+match[0].length)).trimStart();return{keyStart:toOriginal(match.index),valueStart:line.length-value.length}}function isSensitiveExplicitKey(line){if(!line.includes("?"))return!1;let prefix=EXPLICIT_KEY_PREFIX.exec(line);if(prefix===null)return!1;let name=line.slice(prefix[0].length),comment=name.indexOf(" #");comment>=0&&(name=name.slice(0,
|
|
69
|
+
comment)),name=name.trim();let first=name[0];(first==='"'||first==="'")&&name.length>=2&&name.endsWith(first)&&(name=name.slice(1,-1));let key=normalizeKeyText(`${name}:`);return key.text.length<=65&&SENSITIVE_ASSIGNMENT.test(key.text)}function classifyLine(line,explicitPending){if(explicitPending){if(line.trim()===""||line.trimStart().startsWith("#"))return{located:void 0,pending:!0};let colon=EXPLICIT_VALUE.exec(line);if(colon!==null)return{located:{keyStart:colon[0].indexOf(":"),valueStart:colon[0].
|
|
70
|
+
length},pending:!1}}let located=locateAssignment(line);return{located,pending:located===void 0&&isSensitiveExplicitKey(line)}}function collectAliasNames(text,into){if(!text.includes("*"))return!0;ALIAS_REFERENCE.lastIndex=0;for(let match=ALIAS_REFERENCE.exec(text);match!==null;match=ALIAS_REFERENCE.exec(text)){let name=match[1];if(!(name===void 0||into.has(name))){if(into.size>=MAX_ANCHORS)return!1;into.add(name)}}return!0}function collectAnchorGroups(parts,diff){let groups=[],anchorCount=0,budget=ANCHOR_SCAN_BUDGET;
|
|
71
|
+
for(let index=0;index<parts.length;index+=2){let line=parts[index]??"";if(!line.includes("&"))continue;let anchors=[],first;ANCHOR_DEFINITION.lastIndex=0;for(let match=ANCHOR_DEFINITION.exec(line);match!==null;match=ANCHOR_DEFINITION.exec(line)){let name=match[1];if(name!==void 0){if(++anchorCount>MAX_ANCHORS)return;if(anchors.push(name),first===void 0){let tokenEnd=match.index+match[0].length;first={keyStart:tokenEnd-name.length-1,valueStart:line.length-line.slice(tokenEnd).trimStart().length}}}}
|
|
72
|
+
if(first===void 0)continue;let aliases=new Set,tail=line.slice(first.valueStart);if(budget-=tail.length,budget<0||!collectAliasNames(tail,aliases))return;let continuation=startContinuation(line,first,diff);if(continuation.remaining===0)return;for(let next=index+2;next<parts.length&&continuation.remaining>0;next+=2){let nextLine=parts[next]??"";if(consumeContinuationLine(continuation,nextLine)===void 0)break;if(--continuation.remaining<=0||(budget-=nextLine.length,budget<0||!collectAliasNames(nextLine,
|
|
73
|
+
aliases)))return}groups.push({anchors,aliases})}return groups}function propagateAnchors(roots,parts,diff){let names=new Set(roots),groups=collectAnchorGroups(parts,diff);if(groups===void 0)return{names,overflow:!0};let byAnchor=new Map;groups.forEach((group,groupIndex)=>{for(let anchor of group.anchors){let indexes=byAnchor.get(anchor);indexes===void 0?byAnchor.set(anchor,[groupIndex]):indexes.push(groupIndex)}});let queue=[...roots],expanded=new Set;for(let head=0;head<queue.length;head++)for(let groupIndex of byAnchor.
|
|
74
|
+
get(queue[head]??"")??[])if(!expanded.has(groupIndex)){expanded.add(groupIndex);for(let alias of groups[groupIndex]?.aliases??[])if(!names.has(alias)){if(names.size>=MAX_ANCHORS)return{names,overflow:!0};names.add(alias),queue.push(alias)}}return{names,overflow:!1}}function buildAnchorTable(parts,diff){let roots=new Set,overflow=!1;return processLines(parts,diff,{names:new Set,overflow:!1},text=>{!overflow&&(text===void 0||!collectAliasNames(text,roots))&&(overflow=!0)}),overflow?{names:roots,overflow:!0}:
|
|
75
|
+
roots.size===0?{names:roots,overflow:!1}:propagateAnchors(roots,parts,diff)}function locateAnchorDefinition(line,anchors){if(!(anchors.names.size===0&&!anchors.overflow||!line.includes("&"))){ANCHOR_DEFINITION.lastIndex=0;for(let match=ANCHOR_DEFINITION.exec(line);match!==null;match=ANCHOR_DEFINITION.exec(line)){let name=match[1];if(name===void 0||!(anchors.overflow||anchors.names.has(name)))continue;let tokenEnd=match.index+match[0].length,value=line.slice(tokenEnd).trimStart();return{keyStart:tokenEnd-
|
|
76
|
+
name.length-1,valueStart:line.length-value.length}}}}function indentContinuation(line,diff){let strip=startsWithMarker(line,diff);return{kind:"indent",heredocs:[],scan:newScan("value"),indent:lineIndent(line,strip,!1),strip,marker:strip?line[0]??"":"",diff,dashIsDeeper:!strip&&!line.trimStart().startsWith("-"),remaining:MAX_CONTINUATION_LINES}}function startContinuation(line,located,diff){let continuation=indentContinuation(line,diff),heredocs=findHeredocs(line);if(heredocs===void 0)return continuation.
|
|
77
|
+
remaining=0,continuation;continuation.heredocs=heredocs;let flow=newScan("prefix");if(scanValue(line.slice(0,located.keyStart),flow),flow.stack.some(token=>BRACKET_TOKENS.has(token))&&(flow.mode="flow",scanValue(line.slice(located.keyStart),flow),flow.stack.length>0))return continuation.kind="open",continuation.scan=flow,continuation;let stripped=line.slice(located.valueStart).replace(YAML_PROPERTIES,"");if(stripped===""||stripped[0]==="#"||BLOCK_SCALAR.test(stripped))return continuation;let scan=newScan(
|
|
78
|
+
stripped[0]==="["||stripped[0]==="{"||stripped[0]==="("?"flow":"value");return scanValue(stripped,scan),scan.stack.length>0?(continuation.kind="open",continuation.scan=scan):stripped.trimEnd().endsWith("\\")&&(continuation.kind="backslash"),continuation}function redactedBodyLine(line){return line.trim()===""||ALREADY_REDACTED.test(line.trim())?line:REDACTED}function consumeContinuationLine(active,line){let heredoc=active.heredocs[0];if(heredoc!==void 0){let terminator=matchHeredocTerminator(active,
|
|
79
|
+
heredoc,line);return terminator===void 0?redactedBodyLine(line):(active.heredocs.shift(),terminator)}if(active.kind==="indent")return isBlankLine(line,active.strip)?line:lineIndent(line,active.strip,active.dashIsDeeper)>active.indent?redactedBodyLine(line):void 0;let heredocs=findHeredocs(line);if(heredocs===void 0)return active.remaining=0,REDACTED;for(let found of heredocs){if(active.heredocs.length>=MAX_HEREDOCS)throw new Error(CAPACITY_EXCEEDED);active.heredocs.push(found)}return scanValue(line,
|
|
80
|
+
active.scan),active.scan.stack.length>0?active.kind="open":active.kind=line.trimEnd().endsWith("\\")?"backslash":"indent",redactedBodyLine(line)}function processLines(parts,diff,anchors,collect,mask){let out=[],offset=0,continuation,explicitPending=!1;for(let index=0;index<parts.length;index+=2){let line=parts[index]??"",eol=parts[index+1]??"",start=offset;if(offset+=line.length+eol.length,continuation!==void 0){let replacement=consumeContinuationLine(continuation,line);if(replacement!==void 0){
|
|
81
|
+
if(collect?.(line),replacement!==line&&mask?.(start,start+line.length,replacement),out.push(replacement,eol),continuation.remaining--,continuation.remaining<=0)return collect?.(void 0),mask?.(offset,parts.join("").length,REDACTED),out.push(REDACTED),out.join("");continue}continuation=void 0}let classified=classifyLine(line,explicitPending);explicitPending=classified.pending;let located=classified.located??locateAnchorDefinition(line,anchors);if(located===void 0){out.push(line,eol);continue}let value=line.
|
|
82
|
+
slice(located.valueStart);if(collect?.(value),ALREADY_REDACTED.test(value)){continuation=indentContinuation(line,diff),out.push(line,eol);continue}if(continuation=startContinuation(line,located,diff),out.push(value===""?line:`${line.slice(0,located.valueStart)}${REDACTED}`,eol),value!==""&&value!==REDACTED&&mask?.(start+located.valueStart,start+line.length,REDACTED),continuation.remaining===0)return collect?.(void 0),mask?.(offset,parts.join("").length,REDACTED),out.push(REDACTED),out.join("")}return out.
|
|
83
|
+
join("")}function redactSensitiveLines(text,mask){if(!SENSITIVE_QUICK.test(text)&&!KEY_ESCAPE_QUICK.test(text))return text;let parts=text.split(/(\r\n|\n|\r)/),diff=DIFF_HEADER.test(text),anchors=text.includes("*")&&text.includes("&")?buildAnchorTable(parts,diff):{names:new Set,overflow:!1};return processLines(parts,diff,anchors,void 0,mask)}function checkedLiterals(secrets){let usable=new Set,chars=0;for(let secret of secrets)if(!(secret===""||usable.has(secret))){if(secret.length<MIN_SECRET_LENGTH)
|
|
84
|
+
throw new Error(CAPACITY_EXCEEDED);if(chars+=secret.length,usable.size>=MAX_SECRETS||chars>MAX_SECRET_CHARS)throw new Error(CAPACITY_EXCEEDED);usable.add(secret)}return usable}function kGramHashes(text,k,visit){if(text.length<k)return;let hash=0,power=1;for(let index=0;index<k;index++)hash=Math.imul(hash,31)+text.charCodeAt(index)>>>0,index<k-1&&(power=Math.imul(power,31)>>>0);visit(0,hash);for(let offset=1;offset<=text.length-k;offset++)hash=Math.imul(hash-Math.imul(text.charCodeAt(offset-1),power),
|
|
85
|
+
31)+text.charCodeAt(offset+k-1)>>>0,visit(offset,hash)}var BASE64_LEADING_UNSTABLE=[0,2,3],MAX_VARIANT_CHARS=MAX_TEXT_CHARS;function base64Variants(secret){let bytes=Buffer.from(secret,"utf8"),forms=[];for(let offset=0;offset<3;offset++){let core=Buffer.concat([Buffer.alloc(offset),bytes]).toString("base64").replace(/=+$/,"");(offset+bytes.length)%3!==0&&(core=core.slice(0,-1)),core=core.slice(BASE64_LEADING_UNSTABLE[offset]),forms.push(core,core.replace(/\+/g,"-").replace(/\//g,"_"))}return forms.
|
|
86
|
+
filter(form=>form.length>=8)}function buildLiteralCoverage(secrets){let registered=checkedLiterals(secrets);if(registered.size===0)return;let usable=new Set(registered),base64Forms=new Set,variantChars=0;for(let secret of registered)for(let form of base64Variants(secret))if(!usable.has(form)){if(variantChars+=form.length,variantChars>MAX_VARIANT_CHARS)throw new Error(CAPACITY_EXCEEDED);usable.add(form),base64Forms.add(form)}let fragments=new Map;for(let secret of[...usable].sort((a,b)=>a.length-
|
|
87
|
+
b.length))kGramHashes(secret,8,(offset,hash)=>{let hits=fragments.get(hash);hits===void 0&&(hits=new Map,fragments.set(hash,hits));let offsets=hits.get(secret);offsets===void 0?hits.set(secret,[offset]):offsets.push(offset)});let indexed=new Map,minThreshold=1/0;for(let[hash,hits]of fragments)indexed.set(hash,[...hits].map(([secret,origins])=>{let threshold=Math.min(secret.length,Math.max(8,Math.ceil(secret.length/2)));return minThreshold=Math.min(minThreshold,threshold),{secret,threshold,origins,
|
|
88
|
+
base64:base64Forms.has(secret)}}));return{fragments:indexed,minThreshold}}var BASE64_EDGE_BEFORE=3,BASE64_CHAR=/^[A-Za-z0-9+/_-]$/;function maskFragments(text,coverage,work,mask){if(text.length<coverage.minThreshold)return;let covered=new Map,equal=(left,secret,right)=>{if(++work.comparisons>MAX_TEXT_CHARS)throw new Error(CAPACITY_EXCEEDED);return text.charCodeAt(left)===secret.charCodeAt(right)};kGramHashes(text,8,(offset,hash)=>{let entries=coverage.fragments.get(hash);if(entries!==void 0)for(let{
|
|
89
|
+
secret,threshold,origins,base64}of entries){if(++work.candidates>MAX_REDACTION_SPANS*10)throw new Error(CAPACITY_EXCEEDED);if(text.length<threshold)break;for(let origin of origins){if(++work.candidates>MAX_REDACTION_SPANS*10)throw new Error(CAPACITY_EXCEEDED);let diagonal=offset-origin,runs=covered.get(secret);if((runs?.get(diagonal)??-1)>=offset+8)continue;let seed=0;for(;seed<8&&equal(offset+seed,secret,origin+seed);)seed++;if(seed<8)continue;let start=offset,end=offset+8;for(;start>0&&start-diagonal>
|
|
90
|
+
0&&equal(start-1,secret,start-diagonal-1);)start--;for(;end<text.length&&end-diagonal<secret.length&&equal(end,secret,end-diagonal);)end++;if(runs===void 0&&(runs=new Map,covered.set(secret,runs)),runs.set(diagonal,end),end-start>=threshold){if(++work.matches>MAX_REDACTION_SPANS)throw new Error(CAPACITY_EXCEEDED);if(base64){let from=start;for(;from>0&&start-from<BASE64_EDGE_BEFORE&&BASE64_CHAR.test(text[from-1]??"");)from--;let to=end;for(BASE64_CHAR.test(text[to]??"")&&to++;to<text.length&&text[to]===
|
|
91
|
+
"=";)to++;mask(from,to)}else mask(start,end)}}}})}var IGNORABLE=String.raw`[\p{Cf}\p{Default_Ignorable_Code_Point}]`,VIEW_TRIGGER=new RegExp(String.raw`${IGNORABLE}|\\|%[0-9a-fA-F]{2}`,"u"),VIEW_TOKEN=new RegExp(String.raw`${IGNORABLE}|(?<!\\)\\+(?:u\{([0-9a-fA-F]{1,6})\}|u([0-9a-fA-F]{4})|U([0-9a-fA-F]{8})|x([0-9a-fA-F]{2})|(["/bfnrt])?)|(?:%[0-9a-fA-F]{2})+`,"gu"),WRAP_TOKEN=/(?<=[A-Za-z0-9+/_=-])\\?[ \t]*(?:[\r\n\f\v\u0085\u2028\u2029][ \t]*(?:[>#][ \t]*)?)+(?=[A-Za-z0-9+/_-])/gu,LINE_BREAK=/[\r\n\f\v\u0085\u2028\u2029]/,
|
|
92
|
+
WRAP_PROBE=new RegExp(WRAP_TOKEN.source,"u"),JSON_ESCAPES={b:"\b",f:"\f",n:`
|
|
93
|
+
`,r:"\r",t:" "},MAX_VIEW_PASSES=6,MAX_HALVED_RUN=64,ESCAPE_RUN=new RegExp(String.raw`(?<!\\)\\{2,${MAX_HALVED_RUN}}[ux]`),MAX_VIEW_CHARS=4*MAX_TEXT_CHARS,hexValue=code=>code<=57?code-48:(code|32)-87,isContinuation=byte=>byte>=128&&byte<=191;function utf8CodePointAt(byteAt,index,count){let lead=byteAt(index);if(lead>=194&&lead<=223)return index+1>=count||!isContinuation(byteAt(index+1))?void 0:{cp:(lead&31)<<6|byteAt(index+1)&63,length:2};if(lead>=224&&lead<=239){if(index+2>=count)return;let second=byteAt(
|
|
94
|
+
index+1),third=byteAt(index+2);return!isContinuation(second)||!isContinuation(third)||lead===224&&second<160||lead===237&&second>159?void 0:{cp:(lead&15)<<12|(second&63)<<6|third&63,length:3}}if(lead>=240&&lead<=244){if(index+3>=count)return;let second=byteAt(index+1);return!isContinuation(second)||!isContinuation(byteAt(index+2))||!isContinuation(byteAt(index+3))||lead===240&&second<144||lead===244&&second>143?void 0:{cp:(lead&7)<<18|(second&63)<<12|(byteAt(index+2)&63)<<6|byteAt(index+3)&63,length:4}}}
|
|
95
|
+
function decodePercentRun(run,put){let count=run.length/3,byteAt=index=>hexValue(run.charCodeAt(index*3+1))<<4|hexValue(run.charCodeAt(index*3+2)),decodedAny=!1;for(let index=0;index<count;){let lead=byteAt(index);if(lead<128){put(String.fromCharCode(lead),index,index+1),decodedAny=!0,index++;continue}let sequence=utf8CodePointAt(byteAt,index,count);sequence!==void 0?(put(String.fromCodePoint(sequence.cp),index,index+sequence.length),decodedAny=!0,index+=sequence.length):(put(run.slice(index*3,index*
|
|
96
|
+
3+3),index,index+1),index++)}return decodedAny}function viewPass(text,starts,ends,tokens=VIEW_TOKEN,halveEscapes=!1){let out=[],outStarts=new Uint32Array(text.length),outEnds=new Uint32Array(text.length),count=0,put=(decoded,from,to)=>{out.push(decoded);let first=starts?.[from]??from,end=ends?.[to-1]??to;for(let index=0;index<decoded.length;index++)outStarts[count]=first,outEnds[count++]=end},keep=(from,to)=>{out.push(text.slice(from,to));for(let index=from;index<to;index++)outStarts[count]=starts?.[index]??
|
|
97
|
+
index,outEnds[count++]=ends?.[index]??index+1},last=0,changed=!1,structural=!1,wrap=tokens===WRAP_TOKEN;for(let match of text.matchAll(tokens)){let token=match[0],from=match.index,to=from+token.length;if(wrap){keep(last,from),last=to,changed=!0;continue}let wasStructural=structural;if(structural=!0,token.startsWith("%")){keep(last,from),decodePercentRun(token,(decoded,first,end)=>put(decoded,from+first*3,from+end*3))&&(changed=!0),last=to;continue}if(token.startsWith("\\")){let unit=token.search(
|
|
98
|
+
/[^\\]/),run=unit===-1?token.length:unit,escaped=match[1]??match[2]??match[3]??match[4],letter=match[5];if(run===1&&escaped===void 0&&letter===void 0){structural=wasStructural;continue}let rest=token.slice(run);if(escaped!==void 0&&!(halveEscapes&&run>=2&&run<=MAX_HALVED_RUN)){let codePoint=match[1]!==void 0||match[3]!==void 0?Number.parseInt(match[1]??match[3],16):0;if(codePoint>1114111){structural=wasStructural;continue}keep(last,from),put(codePoint>0?String.fromCodePoint(codePoint):String.fromCharCode(
|
|
99
|
+
Number.parseInt(escaped,16)),from,to)}else if(escaped===void 0&&letter!==void 0&&run%2===1){keep(last,from);for(let pair=0;pair<Math.floor(run/2);pair++)put("\\",from+pair*2,from+pair*2+2);put(JSON_ESCAPES[letter]??letter,to-2,to)}else{structural=wasStructural,keep(last,from);for(let pair=0;pair<Math.floor(run/2);pair++)put("\\",from+pair*2,from+pair*2+2);run%2===1&&letter===void 0&&put("\\",from+run-1,from+run),rest!==""&&put(rest,to-rest.length,to)}last=to,changed=!0;continue}keep(last,from),last=
|
|
100
|
+
to,changed=!0}return keep(last,text.length),{text:changed?out.join(""):text,starts:outStarts.subarray(0,count),ends:outEnds.subarray(0,count),changed,structural}}function eachView(text,work,visit,withHalved=!0){let charge=current=>{if(work.viewChars+=current.length,work.viewChars>MAX_VIEW_CHARS)throw new Error(CAPACITY_EXCEEDED)},halved=from=>{let view2=from,structural2=0;for(;;){let current=view2?.text??text;if(!ESCAPE_RUN.test(current))return;charge(current);let next=viewPass(current,view2?.starts,
|
|
101
|
+
view2?.ends,VIEW_TOKEN,!0);if(!next.changed)return;if(next.structural&&++structural2>MAX_VIEW_PASSES)throw new Error(CAPACITY_EXCEEDED);view2=next,visit(view2)}};withHalved&&halved(void 0);let view,structural=0;for(;;){let current=view?.text??text;if(!VIEW_TRIGGER.test(current))return;charge(current);let next=viewPass(current,view?.starts,view?.ends);if(!next.changed)return;if(next.structural&&++structural>MAX_VIEW_PASSES)throw new Error(CAPACITY_EXCEEDED);view=next,visit(view),withHalved&&halved(
|
|
102
|
+
view)}}function decodeEscapes(text){let last;return eachView(text,{candidates:0,comparisons:0,matches:0,viewChars:0},view=>{last=view},!1),last}function joinWrappedLines(text,view,work){let current=view?.text??text;if(!LINE_BREAK.test(current)||!WRAP_PROBE.test(current))return;if(work.viewChars+=current.length,work.viewChars>MAX_VIEW_CHARS)throw new Error(CAPACITY_EXCEEDED);let joined=viewPass(current,view?.starts,view?.ends,WRAP_TOKEN);return joined.changed?joined:void 0}function redactTextWith(text,coverage,work){
|
|
103
|
+
if(text.length>MAX_TEXT_CHARS)throw new Error(CAPACITY_EXCEEDED);let spans=[],mask=(start,end,replacement=REDACTED)=>{if(!(start>=end)){if(spans.length>=MAX_REDACTION_SPANS*10)throw new Error(CAPACITY_EXCEEDED);spans.push({start,end,replacement})}};if(coverage!==void 0){maskFragments(text,coverage,work,mask);let scan=candidate=>{candidate!==void 0&&maskFragments(candidate.text,coverage,work,(start,end)=>{mask(candidate.starts[start]??0,candidate.ends[end-1]??text.length)})};scan(joinWrappedLines(
|
|
104
|
+
text,void 0,work)),eachView(text,work,view=>{scan(view),scan(joinWrappedLines(text,view,work))})}redactSensitiveLines(text,mask);for(let pattern of[...SECRET_PATTERNS,ASSIGNMENT_PATTERN]){pattern.lastIndex=0;for(let match=pattern.exec(text);match!==null;match=pattern.exec(text))mask(match.index+(pattern===ASSIGNMENT_PATTERN?match[1]?.length??0:0),match.index+match[0].length)}spans.sort((a,b)=>a.start-b.start||b.end-a.end);let merged=[];for(let span of spans){let previous=merged[merged.length-1];
|
|
105
|
+
previous!==void 0&&span.start<=previous.end?(previous.end=Math.max(previous.end,span.end),span.replacement===REDACTED&&(previous.replacement=REDACTED)):merged.push({...span})}let chunks=[],offset=0;for(let span of merged)chunks.push(text.slice(offset,span.start),span.replacement),offset=span.end;chunks.push(text.slice(offset));let out=chunks.join("");return{text:out,redacted:out!==text}}function childFieldPath(parent,key){if(!PATH_SEGMENT.test(key))return parent;let path=`${parent}.${key}`;return path.
|
|
106
|
+
length>FIELD_PATH_MAX?parent:path}function isAncestor(chain,candidate){for(let node=chain;node!==null;node=node.parent)if(node.source===candidate)return!0;return!1}function collapseToTopLevel(paths,basePath){let baseSegments=basePath.split(".").length,collapsed=new Set;for(let path of paths)collapsed.add(path.split(".").slice(0,baseSegments+1).join("."));return[...collapsed]}function redactJsonWith(value,basePath,literal,maxNodes,maxDepth){let removed=new Set,truncatedPaths=new Set,truncated=!1,nodes=0,textChars=0,work={candidates:0,comparisons:0,matches:0,viewChars:0},markTruncated=path=>{truncated=!0,truncatedPaths.add(path)},convert=(input,path,depth,ancestry,stack2,collapsed)=>{if(input===null)return null;switch(typeof input){case"boolean":return input;case"number":{if(!Number.isFinite(input))return null;let text=String(input),safe=convert(text,path,depth,ancestry,
|
|
107
|
+
stack2,collapsed);return safe===text?input:safe}case"bigint":return convert(input.toString(),path,depth,ancestry,stack2,collapsed);case"string":{if(textChars+=input.length,textChars>MAX_TEXT_CHARS)throw new Error(CAPACITY_EXCEEDED);let result=redactTextWith(input,literal,work);return result.redacted&&removed.add(path),result.text}case"object":break;default:return}if(input instanceof Date)return Number.isNaN(input.getTime())?null:convert(input.toISOString(),path,depth,ancestry,stack2,collapsed);if(isAncestor(
|
|
108
|
+
ancestry,input))return markTruncated(path),CIRCULAR;if(depth>maxDepth)return markTruncated(path),TRUNCATED;let target=Array.isArray(input)?[]:{};return stack2.push({source:input,target,path,depth,ancestry:{source:input,parent:ancestry},collapsed:collapsed||Array.isArray(input)}),target},rootStack=[],root=convert(value,basePath,1,null,rootStack,!1);nodes++;let stack=rootStack;for(;stack.length>0;){let frame=stack.pop();if(frame===void 0)break;let{source,target,path,depth,ancestry,collapsed}=frame;
|
|
109
|
+
if(Array.isArray(source)&&Array.isArray(target)){for(let index=0;index<source.length;index++){if(nodes>=maxNodes){markTruncated(path);break}let item;try{item=source[index]}catch{item=void 0}nodes++;let converted=convert(item,path,depth+1,ancestry,stack,!0);target.push(converted===void 0?null:converted)}continue}if(Array.isArray(target))continue;let keys2;try{keys2=Object.keys(source)}catch{markTruncated(path);continue}let placeholders=0;for(let key of keys2){if(FORBIDDEN_KEYS.has(key)){markTruncated(
|
|
110
|
+
path);continue}if(nodes>=maxNodes){markTruncated(path);break}if(textChars+=key.length,textChars>MAX_TEXT_CHARS)throw new Error(CAPACITY_EXCEEDED);let outKey=key,childPath=collapsed?path:childFieldPath(path,key);if(redactTextWith(key,literal,work).redacted){do outKey=`redacted_key_${placeholders++}`;while(outKey in target||Object.hasOwn(source,outKey));childPath=path,removed.add(path)}let item;try{item=source[key]}catch{markTruncated(path);continue}if(nodes++,isSensitiveKey(key)&&item!=null&&item!==
|
|
111
|
+
""){target[outKey]=REDACTED,removed.add(childPath);continue}let converted=convert(item,childPath,depth+1,ancestry,stack,collapsed);converted!==void 0&&(target[outKey]=converted)}}return{value:root??null,removedFieldPaths:boundPaths(removed,basePath),truncated,truncatedFieldPaths:boundPaths(truncatedPaths,basePath)}}function boundPaths(paths,basePath){return paths.size>DH_MAX_REMOVED_FIELD_PATHS?collapseToTopLevel(paths,basePath):[...paths]}function getTraceEnvSecrets(env){return Object.entries(env).
|
|
112
|
+
filter(([name,value])=>value!==void 0&&value!==""&&SENSITIVE_ENV_NAME.test(name)).map(([,value])=>value)}function createTraceRedactor(options={}){let secrets=new Set,literal,chars=0,capacityExceeded=!1,disable=()=>{capacityExceeded=!0,secrets.clear(),literal=void 0},add=secret=>{if(capacityExceeded)return!1;if(secret===""||secrets.has(secret))return!0;if(secret.length<MIN_SECRET_LENGTH||secrets.size>=MAX_SECRETS||chars+secret.length>MAX_SECRET_CHARS)return disable(),!1;secrets.add(secret);try{literal=
|
|
113
|
+
buildLiteralCoverage([...secrets])}catch{return disable(),!1}return chars+=secret.length,!0},pattern=()=>{if(capacityExceeded)throw new Error(CAPACITY_EXCEEDED);return literal};for(let secret of options.extraSecrets??[])add(secret);for(let[name,secret]of Object.entries(options.env??{}))secret!==void 0&&SENSITIVE_ENV_NAME.test(name)&&add(secret);return{redactJson:(value,basePath,limits)=>redactJsonWith(value,basePath,pattern(),limits?.maxNodes??DEFAULT_MAX_NODES,limits?.maxDepth??DEFAULT_MAX_DEPTH),
|
|
114
|
+
redactText:text=>redactTextWith(text,pattern(),{candidates:0,comparisons:0,matches:0,viewChars:0}),addSecret:add,disable}}var STRING_SEQUENCE=/\u001b[P\]X^_][\s\S]*?(?:\u0007|\u001b\\|$)|[\u0090\u0098\u009d-\u009f][\s\S]*?(?:\u0007|\u009c|\u001b\\|$)/g,CSI_SEQUENCE=/(?:\u001b\[|\u009b)[0-?]*[ -/]*[@-~]?/g,OTHER_ESCAPE=/\u001b[\s\S]?/g,CONTROL_CHARS=/[\u0000-\u0008\u000b-\u001f\u007f-\u009f]/g,BIDI_CONTROLS=/[\u061c\u200e\u200f\u202a-\u202e\u2066-\u2069]/g;function sanitizeForTerminal(text){return text.replace(STRING_SEQUENCE,"").replace(CSI_SEQUENCE,"").replace(OTHER_ESCAPE,"").replace(CONTROL_CHARS,"").replace(BIDI_CONTROLS,
|
|
115
|
+
"")}import{createHash as createHash4,randomBytes as randomBytes5}from"node:crypto";import{closeSync as closeSync2,constants as constants4,fstatSync as fstatSync2,fsyncSync as fsyncSync2,linkSync as linkSync2,lstatSync as lstatSync2,openSync as openSync2,readdirSync as readdirSync2,readSync as readSync2,renameSync as renameSync2,unlinkSync as unlinkSync2,writeSync as writeSync2}from"node:fs";import{join as join5}from"node:path";import{createHash as createHash3,randomBytes as randomBytes4}from"node:crypto";import{closeSync,constants as constants3,existsSync as existsSync2,fstatSync,fsyncSync,linkSync,lstatSync,mkdirSync,openSync,readdirSync,readFileSync,readSync,realpathSync,renameSync,unlinkSync,writeSync}from"node:fs";import{basename as basename2,dirname as dirname2,join as join4,resolve as resolve2}from"node:path";import{join as join3}from"node:path";var TRACE_BINDING_MAX_BYTES=65536,id=prefix=>typebox_exports.String({pattern:`^${prefix}_[A-Za-z0-9_-]{8,128}$`}),parseBinding=dtoParser("spool binding",()=>typebox_exports.Object({schema:typebox_exports.Literal("dh.spool-binding/1"),originStreamId:typebox_exports.String({pattern:"^[A-Za-z0-9_-]{1,128}$"}),generationId:id("gen"),admission:typebox_exports.Unknown(),producerInstanceId:id("prd"),enrollmentId:id("enr"),credentialVersion:typebox_exports.Integer({minimum:1,maximum:Number.MAX_SAFE_INTEGER}),
|
|
54
116
|
delegationIds:typebox_exports.Array(id("dlg"),{maxItems:64,uniqueItems:!0})},{additionalProperties:!1}));function parseTraceSpoolBinding(input){let parsed=parseBinding(input),admission=parseDhAdmissionBinding(parsed.admission);if(parsed.generationId!==admission.generationId)throw new Error("binding_unavailable");return Object.freeze({...parsed,admission})}function traceBindingPath(spoolDir,streamId){if(!isTraceStreamId(streamId))throw new Error("binding_unavailable");return join3(spoolDir,"bindi\
|
|
55
117
|
ngs",`${streamId}.json`)}function acquireTraceBindingLease(spoolDir,streamId){if(!isTraceStreamId(streamId))throw new Error("binding_unavailable");let release2=acquireTraceSpoolLock(spoolDir,`stream-${streamId}.binding.lock`);if(release2===void 0)throw new Error("binding_unavailable");return release2}function readTraceStreamBinding(spoolDir,streamId){let release2=acquireTraceBindingLease(spoolDir,streamId);try{let text=readTraceStateFile(traceBindingPath(spoolDir,streamId),TRACE_BINDING_MAX_BYTES),
|
|
56
118
|
binding=parseTraceSpoolBinding(parseDhRawJson(Buffer.from(text),{maxBytes:TRACE_BINDING_MAX_BYTES}));if(binding.originStreamId!==streamId)throw new Error("binding_unavailable");return binding}finally{release2()}}function writeTraceStreamBinding(spoolDir,input,io={}){let binding=parseTraceSpoolBinding(input),text=dhCanonicalText(binding),syncDirectory=io.fsyncDir??(path=>fsyncDir(path,!0));if(Buffer.byteLength(text)>TRACE_BINDING_MAX_BYTES)throw new Error("binding_unavailable");ensureTraceSpoolDirs(
|
|
@@ -177,68 +239,7 @@ return invalid(TRACE_ENV.externalIds,"must be a JSON array")}if(!Array.isArray(p
|
|
|
177
239
|
environmentId,projectId},externalIds};parentAgentId!==void 0&&(config.parentAgentId=parentAgentId),retryOfAttemptId!==void 0&&(config.retryOfAttemptId=retryOfAttemptId);let ingestUrl=present(env,TRACE_ENV.ingestUrl);if(ingestUrl!==void 0){let url;try{url=new URL(ingestUrl)}catch{return invalid(TRACE_ENV.ingestUrl,"must be an http(s) URL")}if(url.protocol!=="https:"&&url.protocol!=="http:"||url.username!==""||url.password!=="")return invalid(TRACE_ENV.ingestUrl,"must be an http(s) URL without cre\
|
|
178
240
|
dentials");config.ingestUrl=ingestUrl}return{enabled:!0,config}}function consumeTraceProducerConfig(env){takeTraceIngestCredentials(env),takeTraceIngestCredentials(process.env);let secrets=[...heldIngestSecrets];intakeOverflow&&secrets.push("!");try{return{result:readTraceProducerConfig(env),secrets}}finally{consumeTraceIngestToken()}}function buildChildTraceEnv(parent,child){let set={[TRACE_ENV.spoolDir]:parent.spoolDir,[TRACE_ENV.generationId]:parent.generationId,[TRACE_ENV.agentId]:child.agentId,
|
|
179
241
|
[TRACE_ENV.attemptId]:child.attemptId,[TRACE_ENV.parentAgentId]:parent.agentId,[TRACE_ENV.attemptNumber]:String(child.attemptNumber),[TRACE_ENV.lifecycleOwner]:"parent",[TRACE_ENV.environmentId]:parent.tenantScope.environmentId,[TRACE_ENV.projectId]:parent.tenantScope.projectId};child.retryOfAttemptId!==void 0&&(set[TRACE_ENV.retryOfAttemptId]=child.retryOfAttemptId);let unset=[TRACE_ENV.ingestUrl,TRACE_ENV.ingestToken];return child.retryOfAttemptId===void 0&&unset.push(TRACE_ENV.retryOfAttemptId),
|
|
180
|
-
child.externalIds!==void 0&&child.externalIds.length>0?set[TRACE_ENV.externalIds]=JSON.stringify(child.externalIds):unset.push(TRACE_ENV.externalIds),{set,unset}}
|
|
181
|
-
SENSITIVE_ENV_NAME=/(KEY|TOKEN|SECRET|PASSWORD|CREDENTIAL|AUTH)/i,FORBIDDEN_KEYS=new Set(["__proto__","constructor","prototype"]),PATH_SEGMENT=/^[A-Za-z0-9_-]+$/,FIELD_PATH_MAX=256,SECRET_PATTERNS=[/-----BEGIN [A-Z ]*PRIVATE KEY-----[\s\S]*?(?:-----END [A-Z ]*PRIVATE KEY-----|$)/g,/\bBearer\s+[A-Za-z0-9._~+/=-]{8,}/gi,/\beyJ[A-Za-z0-9_-]{5,}\.[A-Za-z0-9_-]{5,}\.[A-Za-z0-9_-]*/g,/\b(?:sk-ant-[A-Za-z0-9_-]{16,}|sk-[A-Za-z0-9_-]{20,}|gh[pousr]_[A-Za-z0-9]{20,}|github_pat_[A-Za-z0-9_]{20,}|glpat-[A-Za-z0-9_-]{16,}|xox[abpr]-[A-Za-z0-9-]{10,}|A[KS]IA[0-9A-Z]{16}|AIza[0-9A-Za-z_-]{35})/g],
|
|
182
|
-
ASSIGNMENT_PATTERN=/(\b[A-Za-z0-9_-]{0,32}(?:password|passwd|pwd|secret|token|api[_-]?key|access[_-]?key|credential)[A-Za-z0-9_-]{0,32}["']?[ \t]*[=:][ \t]*)("[^"]*"|'[^']*'|[^\s"',;&]+)/gi;function isSensitiveKey(key){if(SENSITIVE_KEY_NAME.test(key))return!0;let segments=key.split(/[-_.\s]+|(?<=[a-z0-9])(?=[A-Z])/).filter(segment=>segment!=="").map(segment=>segment.toLowerCase());for(let start=1;start<segments.length&&start<8;start++)if(SENSITIVE_KEY_NAME.test(segments.slice(start).join("_")))return!0;
|
|
183
|
-
return!1}var SENSITIVE_WORDS="authorization|cookie|password|passwd|pwd|secret|token|api[-_ ]?key|apikey|access[-_]?key|private[-_]?key|credentials?|session|bearer",SENSITIVE_QUICK=new RegExp(SENSITIVE_WORDS,"i"),SENSITIVE_ASSIGNMENT=new RegExp(`(?:${SENSITIVE_WORDS})[A-Za-z0-9_.-]{0,32}(?:\\\\?["'])?[ ]*[:=]`,"i"),KEY_ESCAPE=/\\(?:u([0-9a-fA-F]{4})|U([0-9a-fA-F]{8})|x([0-9a-fA-F]{2})|([0abtnvfre "/\\N_LP\t]))|''/g,KEY_ESCAPE_QUICK=/\\[uUx]/,YAML_ESCAPES={0:"\0",a:"\x07",b:"\b",t:" "," ":" ",n:`\
|
|
184
|
-
|
|
185
|
-
`,v:"\v",f:"\f",r:"\r",e:"\x1B"," ":" ",'"':'"',"/":"/","\\":"\\",N:"\x85",_:"\xA0",L:"\u2028",P:"\u2029"},MAX_CONTINUATION_LINES=200,MAX_ANCHORS=256,MAX_HEREDOCS=MAX_CONTINUATION_LINES,ANCHOR_SCAN_BUDGET=4*1024*1024,ALREADY_REDACTED=/^\[REDACTED\][\s,;}\])"']*$/,BLOCK_SCALAR=/^[|>](?:[+-]\d?|\d[+-]?)?[ \t]*(?:#.*)?$/,YAML_PROPERTIES=/^(?:[!&]\S*[ \t]*)+/,DIFF_HEADER=/^(?:@@|\+\+\+|---)/m,HEREDOC=/(?<!<)<<([-~]?)[ \t]*(?:'([^'\r\n]{1,64})'|"([^"\r\n]{1,64})"|\\?([A-Za-z_][A-Za-z0-9_]{0,63}))(?=$|[\s;|&()<>])/g,
|
|
186
|
-
HEREDOC_START=/(?<!<)<<(?!<)/g,EXPLICIT_KEY_PREFIX=/^[\t +-]*\?[ \t]+/,EXPLICIT_VALUE=/^[\t +-]*:(?=[ \t]|$)[ \t]*/,ANCHOR_DEFINITION=/(?:^|[\s[{,])&([^\s,[\]{}]{1,128})/g,ALIAS_REFERENCE=/(?:^|[\s[{,])\*([^\s,[\]{}]{1,128})/g,BRACKET_TOKENS=new Set(["(","[","{","$(","${"]),MAX_REDACTION_SPANS=1e5;function decodeKeyEscape(match){if(match[1]!==void 0)return String.fromCharCode(Number.parseInt(match[1],16));if(match[2]!==void 0){let codePoint=Number.parseInt(match[2],16);return codePoint<=1114111?
|
|
187
|
-
String.fromCodePoint(codePoint):void 0}return match[3]!==void 0?String.fromCharCode(Number.parseInt(match[3],16)):match[4]!==void 0?YAML_ESCAPES[match[4]]:"'"}function normalizeKeyText(line){KEY_ESCAPE.lastIndex=0;let match=KEY_ESCAPE.exec(line);if(match===null)return{text:line,offsets:void 0};let text="",offsets=[],last=0,append=(chunk,origin,verbatim)=>{for(let index=0;index<chunk.length;index++)offsets.push(verbatim?origin+index:origin);text+=chunk};for(;match!==null;match=KEY_ESCAPE.exec(line)){
|
|
188
|
-
let decoded=decodeKeyEscape(match);decoded!==void 0&&(append(line.slice(last,match.index),last,!0),append(decoded,match.index,!1),last=match.index+match[0].length)}return append(line.slice(last),last,!0),offsets.push(line.length),{text,offsets}}function isMarker(char,spaceIsMarker){return char==="+"||char==="-"||spaceIsMarker&&char===" "}function startsWithMarker(line,diff){let first=line[0];return diff?isMarker(first,!0):first==="+"||first==="-"&&line.length>1&&!/\s/.test(line[1]??"")}function lineIndent(line,strip,dashIsDeeper){
|
|
189
|
-
let index=strip&&isMarker(line[0],!0)?1:0,indent=0;for(;index<line.length;index++){let char=line[index];if(char===" ")indent++;else if(char===" ")indent+=2;else break}return dashIsDeeper&&line[index]==="-"&&(index+1===line.length||/\s/.test(line[index+1]??""))&&indent++,indent}function isBlankLine(line,strip){return line.trim()===""||strip&&isMarker(line[0],!0)&&line.slice(1).trim()===""}function newScan(mode){return{stack:[],mode}}function pushExpansion(text,index,stack,quotes){let next=text[index+
|
|
190
|
-
1];return next==="("||next==="{"||quotes&&(next==="'"||next==='"')?(stack.push(`$${next}`),1):0}function opensBracket(char,top,mode){return mode==="flow"?!0:char==="("?top==="$("||top==="(":char==="{"?mode==="prefix"||top==="${":mode==="prefix"}function scanValue(text,state){let stack=state.stack;for(let index=0;index<text.length;index++){let top=stack[stack.length-1],char=text[index];if(top==="'")char==="'"&&(text[index+1]==="'"?index++:stack.pop());else if(top==="`")char==="\\"?index++:char===
|
|
191
|
-
"`"&&stack.pop();else if(top==='"""'||top==="'''")char==="\\"?index++:char===top[0]&&text.startsWith(top,index)&&(stack.pop(),index+=2);else if(top==="$'")char==="\\"?index++:char==="'"&&stack.pop();else if(top==='"'||top==='$"')char==="\\"?index++:char==='"'?stack.pop():char==="$"&&(index+=pushExpansion(text,index,stack,!1));else if(char==="\\")index++;else if(char==="#"&&top===void 0&&state.mode!=="prefix"){let before=text[index-1];if(index===0||before===" "||before===" ")return}else if(char===
|
|
192
|
-
'"'||char==="'"){let triple=char.repeat(3);text.startsWith(triple,index)?(stack.push(triple),index+=2):stack.push(char)}else char==="`"?stack.push(char):char==="$"?index+=pushExpansion(text,index,stack,!0):char==="("||char==="["||char==="{"?opensBracket(char,top,state.mode)&&stack.push(char):(char===")"&&(top==="$("||top==="(")||char==="}"&&(top==="${"||top==="{")||char==="]"&&top==="[")&&stack.pop()}}function findHeredocs(line){if(!line.includes("<<"))return[];let heredocs=[];HEREDOC.lastIndex=
|
|
193
|
-
0;for(let match=HEREDOC.exec(line);match!==null;match=HEREDOC.exec(line)){let word=match[2]??match[3]??match[4]??"";if(word.trim()==="")return;if(heredocs.length>=MAX_HEREDOCS)throw new Error(CAPACITY_EXCEEDED);heredocs.push({word,mode:match[1]??""})}let openers=0;for(let _match of line.matchAll(HEREDOC_START))if(++openers>MAX_HEREDOCS)throw new Error(CAPACITY_EXCEEDED);if(openers===heredocs.length)return heredocs}function matchHeredocTerminator(active,heredoc,line){let text=line,marker="",first=text[0];
|
|
194
|
-
active.strip&&first!==void 0&&(active.diff?isMarker(first,!0):first===active.marker)&&(marker=first,text=text.slice(1)),text.endsWith("\r")&&(text=text.slice(0,-1));let start=0;if(heredoc.mode!==""){let allowed=heredoc.mode==="-"?" ":" ";for(;start<text.length&&allowed.includes(text[start]??"");)start++}return text.length-start===heredoc.word.length&&text.startsWith(heredoc.word,start)?`${marker}${heredoc.word}`:void 0}function locateAssignment(line){let key=normalizeKeyText(line),match=SENSITIVE_ASSIGNMENT.
|
|
195
|
-
exec(key.text);if(match===null)return;let toOriginal=index=>key.offsets===void 0?index:key.offsets[index]??line.length,value=line.slice(toOriginal(match.index+match[0].length)).trimStart();return{keyStart:toOriginal(match.index),valueStart:line.length-value.length}}function isSensitiveExplicitKey(line){if(!line.includes("?"))return!1;let prefix=EXPLICIT_KEY_PREFIX.exec(line);if(prefix===null)return!1;let name=line.slice(prefix[0].length),comment=name.indexOf(" #");comment>=0&&(name=name.slice(0,
|
|
196
|
-
comment)),name=name.trim();let first=name[0];(first==='"'||first==="'")&&name.length>=2&&name.endsWith(first)&&(name=name.slice(1,-1));let key=normalizeKeyText(`${name}:`);return key.text.length<=65&&SENSITIVE_ASSIGNMENT.test(key.text)}function classifyLine(line,explicitPending){if(explicitPending){if(line.trim()===""||line.trimStart().startsWith("#"))return{located:void 0,pending:!0};let colon=EXPLICIT_VALUE.exec(line);if(colon!==null)return{located:{keyStart:colon[0].indexOf(":"),valueStart:colon[0].
|
|
197
|
-
length},pending:!1}}let located=locateAssignment(line);return{located,pending:located===void 0&&isSensitiveExplicitKey(line)}}function collectAliasNames(text,into){if(!text.includes("*"))return!0;ALIAS_REFERENCE.lastIndex=0;for(let match=ALIAS_REFERENCE.exec(text);match!==null;match=ALIAS_REFERENCE.exec(text)){let name=match[1];if(!(name===void 0||into.has(name))){if(into.size>=MAX_ANCHORS)return!1;into.add(name)}}return!0}function collectAnchorGroups(parts,diff){let groups=[],anchorCount=0,budget=ANCHOR_SCAN_BUDGET;
|
|
198
|
-
for(let index=0;index<parts.length;index+=2){let line=parts[index]??"";if(!line.includes("&"))continue;let anchors=[],first;ANCHOR_DEFINITION.lastIndex=0;for(let match=ANCHOR_DEFINITION.exec(line);match!==null;match=ANCHOR_DEFINITION.exec(line)){let name=match[1];if(name!==void 0){if(++anchorCount>MAX_ANCHORS)return;if(anchors.push(name),first===void 0){let tokenEnd=match.index+match[0].length;first={keyStart:tokenEnd-name.length-1,valueStart:line.length-line.slice(tokenEnd).trimStart().length}}}}
|
|
199
|
-
if(first===void 0)continue;let aliases=new Set,tail=line.slice(first.valueStart);if(budget-=tail.length,budget<0||!collectAliasNames(tail,aliases))return;let continuation=startContinuation(line,first,diff);if(continuation.remaining===0)return;for(let next=index+2;next<parts.length&&continuation.remaining>0;next+=2){let nextLine=parts[next]??"";if(consumeContinuationLine(continuation,nextLine)===void 0)break;if(--continuation.remaining<=0||(budget-=nextLine.length,budget<0||!collectAliasNames(nextLine,
|
|
200
|
-
aliases)))return}groups.push({anchors,aliases})}return groups}function propagateAnchors(roots,parts,diff){let names=new Set(roots),groups=collectAnchorGroups(parts,diff);if(groups===void 0)return{names,overflow:!0};let byAnchor=new Map;groups.forEach((group,groupIndex)=>{for(let anchor of group.anchors){let indexes=byAnchor.get(anchor);indexes===void 0?byAnchor.set(anchor,[groupIndex]):indexes.push(groupIndex)}});let queue=[...roots],expanded=new Set;for(let head=0;head<queue.length;head++)for(let groupIndex of byAnchor.
|
|
201
|
-
get(queue[head]??"")??[])if(!expanded.has(groupIndex)){expanded.add(groupIndex);for(let alias of groups[groupIndex]?.aliases??[])if(!names.has(alias)){if(names.size>=MAX_ANCHORS)return{names,overflow:!0};names.add(alias),queue.push(alias)}}return{names,overflow:!1}}function buildAnchorTable(parts,diff){let roots=new Set,overflow=!1;return processLines(parts,diff,{names:new Set,overflow:!1},text=>{!overflow&&(text===void 0||!collectAliasNames(text,roots))&&(overflow=!0)}),overflow?{names:roots,overflow:!0}:
|
|
202
|
-
roots.size===0?{names:roots,overflow:!1}:propagateAnchors(roots,parts,diff)}function locateAnchorDefinition(line,anchors){if(!(anchors.names.size===0&&!anchors.overflow||!line.includes("&"))){ANCHOR_DEFINITION.lastIndex=0;for(let match=ANCHOR_DEFINITION.exec(line);match!==null;match=ANCHOR_DEFINITION.exec(line)){let name=match[1];if(name===void 0||!(anchors.overflow||anchors.names.has(name)))continue;let tokenEnd=match.index+match[0].length,value=line.slice(tokenEnd).trimStart();return{keyStart:tokenEnd-
|
|
203
|
-
name.length-1,valueStart:line.length-value.length}}}}function indentContinuation(line,diff){let strip=startsWithMarker(line,diff);return{kind:"indent",heredocs:[],scan:newScan("value"),indent:lineIndent(line,strip,!1),strip,marker:strip?line[0]??"":"",diff,dashIsDeeper:!strip&&!line.trimStart().startsWith("-"),remaining:MAX_CONTINUATION_LINES}}function startContinuation(line,located,diff){let continuation=indentContinuation(line,diff),heredocs=findHeredocs(line);if(heredocs===void 0)return continuation.
|
|
204
|
-
remaining=0,continuation;continuation.heredocs=heredocs;let flow=newScan("prefix");if(scanValue(line.slice(0,located.keyStart),flow),flow.stack.some(token=>BRACKET_TOKENS.has(token))&&(flow.mode="flow",scanValue(line.slice(located.keyStart),flow),flow.stack.length>0))return continuation.kind="open",continuation.scan=flow,continuation;let stripped=line.slice(located.valueStart).replace(YAML_PROPERTIES,"");if(stripped===""||stripped[0]==="#"||BLOCK_SCALAR.test(stripped))return continuation;let scan=newScan(
|
|
205
|
-
stripped[0]==="["||stripped[0]==="{"||stripped[0]==="("?"flow":"value");return scanValue(stripped,scan),scan.stack.length>0?(continuation.kind="open",continuation.scan=scan):stripped.trimEnd().endsWith("\\")&&(continuation.kind="backslash"),continuation}function redactedBodyLine(line){return line.trim()===""||ALREADY_REDACTED.test(line.trim())?line:REDACTED}function consumeContinuationLine(active,line){let heredoc=active.heredocs[0];if(heredoc!==void 0){let terminator=matchHeredocTerminator(active,
|
|
206
|
-
heredoc,line);return terminator===void 0?redactedBodyLine(line):(active.heredocs.shift(),terminator)}if(active.kind==="indent")return isBlankLine(line,active.strip)?line:lineIndent(line,active.strip,active.dashIsDeeper)>active.indent?redactedBodyLine(line):void 0;let heredocs=findHeredocs(line);if(heredocs===void 0)return active.remaining=0,REDACTED;for(let found of heredocs){if(active.heredocs.length>=MAX_HEREDOCS)throw new Error(CAPACITY_EXCEEDED);active.heredocs.push(found)}return scanValue(line,
|
|
207
|
-
active.scan),active.scan.stack.length>0?active.kind="open":active.kind=line.trimEnd().endsWith("\\")?"backslash":"indent",redactedBodyLine(line)}function processLines(parts,diff,anchors,collect,mask){let out=[],offset=0,continuation,explicitPending=!1;for(let index=0;index<parts.length;index+=2){let line=parts[index]??"",eol=parts[index+1]??"",start=offset;if(offset+=line.length+eol.length,continuation!==void 0){let replacement=consumeContinuationLine(continuation,line);if(replacement!==void 0){
|
|
208
|
-
if(collect?.(line),replacement!==line&&mask?.(start,start+line.length,replacement),out.push(replacement,eol),continuation.remaining--,continuation.remaining<=0)return collect?.(void 0),mask?.(offset,parts.join("").length,REDACTED),out.push(REDACTED),out.join("");continue}continuation=void 0}let classified=classifyLine(line,explicitPending);explicitPending=classified.pending;let located=classified.located??locateAnchorDefinition(line,anchors);if(located===void 0){out.push(line,eol);continue}let value=line.
|
|
209
|
-
slice(located.valueStart);if(collect?.(value),ALREADY_REDACTED.test(value)){continuation=indentContinuation(line,diff),out.push(line,eol);continue}if(continuation=startContinuation(line,located,diff),out.push(value===""?line:`${line.slice(0,located.valueStart)}${REDACTED}`,eol),value!==""&&value!==REDACTED&&mask?.(start+located.valueStart,start+line.length,REDACTED),continuation.remaining===0)return collect?.(void 0),mask?.(offset,parts.join("").length,REDACTED),out.push(REDACTED),out.join("")}return out.
|
|
210
|
-
join("")}function redactSensitiveLines(text,mask){if(!SENSITIVE_QUICK.test(text)&&!KEY_ESCAPE_QUICK.test(text))return text;let parts=text.split(/(\r\n|\n|\r)/),diff=DIFF_HEADER.test(text),anchors=text.includes("*")&&text.includes("&")?buildAnchorTable(parts,diff):{names:new Set,overflow:!1};return processLines(parts,diff,anchors,void 0,mask)}function checkedLiterals(secrets){let usable=new Set,chars=0;for(let secret of secrets)if(!(secret===""||usable.has(secret))){if(secret.length<MIN_SECRET_LENGTH)
|
|
211
|
-
throw new Error(CAPACITY_EXCEEDED);if(chars+=secret.length,usable.size>=MAX_SECRETS||chars>MAX_SECRET_CHARS)throw new Error(CAPACITY_EXCEEDED);usable.add(secret)}return usable}function kGramHashes(text,k,visit){if(text.length<k)return;let hash=0,power=1;for(let index=0;index<k;index++)hash=Math.imul(hash,31)+text.charCodeAt(index)>>>0,index<k-1&&(power=Math.imul(power,31)>>>0);visit(0,hash);for(let offset=1;offset<=text.length-k;offset++)hash=Math.imul(hash-Math.imul(text.charCodeAt(offset-1),power),
|
|
212
|
-
31)+text.charCodeAt(offset+k-1)>>>0,visit(offset,hash)}var BASE64_LEADING_UNSTABLE=[0,2,3],MAX_VARIANT_CHARS=MAX_TEXT_CHARS;function base64Variants(secret){let bytes=Buffer.from(secret,"utf8"),forms=[];for(let offset=0;offset<3;offset++){let core=Buffer.concat([Buffer.alloc(offset),bytes]).toString("base64").replace(/=+$/,"");(offset+bytes.length)%3!==0&&(core=core.slice(0,-1)),core=core.slice(BASE64_LEADING_UNSTABLE[offset]),forms.push(core,core.replace(/\+/g,"-").replace(/\//g,"_"))}return forms.
|
|
213
|
-
filter(form=>form.length>=8)}function buildLiteralCoverage(secrets){let registered=checkedLiterals(secrets);if(registered.size===0)return;let usable=new Set(registered),base64Forms=new Set,variantChars=0;for(let secret of registered)for(let form of base64Variants(secret))if(!usable.has(form)){if(variantChars+=form.length,variantChars>MAX_VARIANT_CHARS)throw new Error(CAPACITY_EXCEEDED);usable.add(form),base64Forms.add(form)}let fragments=new Map;for(let secret of[...usable].sort((a,b)=>a.length-
|
|
214
|
-
b.length))kGramHashes(secret,8,(offset,hash)=>{let hits=fragments.get(hash);hits===void 0&&(hits=new Map,fragments.set(hash,hits));let offsets=hits.get(secret);offsets===void 0?hits.set(secret,[offset]):offsets.push(offset)});let indexed=new Map,minThreshold=1/0;for(let[hash,hits]of fragments)indexed.set(hash,[...hits].map(([secret,origins])=>{let threshold=Math.min(secret.length,Math.max(8,Math.ceil(secret.length/2)));return minThreshold=Math.min(minThreshold,threshold),{secret,threshold,origins,
|
|
215
|
-
base64:base64Forms.has(secret)}}));return{fragments:indexed,minThreshold}}var BASE64_EDGE_BEFORE=3,BASE64_CHAR=/^[A-Za-z0-9+/_-]$/;function maskFragments(text,coverage,work,mask){if(text.length<coverage.minThreshold)return;let covered=new Map,equal=(left,secret,right)=>{if(++work.comparisons>MAX_TEXT_CHARS)throw new Error(CAPACITY_EXCEEDED);return text.charCodeAt(left)===secret.charCodeAt(right)};kGramHashes(text,8,(offset,hash)=>{let entries=coverage.fragments.get(hash);if(entries!==void 0)for(let{
|
|
216
|
-
secret,threshold,origins,base64}of entries){if(++work.candidates>MAX_REDACTION_SPANS*10)throw new Error(CAPACITY_EXCEEDED);if(text.length<threshold)break;for(let origin of origins){if(++work.candidates>MAX_REDACTION_SPANS*10)throw new Error(CAPACITY_EXCEEDED);let diagonal=offset-origin,runs=covered.get(secret);if((runs?.get(diagonal)??-1)>=offset+8)continue;let seed=0;for(;seed<8&&equal(offset+seed,secret,origin+seed);)seed++;if(seed<8)continue;let start=offset,end=offset+8;for(;start>0&&start-diagonal>
|
|
217
|
-
0&&equal(start-1,secret,start-diagonal-1);)start--;for(;end<text.length&&end-diagonal<secret.length&&equal(end,secret,end-diagonal);)end++;if(runs===void 0&&(runs=new Map,covered.set(secret,runs)),runs.set(diagonal,end),end-start>=threshold){if(++work.matches>MAX_REDACTION_SPANS)throw new Error(CAPACITY_EXCEEDED);if(base64){let from=start;for(;from>0&&start-from<BASE64_EDGE_BEFORE&&BASE64_CHAR.test(text[from-1]??"");)from--;let to=end;for(BASE64_CHAR.test(text[to]??"")&&to++;to<text.length&&text[to]===
|
|
218
|
-
"=";)to++;mask(from,to)}else mask(start,end)}}}})}var IGNORABLE=String.raw`[\p{Cf}\p{Default_Ignorable_Code_Point}]`,VIEW_TRIGGER=new RegExp(String.raw`${IGNORABLE}|\\|%[0-9a-fA-F]{2}`,"u"),VIEW_TOKEN=new RegExp(String.raw`${IGNORABLE}|(?<!\\)\\+(?:u\{([0-9a-fA-F]{1,6})\}|u([0-9a-fA-F]{4})|U([0-9a-fA-F]{8})|x([0-9a-fA-F]{2})|(["/bfnrt])?)|(?:%[0-9a-fA-F]{2})+`,"gu"),WRAP_TOKEN=/(?<=[A-Za-z0-9+/_=-])\\?[ \t]*(?:[\r\n\f\v\u0085\u2028\u2029][ \t]*(?:[>#][ \t]*)?)+(?=[A-Za-z0-9+/_-])/gu,LINE_BREAK=/[\r\n\f\v\u0085\u2028\u2029]/,
|
|
219
|
-
WRAP_PROBE=new RegExp(WRAP_TOKEN.source,"u"),JSON_ESCAPES={b:"\b",f:"\f",n:`
|
|
220
|
-
`,r:"\r",t:" "},MAX_VIEW_PASSES=6,MAX_HALVED_RUN=64,ESCAPE_RUN=new RegExp(String.raw`(?<!\\)\\{2,${MAX_HALVED_RUN}}[ux]`),MAX_VIEW_CHARS=4*MAX_TEXT_CHARS,hexValue=code=>code<=57?code-48:(code|32)-87,isContinuation=byte=>byte>=128&&byte<=191;function utf8CodePointAt(byteAt,index,count){let lead=byteAt(index);if(lead>=194&&lead<=223)return index+1>=count||!isContinuation(byteAt(index+1))?void 0:{cp:(lead&31)<<6|byteAt(index+1)&63,length:2};if(lead>=224&&lead<=239){if(index+2>=count)return;let second=byteAt(
|
|
221
|
-
index+1),third=byteAt(index+2);return!isContinuation(second)||!isContinuation(third)||lead===224&&second<160||lead===237&&second>159?void 0:{cp:(lead&15)<<12|(second&63)<<6|third&63,length:3}}if(lead>=240&&lead<=244){if(index+3>=count)return;let second=byteAt(index+1);return!isContinuation(second)||!isContinuation(byteAt(index+2))||!isContinuation(byteAt(index+3))||lead===240&&second<144||lead===244&&second>143?void 0:{cp:(lead&7)<<18|(second&63)<<12|(byteAt(index+2)&63)<<6|byteAt(index+3)&63,length:4}}}
|
|
222
|
-
function decodePercentRun(run,put){let count=run.length/3,byteAt=index=>hexValue(run.charCodeAt(index*3+1))<<4|hexValue(run.charCodeAt(index*3+2)),decodedAny=!1;for(let index=0;index<count;){let lead=byteAt(index);if(lead<128){put(String.fromCharCode(lead),index,index+1),decodedAny=!0,index++;continue}let sequence=utf8CodePointAt(byteAt,index,count);sequence!==void 0?(put(String.fromCodePoint(sequence.cp),index,index+sequence.length),decodedAny=!0,index+=sequence.length):(put(run.slice(index*3,index*
|
|
223
|
-
3+3),index,index+1),index++)}return decodedAny}function viewPass(text,starts,ends,tokens=VIEW_TOKEN,halveEscapes=!1){let out=[],outStarts=new Uint32Array(text.length),outEnds=new Uint32Array(text.length),count=0,put=(decoded,from,to)=>{out.push(decoded);let first=starts?.[from]??from,end=ends?.[to-1]??to;for(let index=0;index<decoded.length;index++)outStarts[count]=first,outEnds[count++]=end},keep=(from,to)=>{out.push(text.slice(from,to));for(let index=from;index<to;index++)outStarts[count]=starts?.[index]??
|
|
224
|
-
index,outEnds[count++]=ends?.[index]??index+1},last=0,changed=!1,structural=!1,wrap=tokens===WRAP_TOKEN;for(let match of text.matchAll(tokens)){let token=match[0],from=match.index,to=from+token.length;if(wrap){keep(last,from),last=to,changed=!0;continue}let wasStructural=structural;if(structural=!0,token.startsWith("%")){keep(last,from),decodePercentRun(token,(decoded,first,end)=>put(decoded,from+first*3,from+end*3))&&(changed=!0),last=to;continue}if(token.startsWith("\\")){let unit=token.search(
|
|
225
|
-
/[^\\]/),run=unit===-1?token.length:unit,escaped=match[1]??match[2]??match[3]??match[4],letter=match[5];if(run===1&&escaped===void 0&&letter===void 0){structural=wasStructural;continue}let rest=token.slice(run);if(escaped!==void 0&&!(halveEscapes&&run>=2&&run<=MAX_HALVED_RUN)){let codePoint=match[1]!==void 0||match[3]!==void 0?Number.parseInt(match[1]??match[3],16):0;if(codePoint>1114111){structural=wasStructural;continue}keep(last,from),put(codePoint>0?String.fromCodePoint(codePoint):String.fromCharCode(
|
|
226
|
-
Number.parseInt(escaped,16)),from,to)}else if(escaped===void 0&&letter!==void 0&&run%2===1){keep(last,from);for(let pair=0;pair<Math.floor(run/2);pair++)put("\\",from+pair*2,from+pair*2+2);put(JSON_ESCAPES[letter]??letter,to-2,to)}else{structural=wasStructural,keep(last,from);for(let pair=0;pair<Math.floor(run/2);pair++)put("\\",from+pair*2,from+pair*2+2);run%2===1&&letter===void 0&&put("\\",from+run-1,from+run),rest!==""&&put(rest,to-rest.length,to)}last=to,changed=!0;continue}keep(last,from),last=
|
|
227
|
-
to,changed=!0}return keep(last,text.length),{text:changed?out.join(""):text,starts:outStarts.subarray(0,count),ends:outEnds.subarray(0,count),changed,structural}}function eachView(text,work,visit,withHalved=!0){let charge=current=>{if(work.viewChars+=current.length,work.viewChars>MAX_VIEW_CHARS)throw new Error(CAPACITY_EXCEEDED)},halved=from=>{let view2=from,structural2=0;for(;;){let current=view2?.text??text;if(!ESCAPE_RUN.test(current))return;charge(current);let next=viewPass(current,view2?.starts,
|
|
228
|
-
view2?.ends,VIEW_TOKEN,!0);if(!next.changed)return;if(next.structural&&++structural2>MAX_VIEW_PASSES)throw new Error(CAPACITY_EXCEEDED);view2=next,visit(view2)}};withHalved&&halved(void 0);let view,structural=0;for(;;){let current=view?.text??text;if(!VIEW_TRIGGER.test(current))return;charge(current);let next=viewPass(current,view?.starts,view?.ends);if(!next.changed)return;if(next.structural&&++structural>MAX_VIEW_PASSES)throw new Error(CAPACITY_EXCEEDED);view=next,visit(view),withHalved&&halved(
|
|
229
|
-
view)}}function decodeEscapes(text){let last;return eachView(text,{candidates:0,comparisons:0,matches:0,viewChars:0},view=>{last=view},!1),last}function joinWrappedLines(text,view,work){let current=view?.text??text;if(!LINE_BREAK.test(current)||!WRAP_PROBE.test(current))return;if(work.viewChars+=current.length,work.viewChars>MAX_VIEW_CHARS)throw new Error(CAPACITY_EXCEEDED);let joined=viewPass(current,view?.starts,view?.ends,WRAP_TOKEN);return joined.changed?joined:void 0}function redactTextWith(text,coverage,work){
|
|
230
|
-
if(text.length>MAX_TEXT_CHARS)throw new Error(CAPACITY_EXCEEDED);let spans=[],mask=(start,end,replacement=REDACTED)=>{if(!(start>=end)){if(spans.length>=MAX_REDACTION_SPANS*10)throw new Error(CAPACITY_EXCEEDED);spans.push({start,end,replacement})}};if(coverage!==void 0){maskFragments(text,coverage,work,mask);let scan=candidate=>{candidate!==void 0&&maskFragments(candidate.text,coverage,work,(start,end)=>{mask(candidate.starts[start]??0,candidate.ends[end-1]??text.length)})};scan(joinWrappedLines(
|
|
231
|
-
text,void 0,work)),eachView(text,work,view=>{scan(view),scan(joinWrappedLines(text,view,work))})}redactSensitiveLines(text,mask);for(let pattern of[...SECRET_PATTERNS,ASSIGNMENT_PATTERN]){pattern.lastIndex=0;for(let match=pattern.exec(text);match!==null;match=pattern.exec(text))mask(match.index+(pattern===ASSIGNMENT_PATTERN?match[1]?.length??0:0),match.index+match[0].length)}spans.sort((a,b)=>a.start-b.start||b.end-a.end);let merged=[];for(let span of spans){let previous=merged[merged.length-1];
|
|
232
|
-
previous!==void 0&&span.start<=previous.end?(previous.end=Math.max(previous.end,span.end),span.replacement===REDACTED&&(previous.replacement=REDACTED)):merged.push({...span})}let chunks=[],offset=0;for(let span of merged)chunks.push(text.slice(offset,span.start),span.replacement),offset=span.end;chunks.push(text.slice(offset));let out=chunks.join("");return{text:out,redacted:out!==text}}function childFieldPath(parent,key){if(!PATH_SEGMENT.test(key))return parent;let path=`${parent}.${key}`;return path.
|
|
233
|
-
length>FIELD_PATH_MAX?parent:path}function isAncestor(chain,candidate){for(let node=chain;node!==null;node=node.parent)if(node.source===candidate)return!0;return!1}function collapseToTopLevel(paths,basePath){let baseSegments=basePath.split(".").length,collapsed=new Set;for(let path of paths)collapsed.add(path.split(".").slice(0,baseSegments+1).join("."));return[...collapsed]}function redactJsonWith(value,basePath,literal,maxNodes,maxDepth){let removed=new Set,truncatedPaths=new Set,truncated=!1,nodes=0,textChars=0,work={candidates:0,comparisons:0,matches:0,viewChars:0},markTruncated=path=>{truncated=!0,truncatedPaths.add(path)},convert=(input,path,depth,ancestry,stack2,collapsed)=>{if(input===null)return null;switch(typeof input){case"boolean":return input;case"number":{if(!Number.isFinite(input))return null;let text=String(input),safe=convert(text,path,depth,ancestry,
|
|
234
|
-
stack2,collapsed);return safe===text?input:safe}case"bigint":return convert(input.toString(),path,depth,ancestry,stack2,collapsed);case"string":{if(textChars+=input.length,textChars>MAX_TEXT_CHARS)throw new Error(CAPACITY_EXCEEDED);let result=redactTextWith(input,literal,work);return result.redacted&&removed.add(path),result.text}case"object":break;default:return}if(input instanceof Date)return Number.isNaN(input.getTime())?null:convert(input.toISOString(),path,depth,ancestry,stack2,collapsed);if(isAncestor(
|
|
235
|
-
ancestry,input))return markTruncated(path),CIRCULAR;if(depth>maxDepth)return markTruncated(path),TRUNCATED;let target=Array.isArray(input)?[]:{};return stack2.push({source:input,target,path,depth,ancestry:{source:input,parent:ancestry},collapsed:collapsed||Array.isArray(input)}),target},rootStack=[],root=convert(value,basePath,1,null,rootStack,!1);nodes++;let stack=rootStack;for(;stack.length>0;){let frame=stack.pop();if(frame===void 0)break;let{source,target,path,depth,ancestry,collapsed}=frame;
|
|
236
|
-
if(Array.isArray(source)&&Array.isArray(target)){for(let index=0;index<source.length;index++){if(nodes>=maxNodes){markTruncated(path);break}let item;try{item=source[index]}catch{item=void 0}nodes++;let converted=convert(item,path,depth+1,ancestry,stack,!0);target.push(converted===void 0?null:converted)}continue}if(Array.isArray(target))continue;let keys2;try{keys2=Object.keys(source)}catch{markTruncated(path);continue}let placeholders=0;for(let key of keys2){if(FORBIDDEN_KEYS.has(key)){markTruncated(
|
|
237
|
-
path);continue}if(nodes>=maxNodes){markTruncated(path);break}if(textChars+=key.length,textChars>MAX_TEXT_CHARS)throw new Error(CAPACITY_EXCEEDED);let outKey=key,childPath=collapsed?path:childFieldPath(path,key);if(redactTextWith(key,literal,work).redacted){do outKey=`redacted_key_${placeholders++}`;while(outKey in target||Object.hasOwn(source,outKey));childPath=path,removed.add(path)}let item;try{item=source[key]}catch{markTruncated(path);continue}if(nodes++,isSensitiveKey(key)&&item!=null&&item!==
|
|
238
|
-
""){target[outKey]=REDACTED,removed.add(childPath);continue}let converted=convert(item,childPath,depth+1,ancestry,stack,collapsed);converted!==void 0&&(target[outKey]=converted)}}return{value:root??null,removedFieldPaths:boundPaths(removed,basePath),truncated,truncatedFieldPaths:boundPaths(truncatedPaths,basePath)}}function boundPaths(paths,basePath){return paths.size>DH_MAX_REMOVED_FIELD_PATHS?collapseToTopLevel(paths,basePath):[...paths]}function getTraceEnvSecrets(env){return Object.entries(env).
|
|
239
|
-
filter(([name,value])=>value!==void 0&&value!==""&&SENSITIVE_ENV_NAME.test(name)).map(([,value])=>value)}function createTraceRedactor(options={}){let secrets=new Set,literal,chars=0,capacityExceeded=!1,disable=()=>{capacityExceeded=!0,secrets.clear(),literal=void 0},add=secret=>{if(capacityExceeded)return!1;if(secret===""||secrets.has(secret))return!0;if(secret.length<MIN_SECRET_LENGTH||secrets.size>=MAX_SECRETS||chars+secret.length>MAX_SECRET_CHARS)return disable(),!1;secrets.add(secret);try{literal=
|
|
240
|
-
buildLiteralCoverage([...secrets])}catch{return disable(),!1}return chars+=secret.length,!0},pattern=()=>{if(capacityExceeded)throw new Error(CAPACITY_EXCEEDED);return literal};for(let secret of options.extraSecrets??[])add(secret);for(let[name,secret]of Object.entries(options.env??{}))secret!==void 0&&SENSITIVE_ENV_NAME.test(name)&&add(secret);return{redactJson:(value,basePath,limits)=>redactJsonWith(value,basePath,pattern(),limits?.maxNodes??DEFAULT_MAX_NODES,limits?.maxDepth??DEFAULT_MAX_DEPTH),
|
|
241
|
-
redactText:text=>redactTextWith(text,pattern(),{candidates:0,comparisons:0,matches:0,viewChars:0}),addSecret:add,disable}}import{createHash as createHash5}from"node:crypto";import{closeSync as closeSync3,constants as constants5,fstatSync as fstatSync3,fsyncSync as fsyncSync3,writeSync as writeSync3}from"node:fs";import{join as join6}from"node:path";var TRACE_RESPONSE_MAX_BYTES=1024*1024,TRACE_DEFAULT_REQUEST_TIMEOUT_MS=3e4,TRACE_RETRY_AFTER_MAX_MS=3e5,TraceTransportError=class extends Error{retryable;status;retryAfterMs;retryAfterExceeded;constructor(message,options){super(message),this.name="TraceTransportError",this.stack=`${this.name}: ${message}`,this.retryable=options.retryable,this.status=options.status,this.retryAfterMs=options.retryAfterMs,this.retryAfterExceeded=options.retryAfterExceeded===!0}},SHA256_HEX=/^[0-9a-f]{64}$/,JSON_MEDIA_TYPE=/^application\/json\s*(;\s*charset\s*=\s*"?utf-8"?\s*)?$/i,
|
|
242
|
+
child.externalIds!==void 0&&child.externalIds.length>0?set[TRACE_ENV.externalIds]=JSON.stringify(child.externalIds):unset.push(TRACE_ENV.externalIds),{set,unset}}import{createHash as createHash5}from"node:crypto";import{closeSync as closeSync3,constants as constants5,fstatSync as fstatSync3,fsyncSync as fsyncSync3,writeSync as writeSync3}from"node:fs";import{join as join6}from"node:path";var TRACE_RESPONSE_MAX_BYTES=1024*1024,TRACE_DEFAULT_REQUEST_TIMEOUT_MS=3e4,TRACE_RETRY_AFTER_MAX_MS=3e5,TraceTransportError=class extends Error{retryable;status;retryAfterMs;retryAfterExceeded;constructor(message,options){super(message),this.name="TraceTransportError",this.stack=`${this.name}: ${message}`,this.retryable=options.retryable,this.status=options.status,this.retryAfterMs=options.retryAfterMs,this.retryAfterExceeded=options.retryAfterExceeded===!0}},SHA256_HEX=/^[0-9a-f]{64}$/,JSON_MEDIA_TYPE=/^application\/json\s*(;\s*charset\s*=\s*"?utf-8"?\s*)?$/i,
|
|
242
243
|
LOOPBACK_HOSTS=new Set(["127.0.0.1","localhost"]);function hasControlChars2(value){for(let i=0;i<value.length;i++){let code=value.charCodeAt(i);if(code<32||code===127)return!0}return!1}function parseTraceIngestUrl(ingestUrl,allowInsecureLoopback){let url;try{url=new URL(ingestUrl)}catch{throw new TraceTransportError("ingest URL is not a valid URL",{retryable:!1})}let secure=url.protocol==="https:",loopback=url.protocol==="http:"&&allowInsecureLoopback&&LOOPBACK_HOSTS.has(url.hostname);if(!secure&&
|
|
243
244
|
!loopback)throw new TraceTransportError("ingest URL must use https",{retryable:!1});if(url.username!==""||url.password!=="")throw new TraceTransportError("ingest URL must not contain credentials",{retryable:!1});if(url.search!==""||url.hash!=="")throw new TraceTransportError("ingest URL must not contain a query or fragment",{retryable:!1});return url}function isRetryableStatus(status){return status===408||status===425||status===429||status>=500}function parseRetryAfterMs(value,now){if(value===null)
|
|
244
245
|
return;let text=value.trim();if(/^\d{1,9}$/.test(text))return Number(text)*1e3;let at=Date.parse(text);return Number.isNaN(at)||!/[A-Za-z]/.test(text)?void 0:Math.max(0,at-now)}var HttpTraceIngestTransport=class{startsRequestsSynchronously=!0;scope;reauthorize;base;token;originDelegationId;timeoutMs;fetchImpl;constructor(options){let url=parseTraceIngestUrl(options.ingestUrl,options.allowInsecureLoopback===!0);if(options.token===""||hasControlChars2(options.token))throw new TraceTransportError("\
|
|
@@ -309,6 +310,6 @@ activeSignal,run=signal=>{let observed=current.then(()=>(activeSignal=signal,upl
|
|
|
309
310
|
intervalMs),timer.unref())},stopping,stop=()=>(stopping??=(async()=>{stopped=!0,timer!==void 0&&clearTimeout(timer),inflight.abort();try{await current}catch{return{status:"failed",reason:"uploader_stop_failed"}}return failed?{status:"failed",reason:"upload_incomplete"}:{status:"clean"}})(),stopping);return options.signal?.addEventListener("abort",()=>{stop()},{once:!0}),options.signal?.aborted?stopped=!0:schedule(),{stop,flush:async timeoutMs=>{if(stopped)return projectUploadReport({locked:!1,aborted:!0,
|
|
310
311
|
streams:[],error:"upload_failed"});let controller=new AbortController,onStop=()=>controller.abort();inflight.signal.addEventListener("abort",onStop,{once:!0});let timedOut=Promise.withResolvers(),deadline=setTimeout(()=>{failed=!0,controller.abort();let progress=uploadProgress.get(controller.signal)??(activeSignal?uploadProgress.get(activeSignal):void 0);timedOut.resolve(projectUploadReport({...progress,timeout:!0,locked:!1,aborted:!0,streams:(progress?.streams??[]).map(stream=>({...stream,acked:stream.
|
|
311
312
|
committedAcked??{events:0,artifacts:0},pendingIsLowerBound:!0,incomplete:!0})),error:"upload_failed"}))},timeoutMs);try{return await Promise.race([run(controller.signal),timedOut.promise])}finally{clearTimeout(deadline),inflight.signal.removeEventListener("abort",onStop)}}}}export{TraceScopeError,TraceLoginError,TraceClientReauthRequired,TraceAccessDenied,TraceClientProtocolError,TRACE_PERMISSIONS,validateTraceGrantScope,isScopeWithin,scopesEqual,assertScopeAllowsAll,DEFAULT_REQUEST_TIMEOUT_MS,DEFAULT_MAX_JSON_BYTES,normalizeBaseUrl,withTimeout,readBoundedBytes,readBoundedJson,isRecord,traceOAuthErrorCode,TraceTokenOutcomeUnknown,TraceInvalidGrant,requestToken,requestRevoke,PROFILE_LOCK_DIR_NAME,PROFILE_LOCK_DEFAULT_WAIT_MS,lockFileName,withProfileLock,TraceCredentialStoreError,
|
|
312
|
-
spawnCommand,systemTraceCredentialProbes,createDefaultTraceCredentialStore,lazyValidator,mintTraceId,isTraceId,toAllowlistedErrno,markSpoolQuarantinedInProcess,isSpoolQuarantinedInProcess,inspectTraceSpoolQuarantine,QuarantineGateError,withQuarantineGate,admitTraceCapture,verifyAdmittedCaptureGuard,removeCleanCaptureGuard,publishQuarantineMarker,scheduleQuarantineMarkerRetry,
|
|
313
|
-
assertTraceSpoolSecure,readTraceStateFile,writeTraceFileAtomic,fsyncDir,acquireTraceSpoolLock,TraceStreamWriter,readTraceStream,verifyTraceStreamOffset,traceStreamPrefixChain,summarizeTraceStream,listTraceStreams,readTraceArtifactBytes,checkTraceArtifact,parseTraceSpoolBinding,readTraceStreamBinding,writeTraceStreamBinding,TRACE_ENV,traceCaptureDisabledReason,setTraceCredentialIntake,
|
|
314
|
-
|
|
313
|
+
spawnCommand,systemTraceCredentialProbes,createDefaultTraceCredentialStore,TRACE_REDACTION_POLICY_ID,TRACE_REDACTION_POLICY_VERSION,decodeEscapes,getTraceEnvSecrets,createTraceRedactor,sanitizeForTerminal,lazyValidator,mintTraceId,isTraceId,toAllowlistedErrno,markSpoolQuarantinedInProcess,isSpoolQuarantinedInProcess,inspectTraceSpoolQuarantine,QuarantineGateError,withQuarantineGate,admitTraceCapture,verifyAdmittedCaptureGuard,removeCleanCaptureGuard,publishQuarantineMarker,scheduleQuarantineMarkerRetry,
|
|
314
|
+
beginQuarantineRelease,commitQuarantineRelease,traceStreamsDir,TraceSpoolSecurityError,resolveTraceSpoolDir,ensureTraceSpoolDirs,assertTraceSpoolSecure,readTraceStateFile,writeTraceFileAtomic,fsyncDir,acquireTraceSpoolLock,TraceStreamWriter,readTraceStream,verifyTraceStreamOffset,traceStreamPrefixChain,summarizeTraceStream,listTraceStreams,readTraceArtifactBytes,checkTraceArtifact,parseTraceSpoolBinding,readTraceStreamBinding,writeTraceStreamBinding,TRACE_ENV,traceCaptureDisabledReason,setTraceCredentialIntake,
|
|
315
|
+
takeTraceIngestCredentials,consumeTraceIngestToken,readTraceProducerConfig,consumeTraceProducerConfig,buildChildTraceEnv,HttpTraceIngestTransport,abortTraceUploads,isUploadReportClean,traceCursorPath,traceRejectionsPath,TraceUploader,startBackgroundUploader};
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url);
|
|
2
|
+
function peerHandle(id,liveIds){let compact=id.replace(/-/g,""),length=Math.min(4,compact.length);for(;length<compact.length&&liveIds.some(other=>other!==id&&other.replace(/-/g,"").endsWith(compact.slice(-length)));)length++;return compact.slice(-length)}function resolveHandleTargets(sessions,target){let compact=target.replace(/-/g,"");return compact.length<4?[]:sessions.filter(session=>session.info.id.replace(/-/g,"").endsWith(compact))}function resolveExactTargets(sessions,target,scopeId){let exact=sessions.
|
|
3
|
+
filter(session=>session.info.id===target);if(exact.length)return exact;let lower=target.toLowerCase(),qualified=sessions.filter(session=>session.info.repo!==void 0&&session.info.name!==void 0&&`${session.info.repo}/${session.info.name}`===target);if(qualified.length)return qualified;let names=sessions.filter(session=>session.info.name?.toLowerCase()===lower),local=names.filter(session=>session.scopeId===scopeId);return local.length?local:names}function resolvePrefixTargets(sessions,target,scopeId){
|
|
4
|
+
if(!target)return[];let ids=sessions.filter(session=>session.info.id.startsWith(target));if(ids.length)return ids;let lower=target.toLowerCase(),names=sessions.filter(session=>session.info.name?.toLowerCase().startsWith(lower)),local=names.filter(session=>session.scopeId===scopeId);return local.length?local:names}function matchesPeer(session,filters){return(!filters.repo||(session.repo??"").toLowerCase().includes(filters.repo.toLowerCase()))&&(!filters.query||[session.repo,session.branch,session.
|
|
5
|
+
name,session.focus].some(field=>field?.toLowerCase().includes(filters.query.toLowerCase())))&&(!filters.path||(session.subpath??"").startsWith(filters.path)||(session.touchedPaths??[]).some(entry=>entry.path.startsWith(filters.path)))}import{createHash}from"node:crypto";var MAX_MESSAGE_ID_CHARS=128,ID_IN_USE_DETAIL="message id is still held by another sender; retry later";function isValidMessageId(value){return typeof value=="string"&&value.length>0&&value.length<=MAX_MESSAGE_ID_CHARS}var MAX_SESSION_FIELD_CHARS={id:256,name:256,model:256,status:256,branch:256,cwd:4096,worktreeRoot:4096,repo:256,focus:256,subpath:4096};function isRecord(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)}function isBoundedString(value,maxChars){
|
|
6
|
+
return typeof value=="string"&&value.length<=maxChars}function isOptionalBoundedString(value,maxChars){return value===void 0||isBoundedString(value,maxChars)}function isMessageReceiptStatus(value){return value==="receiver_received"||value==="queued"||value==="injected"||value==="not_injected"||value==="deferred"||value==="acknowledged"||value==="expired"||value==="cancelled"||value==="superseded"||value==="cancellation_requested"}var MAX_RECEIPT_DETAIL_CHARS=1024,MAX_REQUEST_ID_CHARS=256,WORST_CASE_REQUEST_ID="\
|
|
7
|
+
".repeat(MAX_REQUEST_ID_CHARS);function truncateChars(text,maxChars){if(text.length<=maxChars)return text;let cut=text.slice(0,maxChars),last=cut.charCodeAt(cut.length-1);return last>=55296&&last<=56319?cut.slice(0,-1):cut}function canonicalMessageReceipt(receipt){return{messageId:receipt.messageId,status:receipt.status,timestamp:receipt.timestamp,...receipt.detail!==void 0?{detail:truncateChars(receipt.detail,MAX_RECEIPT_DETAIL_CHARS)}:{}}}function isMessageReceipt(value){return!isRecord(value)||
|
|
8
|
+
typeof value.messageId!="string"||!isMessageReceiptStatus(value.status)||typeof value.timestamp!="number"?!1:value.detail===void 0||typeof value.detail=="string"}function isMessageControl(value){return!isRecord(value)||typeof value.messageId!="string"||typeof value.timestamp!="number"||value.action!=="cancel"&&value.action!=="supersede"||value.supersededBy!==void 0&&typeof value.supersededBy!="string"?!1:value.detail===void 0||typeof value.detail=="string"}function isAttachment(value){return!isRecord(
|
|
9
|
+
value)||value.type!=="file"&&value.type!=="snippet"&&value.type!=="context"||typeof value.name!="string"||typeof value.content!="string"?!1:value.language===void 0||typeof value.language=="string"}function isMessageProvenance(value){return isRecord(value)?value.type==="extension_outbox"&&typeof value.extensionId=="string"&&typeof value.extensionName=="string"&&typeof value.requestId=="string":!1}function isMessage(value){if(!isRecord(value)||typeof value.id!="string"||typeof value.timestamp!="nu\
|
|
10
|
+
mber")return!1;for(let key of["senderSequence","brokerReceivedAt","brokerDeliveredAt","receiverReceivedAt","injectedAt"])if(value[key]!==void 0&&typeof value[key]!="number")return!1;if(value.supersedes!==void 0&&typeof value.supersedes!="string"||value.retryOf!==void 0&&typeof value.retryOf!="string"||value.replyTo!==void 0&&typeof value.replyTo!="string"||value.expectsReply!==void 0&&typeof value.expectsReply!="boolean"||value.broadcast!==void 0&&typeof value.broadcast!="boolean"||value.intent!==
|
|
11
|
+
void 0&&value.intent!=="question"&&value.intent!=="notice"||value.kind!==void 0&&value.kind!=="answer"&&value.kind!=="ack"&&value.kind!=="decline")return!1;if(value.audience!==void 0){if(!isRecord(value.audience)||!isOptionalBoundedString(value.audience.repo,256))return!1;for(let[field,cap,length]of[["sessions",64,256],["paths",32,4096]]){let list=value.audience[field];if(list!==void 0&&(!Array.isArray(list)||list.length>cap||!list.every(entry=>isBoundedString(entry,length))))return!1}}return value.
|
|
12
|
+
provenance!==void 0&&!isMessageProvenance(value.provenance)||!isRecord(value.content)||typeof value.content.text!="string"?!1:value.content.attachments===void 0||Array.isArray(value.content.attachments)&&value.content.attachments.every(isAttachment)}function messageDeliveryFingerprint(message,targetId){let canonical=JSON.stringify({targetId,text:message.content.text,attachments:message.content.attachments,replyTo:message.replyTo,expectsReply:message.expectsReply,supersedes:message.supersedes,retryOf:message.
|
|
13
|
+
retryOf,provenance:message.provenance,broadcast:message.broadcast,intent:message.intent,audience:message.audience,kind:message.kind});return createHash("sha256").update(canonical).digest("hex")}function isTouchedPaths(value){return Array.isArray(value)&&value.length<=20&&value.every(entry=>isRecord(entry)&&isBoundedString(entry.path,4096)&&entry.path.length>0&&!entry.path.startsWith("/")&&!entry.path.split("/").includes("..")&&typeof entry.timestamp=="number"&&Number.isFinite(entry.timestamp)&&entry.
|
|
14
|
+
timestamp>=0)&&new Set(value.map(entry=>entry.path)).size===value.length}function isDiscoveryPresence(value){return isOptionalBoundedString(value.repo,256)&&isOptionalBoundedString(value.focus,256)&&(value.focus===void 0||!/[\r\n\u2028\u2029]/.test(String(value.focus)))&&isOptionalBoundedString(value.subpath,4096)&&(value.touchedPaths===void 0||isTouchedPaths(value.touchedPaths))}function isSessionInfo(value){if(!isRecord(value)||!isBoundedString(value.id,MAX_SESSION_FIELD_CHARS.id)||!isBoundedString(
|
|
15
|
+
value.cwd,MAX_SESSION_FIELD_CHARS.cwd)||!isBoundedString(value.model,MAX_SESSION_FIELD_CHARS.model)||typeof value.pid!="number"||typeof value.startedAt!="number"||typeof value.lastActivity!="number"||!isOptionalBoundedString(value.handle,MAX_SESSION_FIELD_CHARS.id)||value.endpointEpoch!==void 0&&typeof value.endpointEpoch!="string"||!isOptionalBoundedString(value.name,MAX_SESSION_FIELD_CHARS.name)||value.runtimeFallbackAlias!==void 0&&typeof value.runtimeFallbackAlias!="boolean"||!isOptionalBoundedString(
|
|
16
|
+
value.status,MAX_SESSION_FIELD_CHARS.status)||value.peerUid!==void 0&&typeof value.peerUid!="number")return!1;for(let key of["contextPct","contextTokens","contextWindow"])if(value[key]!==void 0&&typeof value[key]!="number")return!1;return!isOptionalBoundedString(value.worktreeRoot,MAX_SESSION_FIELD_CHARS.worktreeRoot)||!isOptionalBoundedString(value.branch,MAX_SESSION_FIELD_CHARS.branch)?!1:isDiscoveryPresence(value)&&(value.trustedLocal===void 0||typeof value.trustedLocal=="boolean")}function isSessionId(value){
|
|
17
|
+
return isBoundedString(value,MAX_SESSION_FIELD_CHARS.id)&&value.trim().length>0}function isSessionRegistration(value){return!isRecord(value)||!isBoundedString(value.cwd,MAX_SESSION_FIELD_CHARS.cwd)||!isBoundedString(value.model,MAX_SESSION_FIELD_CHARS.model)||typeof value.pid!="number"||typeof value.startedAt!="number"||typeof value.lastActivity!="number"||!isOptionalBoundedString(value.name,MAX_SESSION_FIELD_CHARS.name)||value.runtimeFallbackAlias!==void 0&&typeof value.runtimeFallbackAlias!="b\
|
|
18
|
+
oolean"||value.extensions!==void 0&&!Array.isArray(value.extensions)||!isOptionalBoundedString(value.worktreeRoot,MAX_SESSION_FIELD_CHARS.worktreeRoot)||!isOptionalBoundedString(value.branch,MAX_SESSION_FIELD_CHARS.branch)||value.ownership!==void 0&&!isOwnershipMode(value.ownership)||value.acknowledgesReceipts!==void 0&&typeof value.acknowledgesReceipts!="boolean"||value.livenessIntervalMs!==void 0&&(typeof value.livenessIntervalMs!="number"||!Number.isSafeInteger(value.livenessIntervalMs)||value.
|
|
19
|
+
livenessIntervalMs<=0)?!1:isDiscoveryPresence(value)&&isOptionalBoundedString(value.status,MAX_SESSION_FIELD_CHARS.status)}var MAX_RECORD_VALUE_BYTES=65536,MAX_RECORD_VALUE_DEPTH=16,MAX_RECORD_ARTIFACT_REFS=64,MAX_RECORDS=1024,RECORD_KEY_PATTERN=/^[a-z0-9][a-z0-9._-]{0,127}$/,RESERVED_RECORD_KEYS=["presence","policy","integration"],RESERVED_NAMESPACE_PREFIX="humain.coord.",RECORD_NAMESPACE_PREFIX="humain.coord.record:",POLICY_NAMESPACE="humain.coord.policy",ARTIFACT_NAMESPACE_PREFIX="humain.coor\
|
|
20
|
+
d.artifact:",MAX_ARTIFACT_BYTES=16*1024*1024,ARTIFACT_QUOTA_BYTES=256*1024*1024,MAX_ARTIFACTS=1024,MAX_ARTIFACT_NAME_CHARS=256,MAX_ARTIFACT_NAME_SEGMENTS=8,ARTIFACT_SEGMENT_PATTERN=/^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/,STAGED_FILE_PATTERN=/^[a-f0-9]{32}\.part$/,ARTIFACT_RETENTION_MS=10080*60*1e3,RECORD_TOMBSTONE_RETENTION_MS=ARTIFACT_RETENTION_MS,STALE_STAGED_FILE_MS=3600*1e3,FORBIDDEN_JSON_KEYS=new Set(["__proto__","constructor","prototype"]);function findJsonUnsafe(value,depth,maxDepth,ancestors,budget){
|
|
21
|
+
let overBudget=`value is larger than the limit of ${budget.limit} bytes`;if(value===null)return budget.remaining-=4,budget.remaining<0?overBudget:void 0;switch(typeof value){case"boolean":return budget.remaining-=4,budget.remaining<0?overBudget:void 0;case"string":return budget.remaining-=2,budget.remaining<0?overBudget:void 0;case"number":return Number.isFinite(value)?(budget.remaining-=1,budget.remaining<0?overBudget:void 0):"numbers must be finite";case"object":break;default:return`${typeof value}\
|
|
22
|
+
values are not JSON`}if(ancestors.has(value))return"value contains a cycle";if(depth>maxDepth)return`value is nested deeper than ${maxDepth} levels`;ancestors.add(value);try{if(Array.isArray(value)){if(Object.getPrototypeOf(value)!==Array.prototype)return"only plain arrays are allowed";if(budget.remaining-=2+Math.max(0,value.length-1),budget.remaining<0)return overBudget;for(let key of Reflect.ownKeys(value)){if(typeof key=="symbol")return"symbol keys are not JSON";if(key==="length")continue;let index=Number(
|
|
23
|
+
key);if(!Number.isInteger(index)||index<0||index>=value.length||String(index)!==key)return`arrays must not have non-index key "${key}"`;if(!Object.getOwnPropertyDescriptor(value,key)?.enumerable)return`non-enumerable key "${key}" is not JSON`}for(let index=0;index<value.length;index+=1){if(!Object.hasOwn(value,index))return"arrays must not have holes";let reason=findJsonUnsafe(value[index],depth+1,maxDepth,ancestors,budget);if(reason)return reason}return}let prototype=Object.getPrototypeOf(value);
|
|
24
|
+
if(prototype!==Object.prototype&&prototype!==null)return"only plain objects are allowed";if(budget.remaining-=2,budget.remaining<0)return overBudget;let first=!0;for(let key of Reflect.ownKeys(value)){if(typeof key=="symbol")return"symbol keys are not JSON";if(!Object.getOwnPropertyDescriptor(value,key)?.enumerable)return`non-enumerable key "${key}" is not JSON`;if(budget.remaining-=first?3:4,budget.remaining<0)return overBudget;if(first=!1,FORBIDDEN_JSON_KEYS.has(key))return`key "${key}" is not\
|
|
25
|
+
allowed`;let reason=findJsonUnsafe(value[key],depth+1,maxDepth,ancestors,budget);if(reason)return reason}return}finally{ancestors.delete(value)}}function validateJsonSafe(value,limits){let reason=findJsonUnsafe(value,1,limits.maxDepth,new Set,{remaining:limits.maxBytes,limit:limits.maxBytes});if(reason)return{ok:!1,reason};let bytes=Buffer.byteLength(JSON.stringify(value),"utf8");return bytes>limits.maxBytes?{ok:!1,reason:`value is ${bytes} bytes; the limit is ${limits.maxBytes}`}:{ok:!0,bytes}}
|
|
26
|
+
function isRequestId(value){return isBoundedString(value,MAX_REQUEST_ID_CHARS)&&value.length>0}function isOwnershipMode(value){return value==="on"||value==="off"}function isRecordKey(value){return typeof value=="string"&&RECORD_KEY_PATTERN.test(value)}function isReservedRecordKey(key){return RESERVED_RECORD_KEYS.some(reserved=>key===reserved||key.startsWith(`${reserved}.`))}function isReservedNamespace(namespace){return namespace.startsWith(RESERVED_NAMESPACE_PREFIX)}function isSha256Hex(value){
|
|
27
|
+
return typeof value=="string"&&/^[a-f0-9]{64}$/.test(value)}function isArtifactName(value){if(typeof value!="string"||value.length===0||value.length>MAX_ARTIFACT_NAME_CHARS)return!1;let segments=value.split("/");return segments.length<=MAX_ARTIFACT_NAME_SEGMENTS&&segments.every(segment=>ARTIFACT_SEGMENT_PATTERN.test(segment))}function isRecordState(value){return value==="open"||value==="done"}var INTEGRATION_NAMESPACE="humain.coord.integration",HANDOFF_KEY_PREFIX="integration.handoff.",RESOLUTION_KEY_PREFIX="\
|
|
28
|
+
integration.resolution.",MAX_HANDOFFS=48,MAX_HANDOFF_COMMITS=32,MAX_HANDOFF_DEPENDENCIES=16,MAX_HANDOFF_VERIFICATIONS=16,MAX_HANDOFF_ARTIFACT_REFS=16,MAX_BRANCH_NAME_CHARS=200,MAX_VERIFICATION_COMMAND_CHARS=256,MAX_VERIFICATION_SUMMARY_CHARS=512,MAX_HANDOFF_NOTE_CHARS=1024,MAX_ATTEMPTS=6,MAX_WRITERS=6,MAX_CHECKOUT_ROOT_CHARS=512,MAX_CONFLICT_FILES=10,MAX_CONFLICT_FILE_CHARS=80,MAX_EVIDENCE_CHARS=256;function hasControlChars(value,allowNewline=!1){for(let index=0;index<value.length;index+=1){let code=value.charCodeAt(index);if(!(code===10&&allowNewline)&&(code<32||code===127))return!0}return!1}function isGitObjectId(value){return typeof value=="string"&&/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/.test(value)}function isHandoffId(value){return typeof value=="string"&&/^[a-f0-9]{16}$/.test(value)}function isValidBranchName(value){return typeof value!="string"||value.length===0||value.length>MAX_BRANCH_NAME_CHARS||
|
|
29
|
+
!/^[\x21-\x7e]+$/.test(value)||value==="@"||value==="HEAD"||value.startsWith("-")||value.startsWith("/")||value.endsWith("/")||value.endsWith(".")||value.includes("..")||value.includes("//")||value.includes("@{")||/[~^:?*[\\]/.test(value)?!1:value.split("/").every(part=>!part.startsWith(".")&&!part.endsWith(".lock"))}function uniqueStrings(values,isValid){for(let index=0;index<values.length;index+=1)if(!Object.hasOwn(values,index)||!isValid(values[index]))return!1;return new Set(values).size===values.
|
|
30
|
+
length}function parseVerification(value){if(!isRecord(value))return"each verification must be an object";let{command,result,summary}=value;return typeof command!="string"||command.length===0||command.length>MAX_VERIFICATION_COMMAND_CHARS||hasControlChars(command)?`verification command must be 1-${MAX_VERIFICATION_COMMAND_CHARS} characters without control characters`:result!=="passed"&&result!=="failed"&&result!=="not_run"?'verification result must be "passed", "failed" or "not_run"':summary!==void 0&&
|
|
31
|
+
(typeof summary!="string"||summary.length>MAX_VERIFICATION_SUMMARY_CHARS||hasControlChars(summary))?`verification summary must be at most ${MAX_VERIFICATION_SUMMARY_CHARS} characters without control characters`:{command,result,...summary!==void 0?{summary}:{}}}function validateHandoffInput(value){if(!isRecord(value))return{ok:!1,reason:"handoff must be an object"};let{branch,commits,base,target,dependencies=[],verification=[],artifactRefs=[],note}=value;if(!isValidBranchName(branch))return{ok:!1,
|
|
32
|
+
reason:"branch is not a valid branch name"};if(!isValidBranchName(target))return{ok:!1,reason:"target is not a valid branch name"};if(!isGitObjectId(base))return{ok:!1,reason:"base must be a full commit id"};if(!Array.isArray(commits)||commits.length===0||commits.length>MAX_HANDOFF_COMMITS||!uniqueStrings(commits,isGitObjectId))return{ok:!1,reason:`commits must be 1-${MAX_HANDOFF_COMMITS} unique full commit ids`};if(commits.includes(base)||commits.some(commit=>commit.length!==base.length))return{
|
|
33
|
+
ok:!1,reason:"commits must not contain the base and must use the same id length as it"};if(!Array.isArray(dependencies)||dependencies.length>MAX_HANDOFF_DEPENDENCIES||!uniqueStrings(dependencies,isHandoffId))return{ok:!1,reason:`dependencies must be at most ${MAX_HANDOFF_DEPENDENCIES} unique handoff ids`};if(!Array.isArray(verification)||verification.length>MAX_HANDOFF_VERIFICATIONS)return{ok:!1,reason:`verification must be an array of at most ${MAX_HANDOFF_VERIFICATIONS} entries`};let checks=[];
|
|
34
|
+
for(let entry of verification){let parsed=parseVerification(entry);if(typeof parsed=="string")return{ok:!1,reason:parsed};checks.push(parsed)}return!Array.isArray(artifactRefs)||artifactRefs.length>MAX_HANDOFF_ARTIFACT_REFS||!uniqueStrings(artifactRefs,isSha256Hex)?{ok:!1,reason:`artifactRefs must be at most ${MAX_HANDOFF_ARTIFACT_REFS} unique SHA-256 hex strings`}:note!==void 0&&(typeof note!="string"||note.length>MAX_HANDOFF_NOTE_CHARS||hasControlChars(note,!0))?{ok:!1,reason:`note must be at \
|
|
35
|
+
most ${MAX_HANDOFF_NOTE_CHARS} characters without control characters`}:{ok:!0,value:{branch,commits:[...commits],base,target,dependencies:[...dependencies],verification:checks,artifactRefs:[...artifactRefs],...note!==void 0?{note}:{}}}}var EXTENSION_BUS_FEATURE="extension-bus-v1",EXACT_SEND_FEATURE="exact-send-v1",SESSION_HELD_ERROR_CODE="E_SESSION_HELD",COORD_RECORDS_FEATURE="coord-records-v1",COORD_INTEGRATION_FEATURE="coord-integration-v1";export{peerHandle,resolveHandleTargets,resolveExactTargets,resolvePrefixTargets,matchesPeer,MAX_MESSAGE_ID_CHARS,ID_IN_USE_DETAIL,isValidMessageId,MAX_SESSION_FIELD_CHARS,isBoundedString,MAX_REQUEST_ID_CHARS,WORST_CASE_REQUEST_ID,truncateChars,canonicalMessageReceipt,isMessageReceipt,isMessageControl,isMessage,messageDeliveryFingerprint,isTouchedPaths,isSessionInfo,isSessionId,isSessionRegistration,MAX_RECORD_VALUE_BYTES,MAX_RECORD_VALUE_DEPTH,MAX_RECORD_ARTIFACT_REFS,MAX_RECORDS,RECORD_NAMESPACE_PREFIX,
|
|
36
|
+
POLICY_NAMESPACE,ARTIFACT_NAMESPACE_PREFIX,MAX_ARTIFACT_BYTES,ARTIFACT_QUOTA_BYTES,MAX_ARTIFACTS,STAGED_FILE_PATTERN,ARTIFACT_RETENTION_MS,RECORD_TOMBSTONE_RETENTION_MS,STALE_STAGED_FILE_MS,validateJsonSafe,isRequestId,isOwnershipMode,isRecordKey,isReservedRecordKey,isReservedNamespace,isSha256Hex,isArtifactName,isRecordState,INTEGRATION_NAMESPACE,HANDOFF_KEY_PREFIX,RESOLUTION_KEY_PREFIX,MAX_HANDOFFS,MAX_HANDOFF_COMMITS,MAX_BRANCH_NAME_CHARS,MAX_ATTEMPTS,MAX_WRITERS,MAX_CHECKOUT_ROOT_CHARS,MAX_CONFLICT_FILES,
|
|
37
|
+
MAX_CONFLICT_FILE_CHARS,MAX_EVIDENCE_CHARS,isGitObjectId,isHandoffId,isValidBranchName,validateHandoffInput,EXTENSION_BUS_FEATURE,EXACT_SEND_FEATURE,SESSION_HELD_ERROR_CODE,COORD_RECORDS_FEATURE,COORD_INTEGRATION_FEATURE};
|