@zaly/agent 0.1.0 → 0.1.1
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/dist/{agent-D5NrjvG5.mjs → agent-BRENvuvx.mjs} +8 -11
- package/dist/{agent-D5NrjvG5.mjs.map → agent-BRENvuvx.mjs.map} +1 -1
- package/dist/{agent-B7cQOuMZ.mjs → agent-sHtwQDAk.mjs} +2 -3
- package/dist/{agent-B7cQOuMZ.mjs.map → agent-sHtwQDAk.mjs.map} +1 -1
- package/dist/{bash-9x8PPg0A.mjs → bash-DSy03sAj.mjs} +3 -4
- package/dist/{bash-9x8PPg0A.mjs.map → bash-DSy03sAj.mjs.map} +1 -1
- package/dist/compactions-HFjEgrv3.mjs +150 -0
- package/dist/compactions-HFjEgrv3.mjs.map +1 -0
- package/dist/{edit-D4yaBK1K.mjs → edit-DT672zIy.mjs} +2 -3
- package/dist/edit-DT672zIy.mjs.map +1 -0
- package/dist/{env-UUFv5Mye.mjs → env-C8p8i1E0.mjs} +2 -3
- package/dist/{env-UUFv5Mye.mjs.map → env-C8p8i1E0.mjs.map} +1 -1
- package/dist/{fetch-D0IeDN6H.mjs → fetch-BrtIqrid.mjs} +5 -6
- package/dist/{fetch-D0IeDN6H.mjs.map → fetch-BrtIqrid.mjs.map} +1 -1
- package/dist/{find-D1Z2ac_b.mjs → find-B-vvdlHu.mjs} +3 -4
- package/dist/{find-D1Z2ac_b.mjs.map → find-B-vvdlHu.mjs.map} +1 -1
- package/dist/{grep-By4wLRDk.mjs → grep-rvZ5S319.mjs} +3 -4
- package/dist/{grep-By4wLRDk.mjs.map → grep-rvZ5S319.mjs.map} +1 -1
- package/dist/{html-J629LNIm.mjs → html-VrAsoGBK.mjs} +277 -552
- package/dist/{html-J629LNIm.mjs.map → html-VrAsoGBK.mjs.map} +1 -1
- package/dist/{index-node-esm-CJsN8G51.mjs → index-node-esm-BwaOzhXB.mjs} +2 -3
- package/dist/{index-node-esm-CJsN8G51.mjs.map → index-node-esm-BwaOzhXB.mjs.map} +1 -1
- package/dist/index.d.mts +33 -101
- package/dist/index.d.mts.map +1 -1
- package/dist/index.mjs +3 -3
- package/dist/{jsonl-CvgEOakL.mjs → jsonl-BGt7eqPK.mjs} +2 -3
- package/dist/{jsonl-CvgEOakL.mjs.map → jsonl-BGt7eqPK.mjs.map} +1 -1
- package/dist/{manager-BJLjayBz.mjs → manager-1zEE5WiA.mjs} +4 -6
- package/dist/{manager-BJLjayBz.mjs.map → manager-1zEE5WiA.mjs.map} +1 -1
- package/dist/{markdown-Bv4J8cg3.mjs → markdown-8ICz5aFw.mjs} +2 -3
- package/dist/{markdown-Bv4J8cg3.mjs.map → markdown-8ICz5aFw.mjs.map} +1 -1
- package/dist/{masker-jgSUXzjY.mjs → masker-DEgR_ntk.mjs} +4 -6
- package/dist/{masker-jgSUXzjY.mjs.map → masker-DEgR_ntk.mjs.map} +1 -1
- package/dist/{model-_3ZA2xqm.mjs → model-DqGqxfAc.mjs} +2 -3
- package/dist/{model-_3ZA2xqm.mjs.map → model-DqGqxfAc.mjs.map} +1 -1
- package/dist/{notify-DpG_m9iP.mjs → notify-Ds0-4BeI.mjs} +2 -3
- package/dist/{notify-DpG_m9iP.mjs.map → notify-Ds0-4BeI.mjs.map} +1 -1
- package/dist/{read-B-hwcc2Q.mjs → read-C5keKntU.mjs} +4 -44
- package/dist/read-C5keKntU.mjs.map +1 -0
- package/dist/{registry-Zo0QmKdR.mjs → registry-CntkeXlo.mjs} +34 -32
- package/dist/registry-CntkeXlo.mjs.map +1 -0
- package/dist/{rolldown-runtime-DktXgydw.mjs → rolldown-runtime-DYf_mQCB.mjs} +1 -2
- package/dist/{search-CH0D5CkV.mjs → search-B-89W3SM.mjs} +2 -3
- package/dist/{search-CH0D5CkV.mjs.map → search-B-89W3SM.mjs.map} +1 -1
- package/dist/session/claude.d.mts +0 -2
- package/dist/session/claude.d.mts.map +1 -1
- package/dist/session/claude.mjs +4 -6
- package/dist/session/claude.mjs.map +1 -1
- package/dist/{session-CACkHyDR.mjs → session-C8zqqbPE.mjs} +6 -8
- package/dist/{session-CACkHyDR.mjs.map → session-C8zqqbPE.mjs.map} +1 -1
- package/dist/{session-Ds5nJz5A.d.mts → session-Cq52cam5.d.mts} +1 -11
- package/dist/session-Cq52cam5.d.mts.map +1 -0
- package/dist/session.d.mts +1 -3
- package/dist/session.d.mts.map +1 -1
- package/dist/session.mjs +4 -5
- package/dist/{src-DoXC_gDY.mjs → src-C04Qk9KE.mjs} +35 -40
- package/dist/{src-DoXC_gDY.mjs.map → src-C04Qk9KE.mjs.map} +1 -1
- package/dist/{subagent-BMQMbANL.mjs → subagent-BbcxLzgC.mjs} +4 -5
- package/dist/{subagent-BMQMbANL.mjs.map → subagent-BbcxLzgC.mjs.map} +1 -1
- package/dist/{swarm-BJ3gQA1Z.mjs → swarm-B_s9Qpbt.mjs} +2 -3
- package/dist/{swarm-BJ3gQA1Z.mjs.map → swarm-B_s9Qpbt.mjs.map} +1 -1
- package/dist/{swarm-BuFx_xeY.mjs → swarm-D823Yumk.mjs} +2 -3
- package/dist/{swarm-BuFx_xeY.mjs.map → swarm-D823Yumk.mjs.map} +1 -1
- package/dist/{tasks-WdRAHsOL.mjs → tasks-D76WXWr2.mjs} +3 -4
- package/dist/{tasks-WdRAHsOL.mjs.map → tasks-D76WXWr2.mjs.map} +1 -1
- package/dist/{tasks-BA-PCeGa.mjs → tasks-Dgsiuh0Q.mjs} +3 -4
- package/dist/{tasks-BA-PCeGa.mjs.map → tasks-Dgsiuh0Q.mjs.map} +1 -1
- package/dist/{tools-CJ2x45EZ.mjs → tools-DmoUYORG.mjs} +6 -10
- package/dist/{tools-CJ2x45EZ.mjs.map → tools-DmoUYORG.mjs.map} +1 -1
- package/dist/{truncate-BSMXgiXj.mjs → truncate-CChlZ113.mjs} +2 -3
- package/dist/{truncate-BSMXgiXj.mjs.map → truncate-CChlZ113.mjs.map} +1 -1
- package/dist/{uuid-CAdJg4l8.mjs → uuid-rfbQ9ad2.mjs} +2 -3
- package/dist/{uuid-CAdJg4l8.mjs.map → uuid-rfbQ9ad2.mjs.map} +1 -1
- package/dist/{wakeup-BYqTnfSp.mjs → wakeup-CFr1nu_L.mjs} +2 -3
- package/dist/{wakeup-BYqTnfSp.mjs.map → wakeup-CFr1nu_L.mjs.map} +1 -1
- package/dist/{write-DwGiDNeG.mjs → write-BRQFfWAn.mjs} +2 -3
- package/dist/write-BRQFfWAn.mjs.map +1 -0
- package/package.json +6 -6
- package/dist/compactions-D9XlwQGO.mjs +0 -191
- package/dist/compactions-D9XlwQGO.mjs.map +0 -1
- package/dist/edit-D4yaBK1K.mjs.map +0 -1
- package/dist/read-B-hwcc2Q.mjs.map +0 -1
- package/dist/registry-Zo0QmKdR.mjs.map +0 -1
- package/dist/session-Ds5nJz5A.d.mts.map +0 -1
- package/dist/write-DwGiDNeG.mjs.map +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"registry-CntkeXlo.mjs","names":["resolveRule","ignore","ignore"],"sources":["../src/permissions/handlers/bash.ts","../../../node_modules/.bun/ignore@7.0.14/node_modules/ignore/index.js","../src/permissions/handlers/files.ts","../src/permissions/handlers/tool.ts","../src/permissions/handlers/registry.ts"],"sourcesContent":["import type { Segment } from \"../../utils/bash/parser.ts\"\nimport type { CheckResult, PermissionHandler, Rule, Suggestion, Verdict } from \"../types.ts\"\n\nimport { parseBash } from \"../../utils/bash/parser.ts\"\nimport { TOOLS } from \"../../utils/bash/tools.ts\"\n\n/**\n * Handler for `Rule<\"bash\">` — evaluates a bash command line against\n * pattern rules, then delegates each segment's inferred and explicit\n * file paths to the file handler via `ctx.validate(\"read\"|\"write\", …)`.\n *\n * Composition keeps file-rule logic in one place: the bash handler\n * doesn't know about workspaces, sensitive files, or path-pattern\n * matching — it just asks the registered handler for those scopes.\n *\n * Sources of file paths per segment:\n * - `seg.reads` / `seg.writes` — explicit `<` / `>` / `>>` redirects\n * extracted by the parser.\n * - `TOOLS[cmd].reads/writes(args)` — inferred from built-in tool\n * specs (e.g. `cat foo.txt` reads `foo.txt`, `tee out` writes `out`).\n *\n * Suggestions and reasons from inner `validate` calls bubble up so the\n * prompt UI can offer \"allow `Bash(cat:*)`\" alongside \"add ~/Documents\n * as workspace\" in a single ask.\n */\nexport const bashHandler: PermissionHandler<\"bash\"> = {\n validate(input, ctx): CheckResult {\n const parsed = parseBash(input)\n if (!parsed.ok) {\n if ([\"bash\", \"read\", \"write\"].every((scope) => ctx.allowsAll?.(scope))) {\n return { verdict: \"allow\" }\n }\n return {\n ask: `Allow this bash command? (${parsed.reason})`,\n reason: parsed.reason,\n verdict: \"ask\",\n }\n }\n\n let verdict: Verdict = \"allow\"\n let reason: string | undefined\n const suggestions: Suggestion[] = []\n\n for (const seg of parsed.segments) {\n // Bash rule match for the command itself. Resolve this before the\n // conservative safety checks so explicit allow-all presets like yolo can\n // mean exactly that instead of degrading to an unimplemented ask prompt.\n const cmdVerdict = resolveRules(ctx.rules, seg) ?? \"ask\"\n if (seg.hasCommandSubst && cmdVerdict !== \"allow\") {\n return {\n ask: `Allow command substitution in \\`${seg.cmd}\\`?`,\n reason: \"command substitution not allowed\",\n verdict: \"ask\",\n }\n }\n const spec = TOOLS[seg.cmd]\n if (spec?.unsafe?.(seg.args) && cmdVerdict !== \"allow\") {\n return {\n ask: `Allow invocation of \\`${seg.cmd}\\`? (unsafe)`,\n reason: `${seg.cmd}: invocation mode not safely modelled`,\n verdict: \"ask\",\n }\n }\n\n let segVerdict: Verdict = cmdVerdict\n let segReason: string | undefined =\n cmdVerdict === \"allow\" ? undefined : `segment \"${seg.cmd}\" → ${cmdVerdict}`\n if (cmdVerdict === \"ask\") {\n suggestions.push({\n kind: \"rule\",\n pattern: seg.args.length > 0 ? `${seg.cmd}:*` : seg.cmd,\n scope: \"bash\",\n })\n }\n\n // Delegate file paths to the file handler. Reads first, then\n // writes; both contribute to this segment's verdict via combine.\n const reads = [...(spec?.reads?.(seg.args) ?? []), ...seg.reads]\n const writes = [...(spec?.writes?.(seg.args) ?? []), ...seg.writes.map((w) => w.path)]\n\n for (const path of reads) {\n if (seg.dyn?.has(path) && !ctx.allowsAll?.(\"read\")) {\n segVerdict = combine(segVerdict, \"ask\")\n segReason ??= `${seg.cmd}: read ${path}: dynamic path`\n suggestions.push({\n kind: \"rule\",\n pattern: `${seg.cmd}:*`,\n scope: \"bash\",\n })\n continue\n }\n const r = ctx.validate(\"read\", path)\n segVerdict = combine(segVerdict, r.verdict)\n if (r.verdict !== \"allow\") {\n segReason ??= `${seg.cmd}: read ${path}: ${r.reason}`\n if (r.suggestions) suggestions.push(...r.suggestions)\n }\n if (segVerdict === \"deny\") break\n }\n if (segVerdict !== \"deny\") {\n for (const path of writes) {\n if (seg.dyn?.has(path) && !ctx.allowsAll?.(\"write\")) {\n segVerdict = combine(segVerdict, \"ask\")\n segReason ??= `${seg.cmd}: write ${path}: dynamic path`\n suggestions.push({\n kind: \"rule\",\n pattern: `${seg.cmd}:*`,\n scope: \"bash\",\n })\n continue\n }\n const w = ctx.validate(\"write\", path)\n segVerdict = combine(segVerdict, w.verdict)\n if (w.verdict !== \"allow\") {\n segReason ??= `${seg.cmd}: write ${path}: ${w.reason}`\n if (w.suggestions) suggestions.push(...w.suggestions)\n }\n if (segVerdict === \"deny\") break\n }\n }\n\n verdict = combine(verdict, segVerdict)\n if (verdict !== \"allow\" && reason === undefined) reason = segReason\n if (verdict === \"deny\") break\n }\n\n return verdict === \"allow\"\n ? { verdict: \"allow\" }\n : {\n ask: `Allow this bash command?`,\n reason: reason ?? \"no rule matched\",\n suggestions: suggestions.length > 0 ? suggestions : undefined,\n verdict,\n }\n },\n}\n\n// ── Pattern matching ─────────────────────────────────────────────────────\n\n/** A command-pattern rule.\n *\n * Pattern syntax:\n * \"cmd\" → cmd alone, no args\n * \"cmd:*\" → cmd with any args (trailing wildcard)\n * \"cmd a\" → cmd with arg \"a\", no other args\n * \"cmd a:*\" → cmd with arg \"a\" plus any others\n * \"cmd a b\" → cmd with exact args [a, b]\n * \"cmd --flag*\" → cmd with arg starting with \"--flag\" (per-arg prefix)\n * \"bun test:node:*\" → cmd \"bun\", arg \"test:node\", any others\n *\n * Whitespace separates the cmd from its args, and args from each\n * other. The `:` character is only meaningful as the trailing `:*`\n * wildcard suffix — anywhere else (including inside an arg like\n * `test:node`) it's a literal character. */\n\ninterface ParsedPattern {\n cmd: string\n /** Arg-position match tokens. Each may end with `*` for prefix match. */\n parts: string[]\n /** Set when the pattern ends with `:*`, allowing arbitrary further args. */\n trailingWildcard: boolean\n}\n\n/** Combine two verdicts: deny dominates, ask beats allow. */\nfunction combine(a: Verdict, b: Verdict): Verdict {\n if (a === \"deny\" || b === \"deny\") return \"deny\"\n if (a === \"ask\" || b === \"ask\") return \"ask\"\n return \"allow\"\n}\n\nconst patternCache = new Map<string, ParsedPattern>()\n\nfunction parsePattern(pattern: string): ParsedPattern {\n const cached = patternCache.get(pattern)\n if (cached) return cached\n\n let body = pattern.trim()\n let trailingWildcard = false\n if (body.endsWith(\":*\")) {\n trailingWildcard = true\n body = body.slice(0, -2)\n }\n\n const tokens = body.split(/\\s+/).filter((s) => s.length > 0)\n const cmd = tokens[0] ?? \"\"\n const result: ParsedPattern = {\n cmd,\n parts: tokens.slice(1),\n trailingWildcard,\n }\n patternCache.set(pattern, result)\n return result\n}\n\nfunction matchPart(part: string, value: string): boolean {\n if (part.endsWith(\"*\")) {\n return value.startsWith(part.slice(0, -1))\n }\n return part === value\n}\n\n/** Test whether a parsed segment matches a rule pattern. */\nexport function matchRule(rule: Rule, seg: Segment): boolean {\n const p = parsePattern(rule.pattern)\n // Bare `*` (e.g. from a `Bash` rule with no parens) matches any command.\n if (p.cmd === \"*\" && p.parts.length === 0) return true\n if (p.cmd !== seg.cmd) return false\n if (seg.args.length < p.parts.length) return false\n for (let i = 0; i < p.parts.length; i++) {\n if (!matchPart(p.parts[i], seg.args[i])) return false\n }\n if (p.trailingWildcard) return true\n return seg.args.length === p.parts.length\n}\n\n/** First-match-wins resolution. Returns `undefined` if no rule matches. */\nfunction resolveRules(rules: readonly Rule[], seg: Segment): Verdict | undefined {\n for (const r of rules) {\n if (matchRule(r, seg)) return r.policy\n }\n return undefined\n}\n","// A simple implementation of make-array\nfunction makeArray (subject) {\n return Array.isArray(subject)\n ? subject\n : [subject]\n}\n\nconst UNDEFINED = undefined\nconst EMPTY = ''\nconst SPACE = ' '\nconst ESCAPE = '\\\\'\n\n// The characters that carry a meaning of their own inside a regular\n// expression, so a literal one has to be escaped before it is emitted.\nconst REGEX_LITERAL_SPECIAL = /[.*+?()[\\]{}^$|\\\\/]/\nconst BOM = '\\uFEFF'\nconst REGEX_INVALID_TRAILING_BACKSLASH = /(?:[^\\\\]|^)\\\\$/\n// A run of two or more asterisks is a globstar (#175)\nconst REGEX_ANCHORED_GLOBSTAR = /^\\/\\*{2,}$/\nconst REGEX_REPLACE_LEADING_EXCAPED_EXCLAMATION = /^\\\\!/\nconst REGEX_REPLACE_LEADING_EXCAPED_HASH = /^\\\\#/\nconst REGEX_SPLITALL_CRLF = /\\r?\\n/g\n\n// Invalid:\n// - /foo,\n// - ./foo,\n// - ../foo,\n// - .\n// - ..\n// Valid:\n// - .foo\nconst DOUBLE_SLASH = '//'\nconst SLASH_CODE = 47\nconst DOT_CODE = 46\n\n\nconst SLASH = '/'\n\n// Do not use ternary expression here, since \"istanbul ignore next\" is buggy\nlet TMP_KEY_IGNORE = 'node-ignore'\n/* istanbul ignore else */\nif (typeof Symbol !== 'undefined') {\n TMP_KEY_IGNORE = Symbol.for('node-ignore')\n}\nconst KEY_IGNORE = TMP_KEY_IGNORE\n\nconst define = (object, key, value) => {\n Object.defineProperty(object, key, {value})\n return value\n}\n\nconst RETURN_FALSE = () => false\n\n// > The range notation, e.g. [a-zA-Z],\n// > can be used to match one of the characters in a range.\n//\n// gitignore(5) defers to fnmatch(3) for this, and git implements it in\n// `wildmatch.c`. A bracket expression has a sub-grammar of its own, which\n// is neither the surrounding pattern grammar nor the JavaScript one:\n//\n// - a `]` right after `[` or `[!` is a literal member, not the terminator\n// - `[:alpha:]` names one of twelve POSIX classes\n// - `\\` escapes the next member, `]` included\n// - `*`, `?` and `.` are plain literal members\n// - an unterminated expression makes the whole pattern match nothing\n//\n// which means the expression can not be located -- let alone translated -- by\n// a regular expression. It is scanned out of the pattern before the\n// replacers below run, and put back once they are done, so that neither the\n// metacharacter escaper nor the `?` / `*` replacers ever see its body.\n\n// git classifies with its own ASCII-only ctype macros (`wildmatch.c`), never\n// with the C library ones, so these must not be mapped onto `\\d` / `\\w` /\n// `\\s`, which are wider. `/` is left out of every expansion, because a\n// bracket expression never matches a path separator.\nconst POSIX_CLASSES = {\n alnum: '0-9A-Za-z',\n alpha: 'A-Za-z',\n blank: ' \\\\t',\n cntrl: '\\\\x00-\\\\x1f\\\\x7f',\n digit: '0-9',\n graph: '!-.0-~',\n lower: 'a-z',\n print: ' -.0-~',\n punct: '!-.:-@\\\\[-`{-~',\n // git's `sane-ctype.h` classifies \\v and \\f as control, not space,\n // unlike C's `isspace`\n space: ' \\\\t\\\\n\\\\r',\n upper: 'A-Z',\n xdigit: '0-9A-Fa-f'\n}\n\nconst CLASS_MEMBERS_TO_ESCAPE = '\\\\]^-['\n\nconst escapeMember = char => CLASS_MEMBERS_TO_ESCAPE.indexOf(char) < 0\n ? char\n : ESCAPE + char\n\n// > if (matched == negated || ((flags & WM_PATHNAME) && text_ch == '/'))\n// > return WM_ABORT_TO_STARSTAR; (git, `wildmatch.c`)\n// A bracket expression never matches a path separator, whatever its members\n// say, so a negated class gets `/` as one more excluded character, while a\n// plain one -- where a literal member or a range could still let `/` in --\n// is guarded with a lookahead, `/` being impossible to subtract from a\n// JavaScript character class.\nconst NON_SLASH = '(?!\\\\/)'\n\nconst classSource = (negated, body) => {\n if (negated) {\n return `[^\\\\/${body}]`\n }\n\n const source = `[${body}]`\n\n return new RegExp(source).test('/')\n ? NON_SLASH + source\n : source\n}\n\n// Scan the bracket expression that starts at `pattern[start] === '['`,\n// mirroring the member loop of git's `wildmatch.c`.\n// @returns {{end: number, source: string} | null} `null` if the expression is\n// never terminated, which makes the whole pattern match nothing.\nconst scanBracket = (pattern, start) => {\n const {length} = pattern\n let index = start + 1\n let negated = EMPTY\n\n const lead = pattern[index]\n if (lead === '!' || lead === '^') {\n negated = '^'\n index ++\n }\n\n let body = EMPTY\n\n // The member a `-` could start a range from, or EMPTY when the previous\n // member can not open one (start of the body, or a range / POSIX class\n // that has just closed)\n let prev = EMPTY\n\n // git scans the members with a do-while, so the first one is consumed\n // unconditionally. That is the whole reason a leading `]` is a member\n // and not the terminator.\n for (;;) {\n const char = pattern[index]\n\n if (char === UNDEFINED) {\n return null\n }\n\n if (char === ESCAPE) {\n const escaped = pattern[index + 1]\n if (escaped === UNDEFINED) {\n return null\n }\n body += escapeMember(escaped)\n prev = escaped\n index ++\n } else if (\n char === '-'\n && prev\n && index + 1 < length\n && pattern[index + 1] !== ']'\n ) {\n index ++\n let to = pattern[index]\n if (to === ESCAPE) {\n // A pattern can not end on a lone backslash -- `checkPattern` has\n // already thrown it away -- so there is an upper bound to read.\n to = pattern[index += 1]\n }\n // An out-of-order range matches nothing in git but is a syntax error in\n // JavaScript, so it is dropped. Its lower bound stays: git tests it\n // as a plain member before it ever looks at the `-`, so `[c-a]` does\n // match `c`.\n if (prev <= to) {\n body += `-${escapeMember(to)}`\n }\n prev = EMPTY\n } else if (char === '[' && pattern[index + 1] === ':') {\n const nameStart = index + 2\n let end = nameStart\n while (end < length && pattern[end] !== ']') {\n end ++\n }\n\n if (end === length) {\n return null\n }\n\n if (end > nameStart && pattern[end - 1] === ':') {\n const name = pattern.slice(nameStart, end - 1)\n\n // An unknown class name makes the whole pattern match nothing\n if (!Object.prototype.hasOwnProperty.call(POSIX_CLASSES, name)) {\n return null\n }\n\n body += POSIX_CLASSES[name]\n prev = EMPTY\n index = end\n } else {\n // No `:]` to close it, so the `[` is a plain member and scanning\n // resumes right after it.\n body += escapeMember('[')\n prev = '['\n index = nameStart - 2\n }\n } else {\n body += escapeMember(char)\n prev = char\n }\n\n index ++\n\n if (pattern[index] === ']') {\n return {\n end: index,\n source: classSource(negated, body)\n }\n }\n }\n}\n\n// An empty JavaScript class can never match, which is how a pattern that git\n// gives up on (`WM_ABORT_ALL`) is expressed here.\nconst NEVER_MATCH = '[]'\n\n// A NUL can appear in neither a `.gitignore` line nor a path, which makes it\n// the one safe placeholder character. A literal one in the pattern is\n// held aside all the same, so a collision is impossible by construction.\nconst PLACEHOLDER = '\\u0000'\nconst REGEX_RESTORE_PLACEHOLDER = new RegExp(\n `${PLACEHOLDER}(\\\\d+)${PLACEHOLDER}`, 'g'\n)\n\n// The one wildcard the chain does not expand for itself is a trailing `*`. How\n// it expands depends on the mode (`regex` vs `checkRegex`), so `_make` is\n// left to do it, and until then the pending wildcard travels as this marker.\n// That is what keeps it apart from a user-escaped literal `\\*`: the unescape\n// steps collapse the escaped one to the exact `\\*` a wildcard would leave\n// behind, so by the time `_make` runs the two are otherwise the same string\n// and a literal star gets wrongly rewritten into a wildcard. The marker is a\n// private-use character, and `extractBrackets` keeps one that came out of the\n// pattern apart from it, so the only marker `_make` ever turns back into a\n// real wildcard is the one this chain put there itself.\nconst TRAILING_WILDCARD = '\\uE000'\n\n// A trailing \"/**\" is deferred the same way, because `checkRegex` has to tell\n// it apart from a trailing \"/*\" (see `checkSourceOf`). For `.ignores()` it\n// still never matches the folder itself (#21).\nconst TRAILING_DOUBLESTAR = '\\uE001'\n\n// The three characters above mean something to the chain that builds the\n// source rather than to the path, so one that came out of the pattern is\n// held aside like a bracket expression instead of going straight out. Being\n// held is what makes it safe: the restore runs after the step that anchors\n// the source, so the character comes back in the middle of the source and\n// not at its end, which is the one place `_make` and `checkSourceOf` look\n// for a marker. Without it a pattern's own character lands where a pending\n// marker sits, and `_make` turns it into a real trailing wildcard.\n//\n// It is held as a one-member class rather than bare, in both of the branches\n// a reserved character can reach, so that the property can be\n// read off this function alone -- a reserved character never goes out on\n// its own -- rather than depending on where in the chain the restore\n// happens to run. In the expression built here `[x]` matches exactly what\n// `x` matches, none of the three being special to a regular expression or\n// inside a class, so no test can tell the two apart: the class is insurance,\n// and the paragraph above is the reason it is not needed.\nconst isReserved = char =>\n char === PLACEHOLDER\n || char === TRAILING_WILDCARD\n || char === TRAILING_DOUBLESTAR\n\n// Replace every bracket expression with a placeholder the replacers below\n// leave alone, and translate it separately.\nconst extractBrackets = pattern => {\n const sources = []\n const hold = source =>\n `${PLACEHOLDER}${sources.push(source) - 1}${PLACEHOLDER}`\n\n const {length} = pattern\n let out = EMPTY\n let index = 0\n\n while (index < length) {\n const char = pattern[index]\n\n if (char === ESCAPE) {\n // > Put a backslash (\"\\\") in front of ... a character to make it literal.\n // (gitignore(5) -> fnmatch(3))\n // A backslash quotes the next character, whatever it is, so `\\d` is a\n // literal `d`, not the regex digit class, and `\\?` is a literal `?`,\n // not a wildcard. Held aside as its literal here, the escape never\n // reaches the replacers below, which would otherwise let `\\d`, `\\b`,\n // `\\1`, `\\/` keep their regular-expression meaning, and would turn a\n // `\\?` into `[^\\/]`.\n //\n // Three escapes are still left for the chain: `\\*` (a literal star,\n // told apart from a wildcard by `TRAILING_WILDCARD` and the wildcard\n // replacers), `\\[` (a literal bracket, the one `[` the bracket\n // replacer still expects), and `\\ ` (a quoted space, which one pass\n // below rewrites in bulk -- holding each one aside instead costs more\n // on a pattern built out of them). A lone trailing backslash can reach\n // here after line-ending cleanup.\n //\n // A quoted backslash is not among them. The chain doubles every\n // backslash, then takes the doubling back out again, and a quoted one\n // standing next to a character the chain also escapes left the two\n // counts sharing a run, so one of the escapes was lost. Held here as\n // the literal it means, it never joins that run.\n const escaped = pattern[index + 1]\n\n if (\n escaped === UNDEFINED\n || escaped === SLASH && index + 2 === length\n ) {\n // Git removes a final directory slash before matching. An escape\n // without a character after that removal makes the pattern invalid.\n out += hold(NEVER_MATCH)\n } else if (\n escaped === '*'\n || escaped === '['\n || escaped === SPACE\n ) {\n out += pattern.slice(index, index + 2)\n } else {\n out += hold(\n REGEX_LITERAL_SPECIAL.test(escaped)\n ? ESCAPE + escaped\n : isReserved(escaped)\n ? `[${escaped}]`\n : escaped\n )\n }\n\n index += 2\n } else if (isReserved(char)) {\n out += hold(`[${char}]`)\n index ++\n } else if (char === '[') {\n const scanned = scanBracket(pattern, index)\n\n if (scanned === null) {\n // git gives up on the whole pattern (`WM_ABORT_ALL`), so whatever\n // follows can not make it match either.\n out += hold(NEVER_MATCH)\n index = length\n } else {\n out += hold(scanned.source)\n index = scanned.end + 1\n }\n } else {\n out += char\n index ++\n }\n }\n\n return {\n source: out,\n sources\n }\n}\n\n// A step of the chain below is normally a `[matcher, replacer]` pair handed\n// to `String.replace`. `DIRECT` marks the ones that are plain string work\n// instead, and take `(source, pattern)`.\n//\n// Anchoring the two ends is exactly that -- a test of one character and a\n// concatenation -- and putting it through the regular expression engine\n// cost a third of this chain for nothing: 167ns where 10ns does the same\n// job. The two are still steps in the same list, in the same places,\n// because their position in the order is part of what they mean.\nconst DIRECT = null\n\n// A separator at the beginning or in the middle of a pattern, as opposed to\n// one at the very end.\nconst REGEX_INNER_SLASH = /\\/(?!$)/\n\n// > If the pattern ends with a slash,\n// > it is removed for the purpose of the following description,\n// > but it would only find a match with a directory.\n// > In other words, foo/ will match a directory foo and paths underneath it,\n// > but will not match a regular file or a symbolic link foo\n// > (this is consistent with the way how pathspec works in general in Git).\n// '`foo/`' will not match regular file '`foo`' or symbolic link '`foo`'\n// -> ignore-rules will not deal with it, because it costs extra `fs.stat` call\n// you could use option `mark: true` with `glob`\n\n// '`foo/`' should not continue with the '`..`'\n// The chain that turns one gitignore pattern into a regular expression\n// source, in order. A step is either\n//\n// [matcher, replacer] handed to `String.replace`\n// [matcher, replacer, required] the same, but skipped outright unless\n// `required` appears in the string, which\n// the matcher cannot match without\n// [DIRECT, transform] plain string work, taking (source, pattern)\n//\n// The `required` character is only ever a shortcut: finding it does not mean\n// the matcher will match, and not finding it means it cannot. It is there\n// because scanning for one character costs a fraction of running a matcher\n// that then finds nothing -- for the wildcard step, whose `[^\\\\]+`\n// backtracks its way through the whole string before giving up, 11ns\n// against 400ns.\nconst REPLACERS = [\n\n // Replace (\\ ) with ' '\n // Only a space: an escaped tab or other whitespace is already a literal by\n // the time it reaches here, and a bare tab must be left as one, not turned\n // into a space.\n // (\\ ) -> ' '\n // (\\\\ ) -> '\\\\ '\n // (\\\\\\ ) -> '\\\\ '\n [\n // A run of backslashes is taken whole, from its first one, so no match\n // ever starts again inside it -- `(\\\\+?) ` did, which made a long run\n // quadratic.\n /(\\\\+)( ?)/g,\n (_, run, space) => space\n ? run.slice(0, run.length - run.length % 2) + SPACE\n : run,\n ESCAPE + SPACE\n ],\n\n // git's wildmatch() reads a run of two or more asterisks as one globstar\n // whenever the run fills a path segment: it starts the pattern or follows\n // a `/`, and it ends the pattern or comes before a `/`. A run of two is\n // already `**`; a longer one is folded into `**` here, so the steps\n // below only ever have to know `**`.\n // `***/foo` -> `**/foo`, `a/***/b` -> `a/**/b`, `a/***` -> `a/**`\n // git also takes a run beside a literal prefix (`a***/b`) or beside an\n // escaped slash (`***\\/b`) as a globstar, and this does not; the README\n // lists both, under \"A run of asterisks\".\n [\n /(^|\\/)\\*{3,}(?=\\/|$)/g,\n (_, start) => `${start}**`,\n '*'\n ],\n\n // Escape metacharacters\n // which is written down by users but means special for regular expressions.\n\n // > There are 12 characters with special meanings:\n // > - the backslash \\,\n // > - the caret ^,\n // > - the dollar sign $,\n // > - the period or dot .,\n // > - the vertical bar or pipe symbol |,\n // > - the question mark ?,\n // > - the asterisk or star *,\n // > - the plus sign +,\n // > - the opening parenthesis (,\n // > - the closing parenthesis ),\n // > - and the opening square bracket [,\n // > - the opening curly brace {,\n // > These special characters are often called \"metacharacters\".\n [\n /[\\\\$.|*+(){^]/g,\n match => `\\\\${match}`\n ],\n\n [\n // > a question mark (?) matches a single character\n /(?!\\\\)\\?/g,\n () => '[^/]',\n '?'\n ],\n\n // leading slash\n [\n\n // > A leading slash matches the beginning of the pathname.\n // > For example, \"/*.c\" matches \"cat-file.c\" but not \"mozilla-sha1/sha1.c\".\n // A leading slash matches the beginning of the pathname\n /^\\//,\n () => '^',\n SLASH\n ],\n\n // replace special metacharacter slash after the leading slash\n [\n /\\//g,\n () => '\\\\/',\n SLASH\n ],\n\n [\n // > A leading \"**\" followed by a slash means match in all directories.\n // > For example, \"**/foo\" matches file or directory \"foo\" anywhere,\n // > the same as pattern \"foo\".\n // > \"**/foo/bar\" matches file or directory \"bar\" anywhere that is directly\n // > under directory \"foo\".\n // Notice that the '*'s have been replaced as '\\\\*'\n /^\\^*(?:\\\\\\*\\\\\\*\\\\\\/)+/,\n\n // '**/foo' <-> 'foo'\n () => '^(?:.*\\\\/)?',\n '*'\n ],\n\n // starting\n [\n // there will be no leading '/'\n // (which has been replaced by section \"leading slash\")\n // If starts with '**', adding a '^' to the regular expression also works\n DIRECT,\n (source, pattern) => {\n // Nothing to anchor to, or already anchored\n if (!source || source[0] === '^') {\n return source\n }\n\n // If has a slash `/` at the beginning or middle\n const anchor = !REGEX_INNER_SLASH.test(pattern)\n // > Prior to 2.22.1\n // > If the pattern does not contain a slash /,\n // > Git treats it as a shell glob pattern\n // Actually, if there is only a trailing slash,\n // git also treats it as a shell glob pattern\n\n // After 2.22.1 (compatible but clearer)\n // > If there is a separator at the beginning or middle (or both)\n // > of the pattern, then the pattern is relative to the directory\n // > level of the particular .gitignore file itself.\n // > Otherwise the pattern may also match at any level below\n // > the .gitignore level.\n ? '(?:^|\\\\/)'\n\n // > Otherwise, Git treats the pattern as a shell glob suitable for\n // > consumption by fnmatch(3)\n : '^'\n\n return anchor + source\n }\n ],\n\n // two globstars\n [\n // Use lookahead assertions so that we could match more than one `'/**'`\n /\\\\\\/\\\\\\*\\\\\\*(?=\\\\\\/|$)/g,\n\n // Zero, one or several directories\n // should not use '*', or it will be replaced by the next replacer\n\n // Check if it is not the last `'/**'`\n (_, index, str) => index + 6 < str.length\n\n // case: /**/ at the end of the pattern, i.e. a trailing `'/**/'`\n // > A trailing `\"/**/\"` (a trailing `\"/**\"` restricted to directories)\n // > matches everything inside, but it should not match the current\n // > folder itself, so it requires at least one directory segment.\n // 'a/**/' matches 'a/b/', 'a/x/y/' but not 'a/'\n ? str.slice(index + 6) === '\\\\/'\n ? '(?:\\\\/[^\\\\/]+)+'\n\n // case: /**/\n // > A slash followed by two consecutive asterisks then a slash matches\n // > zero or more directories.\n // > For example, \"a/**/b\" matches \"a/b\", \"a/x/b\", \"a/x/y/b\" and so on.\n // '/**/'\n : '(?:\\\\/[^\\\\/]+)*'\n\n // case: /**\n // > A trailing `\"/**\"` matches everything inside.\n\n // #21: everything inside but it should not include the current folder,\n // resolved by `_make`\n : `\\\\/${TRAILING_DOUBLESTAR}`,\n '*'\n ],\n\n // normal intermediate wildcards\n [\n // Never replace escaped '*'\n // ignore rule '\\*' will match the path '*'\n\n // 'abc.*/' -> go\n // 'abc.*' -> skip this rule,\n // coz trailing single wildcard will be handed by [trailing wildcard]\n /(^|[^\\\\]+)(\\\\\\*)+(?=.+)/g,\n\n // '*.js' matches '.js'\n // '*.js' doesn't match 'abc'\n (_, p1, p2) => {\n // 1.\n // > An asterisk \"*\" matches anything except a slash.\n // 2.\n // > Other consecutive asterisks are considered regular asterisks\n // > and will match according to the previous rules.\n const unescaped = p2.replace(/\\\\\\*/g, '[^\\\\/]*')\n return p1 + unescaped\n },\n '*'\n ],\n\n // trailing wildcard, held apart from a literal star\n [\n // The step above leaves a trailing `*` alone, so a single `\\*` is all that\n // can be left at the end here, and what stands in front of it says which\n // kind it is. A wildcard arrives as the escaper wrote it, `\\*` with\n // nothing before it; a literal arrives as the user's own escape, which\n // the escaper doubled, and then the star's own -- `\\\\` and then `\\*`.\n // There is no third case: every backslash still reaching the chain is\n // one `\\*`, `\\[` or `\\ ` carries itself, and each is followed by its\n // own character, so a longer run can never form. This runs while the\n // two are still distinct, before the unescape steps below collapse the\n // literal onto the very `\\*` a wildcard leaves behind.\n /(^|[^\\\\])((?:\\\\\\\\)*)\\\\\\*$/,\n\n (match, p1, p2) =>\n p2 === EMPTY\n // A real wildcard: carry it to `_make` as the marker, so the unescape\n // steps and the trailing-wildcard rewrite can never mistake it for a\n // literal `\\*` (nor the reverse).\n ? p1 + TRAILING_WILDCARD\n // A literal star: leave it exactly as it stands for the unescape steps.\n : match,\n '*'\n ],\n\n [\n // unescape, revert step 3 except for back slash\n // For example, if a user escape a '\\\\*',\n // after step 3, the result will be '\\\\\\\\\\\\*'\n /\\\\\\\\\\\\(?=[$.|*+(){^])/g,\n () => ESCAPE,\n ESCAPE + ESCAPE\n ],\n\n [\n // '\\\\\\\\' -> '\\\\'\n /\\\\\\\\/g,\n () => ESCAPE,\n ESCAPE + ESCAPE\n ],\n\n [\n // Every real bracket expression -- POSIX classes included -- has already\n // been held aside by `extractBrackets`, so the only `[` left in the\n // pattern is an escaped, literal one.\n\n // A backslash could only stand at the end of the range if it quoted the\n // `]`, and `\\]` is held aside long before this.\n /\\\\\\[([^\\]/]*?)($|\\])/g,\n\n // '\\\\[bar]' -> '\\\\\\\\[bar]'\n (match, range, close) => `\\\\[${range}${close}`,\n '['\n ],\n\n // ending\n [\n // 'js' will not match 'js.'\n // 'ab' will not match 'abc'\n DIRECT,\n\n // WTF!\n // https://git-scm.com/docs/gitignore\n // changes in [2.22.1](https://git-scm.com/docs/gitignore/2.22.1)\n // which re-fixes #24, #38\n\n // > If there is a separator at the end of the pattern then the pattern\n // > will only match directories, otherwise the pattern can match both\n // > files and directories.\n\n // 'js*' will not match 'a.js'\n // 'js/' will not match 'a.js'\n // 'js' will match 'a.js' and 'a.js/'\n source => {\n const last = source[source.length - 1]\n\n // The pattern is empty, or ends in a pending marker `_make` owns --\n // the trailing wildcard, or a trailing \"/**\". A trailing `*` that is\n // not the marker is a literal star, which anchors like any other\n // final character.\n if (!last || last === TRAILING_WILDCARD || last === TRAILING_DOUBLESTAR) {\n return source\n }\n\n return last === SLASH\n // foo/ will not match 'foo'\n ? `${source}$`\n // foo matches 'foo' and 'foo/'\n : `${source}(?=$|\\\\/$)`\n }\n ]\n]\n\nconst REGEX_REPLACE_TRAILING_WILDCARD = /(^|\\\\\\/)?\\uE000$/\nconst MODE_IGNORE = 'regex'\nconst MODE_CHECK_IGNORE = 'checkRegex'\nconst UNDERSCORE = '_'\n\nconst replaceTrailingWildcard = (_, p1) => {\n const prefix = p1\n // '\\^':\n // '/*' does not match EMPTY\n // '/*' does not match everything\n\n // '\\\\\\/':\n // 'abc/*' does not match 'abc/'\n ? `${p1}[^/]+`\n\n // 'a*' matches 'a'\n // 'a*' matches 'aa'\n : '[^/]*'\n\n return `${prefix}(?=$|\\\\/$)`\n}\n\nconst REGEX_REPLACE_TRAILING_DOUBLESTAR = /\\uE001$/\n\n// 'abc/**' matches everything under 'abc', but not 'abc/' itself (#21)\nconst replaceTrailingDoublestar = () => '.+(?=$|\\\\/$)'\n\nconst WILDCARD = '[^\\\\/]*'\n\n// The fixed piece between the wildcard at `at` and the next wildcard of the\n// run: the tokens that separate them, joined as they appear in the source.\n// A run never holds two wildcards in a row, so there is always at least one\n// token.\nconst separatorAfter = (run, at) => {\n let separator = EMPTY\n\n for (let index = at + 1; index < run.length && !run[index].wildcard; index ++) {\n separator += run[index].single\n }\n\n return separator\n}\n\n// Where a run of non-slash wildcards is split by fixed pieces --\n// `[^/]*ab[^/]*cd...` -- the engine has many equivalent ways to lay the\n// input across the wildcards, and on input that does not match it works\n// through all of them, so the time grows with the number of wildcards\n// rather than the length of the path. Every wildcard but the last in such a\n// run can be pinned to stop where the piece after it begins, which leaves\n// one way to lay out the input and no rewinding, without changing which\n// paths match: the fixed pieces still bound the count, and the last\n// wildcard still absorbs the rest.\n//\n// A wildcard is pinned to the whole piece, never to the piece's first\n// character. The pin leaves no way back, so a wildcard that stopped at that\n// first character would hand over wherever the character happens to turn\n// up, including the places the rest of the piece cannot follow -- which is\n// how `f*o/*/*` came to miss `foo/b/c`, the first `o` of `foo` not being\n// the one the `o/` after it needs. Every token of a piece matches exactly\n// one character, so the first place the whole piece fits is the leftmost\n// place it can sit, and whatever is left over goes to the wildcards that\n// follow.\n//\n// The source is read one token at a time -- a wildcard, a single-character\n// piece (a literal, an escape, a class), or a parenthesised group or anchor\n// that ends the run -- so only a genuine wildcard is touched.\nconst pinWildcards = source => {\n if (source.indexOf(WILDCARD) < 0) {\n return source\n }\n\n const tokens = []\n const {length} = source\n let index = 0\n\n while (index < length) {\n const char = source[index]\n\n if (source.startsWith(WILDCARD, index)) {\n tokens.push({wildcard: true})\n index += WILDCARD.length\n } else if (char === '[') {\n let end = index + 1\n\n if (source[end] === '^') {\n end ++\n }\n\n if (source[end] === ']') {\n end ++\n }\n\n while (end < length && source[end] !== ']') {\n end += source[end] === ESCAPE\n ? 2\n : 1\n }\n\n end ++\n tokens.push({single: source.slice(index, end)})\n index = end\n } else if (char === ESCAPE) {\n tokens.push({single: source.slice(index, index + 2)})\n index += 2\n } else if (char === '(') {\n let depth = 0\n let end = index\n\n do {\n if (source[end] === ESCAPE) {\n end ++\n } else if (source[end] === '(') {\n depth ++\n } else if (source[end] === ')') {\n depth --\n }\n\n end ++\n } while (end < length && depth > 0)\n\n if ('*+?'.indexOf(source[end]) >= 0) {\n end ++\n }\n\n tokens.push({boundary: source.slice(index, end)})\n index = end\n } else if (char === '^' || char === '$') {\n tokens.push({boundary: char})\n index ++\n } else {\n tokens.push({single: char})\n index ++\n }\n }\n\n let out = EMPTY\n let run = []\n\n const flush = () => {\n let lastWildcard\n\n run.forEach((token, at) => {\n if (token.wildcard) {\n lastWildcard = at\n }\n })\n\n run.forEach((token, at) => {\n if (!token.wildcard) {\n out += token.single\n return\n }\n\n // Every wildcard but the last is pinned to the whole piece that\n // follows it, for the reason set out above this function. The last\n // one stays as it is and takes up the rest.\n out += at === lastWildcard\n ? WILDCARD\n : `(?:(?!${separatorAfter(run, at)})[^\\\\/])*`\n })\n\n run = []\n }\n\n tokens.forEach(token => {\n if (token.boundary === undefined) {\n run.push(token)\n return\n }\n\n flush()\n out += token.boundary\n })\n\n flush()\n\n return out\n}\n\n// @param {pattern}\nconst makeRegexPrefix = pattern => {\n // `/**` matches every path, as `**` does. The translation below only finds\n // a globstar beside a slash it keeps, and the leading one is turned into\n // an anchor, so `/**` would come out as `/*` and match one level only.\n // Here rather than in `createRule`, so that `checkSourceOf`, which\n // compiles `/**/` again without its trailing slash, gets it too.\n if (REGEX_ANCHORED_GLOBSTAR.test(pattern)) {\n pattern = '**'\n }\n\n const {source, sources} = extractBrackets(pattern)\n\n const replaced = REPLACERS.reduce(\n // A pass whose matcher finds nothing hands back the very string it was\n // given, so asking first costs a search and saves a rewrite. Ten of the\n // fifteen passes never fire for a typical .gitignore line, and between\n // them they were 45% of this chain.\n (prev, [matcher, replacer, required]) => {\n if (matcher === DIRECT) {\n return replacer(prev, pattern)\n }\n\n if (required !== UNDEFINED && prev.indexOf(required) < 0) {\n return prev\n }\n\n // A pass whose matcher finds nothing hands back the very string it was\n // given, so asking first costs a search and saves a rewrite.\n return matcher.test(prev)\n ? prev.replace(matcher, replacer.bind(pattern))\n : prev\n },\n source\n )\n\n // Most patterns hold no bracket expression at all, and then there is\n // nothing to put back.\n return sources.length\n ? replaced.replace(\n REGEX_RESTORE_PLACEHOLDER,\n (match, index) => sources[index]\n )\n : replaced\n}\n\n// `checkRegex` tests a path with a trailing slash, 'abc/', the way\n// `git check-ignore` matches that literal string once the directory itself\n// is known not to be excluded (see `checkIgnore`): a trailing '/' of the\n// pattern is dropped, a basename pattern sees an empty basename, and only a\n// pattern whose last segment is a pending wildcard can match what is left\n// after the final slash -- 'abc/*' and 'abc/**' match 'abc/', and 'abc/**'\n// also matches 'abc/d/' (#77, #169).\nconst checkSourceOf = (body, prefix) => {\n if (body[body.length - 1] === SLASH) {\n prefix = makeRegexPrefix(body.slice(0, - 1))\n }\n\n const head = prefix.slice(0, - 1)\n const last = prefix[prefix.length - 1]\n\n return last === TRAILING_WILDCARD\n ? `${head}$`\n : last === TRAILING_DOUBLESTAR\n ? `${head}.*$`\n : NEVER_MATCH\n}\n\n// A trailing slash does not stop a pattern being basename-only: it restricts\n// the match to a directory, it does not let the pattern reach across one.\n// Everything else a pattern can hold -- a wildcard, a character class, an\n// escape -- stays inside a single path segment too, so a pattern with no\n// separator in it can only ever describe the last one.\nconst matchesBasename = body => {\n const index = body.indexOf(SLASH)\n\n return index < 0 || index === body.length - 1\n}\n\n// The last segment of a path, keeping a trailing slash, because a pattern that\n// ends in one matches only a directory.\n// 'a/b/c.js' -> 'c.js'; 'a/b/' -> 'b/'; 'c.js' -> 'c.js' (no copy made)\nconst basenameOf = path => {\n const end = path.length - 1\n\n const index = path.lastIndexOf(\n SLASH,\n path[end] === SLASH\n ? end - 1\n : end\n )\n\n return index < 0\n ? path\n : path.slice(index + 1)\n}\n\n// The parent directory of a path, with its trailing separator, or EMPTY when\n// the path has none.\n// 'a/b/c' -> 'a/b/'; 'a/b/' -> 'a/'; 'a' -> EMPTY; 'a/' -> EMPTY\n//\n// A path holding an empty segment has to be taken apart, because its\n// ancestors are not prefixes of it: the parent of 'a//b' is 'a/', not\n// 'a//', and the parent of '/a/' is nothing at all. Both shapes reach here\n// -- 'a//b' is accepted outright, and `checkIgnore` does not put the path\n// it is given through the relative-path check.\n//\n// Every other path is a prefix of itself, and cutting one costs a fraction of\n// splitting it into an array and joining that back at every level: 73ns\n// against 207ns.\nconst parentOf = path => {\n if (\n path.charCodeAt(0) === SLASH_CODE\n || path.indexOf(DOUBLE_SLASH) >= 0\n ) {\n const slices = path.split(SLASH).filter(Boolean)\n\n slices.pop()\n\n return slices.length\n ? slices.join(SLASH) + SLASH\n : EMPTY\n }\n\n const end = path.length - 1\n\n // Look back from before a trailing separator, since that one belongs to the\n // path itself.\n //\n // A negative place to start would be a trap here: `lastIndexOf` clamps one\n // to 0 and searches there rather than reporting no match, so '/' would\n // come back as its own parent and the walk would never end. It cannot\n // happen -- that is the only path short enough to produce one, and the\n // test above has already sent it the other way.\n const cut = path.lastIndexOf(\n SLASH,\n path.charCodeAt(end) === SLASH_CODE\n ? end - 1\n : end\n )\n\n return cut < 0\n ? EMPTY\n : path.slice(0, cut + 1)\n}\n\nconst isString = subject => typeof subject === 'string'\n\n// Blank lines and comments are told by `createRule`, once the pattern is\n// normalized.\nconst checkPattern = pattern => pattern\n && isString(pattern)\n && !REGEX_INVALID_TRAILING_BACKSLASH.test(pattern)\n\nconst splitPattern = pattern => pattern\n.split(REGEX_SPLITALL_CRLF)\n.filter(Boolean)\n\nclass IgnoreRule {\n constructor (\n pattern,\n mark,\n body,\n ignoreCase,\n negative,\n prefix\n ) {\n this.pattern = pattern\n this.mark = mark\n this.negative = negative\n\n define(this, 'body', body)\n define(this, 'ignoreCase', ignoreCase)\n define(this, 'regexPrefix', prefix)\n }\n\n // Worked out on first use and kept behind an own property, the way `regex`\n // caches itself in `_regex`. Deciding it in the constructor instead would\n // add a fourth `defineProperty` to every rule ever built, which cost 4% of\n // every compile -- including the compiles of rules that are never matched\n // against anything.\n get _basenameOnly () {\n return define(this, '_basenameOnly', matchesBasename(this.body))\n }\n\n get regex () {\n const key = UNDERSCORE + MODE_IGNORE\n\n if (this[key]) {\n return this[key]\n }\n\n return this._make(MODE_IGNORE, key)\n }\n\n get checkRegex () {\n const key = UNDERSCORE + MODE_CHECK_IGNORE\n\n if (this[key]) {\n return this[key]\n }\n\n return this._make(MODE_CHECK_IGNORE, key)\n }\n\n _make (mode, key) {\n const str = pinWildcards(\n mode === MODE_IGNORE\n ? this.regexPrefix\n .replace(REGEX_REPLACE_TRAILING_WILDCARD, replaceTrailingWildcard)\n .replace(REGEX_REPLACE_TRAILING_DOUBLESTAR, replaceTrailingDoublestar)\n : checkSourceOf(this.body, this.regexPrefix)\n )\n\n const regex = this.ignoreCase\n ? new RegExp(str, 'i')\n : new RegExp(str)\n\n return define(this, key, regex)\n }\n}\n\nconst isLineEnd = char => char === '\\r' || char === '\\n'\n\n// Drop a line terminator, which can remain when patterns are passed as an\n// array, and then the trailing spaces. Git trims spaces only, and a space\n// escaped by an odd run of backslashes stays, unescaped, as the last one.\n// Scanned from the end: a regular expression can only try each start in\n// turn, which is quadratic over a long run of spaces or backslashes.\n// 'a ' -> 'a'; 'a\\ ' -> 'a '; 'a\\\\ ' -> 'a\\\\'; 'a\\t' -> 'a\\t'\nconst trimEnd = body => {\n let end = body.length\n\n while (end && isLineEnd(body[end - 1])) {\n end --\n }\n\n const lineEnd = end\n\n while (end && body[end - 1] === SPACE) {\n end --\n }\n\n if (end === lineEnd) {\n return body.slice(0, end)\n }\n\n let backslashes = 0\n\n while (backslashes < end && body[end - backslashes - 1] === ESCAPE) {\n backslashes ++\n }\n\n return backslashes % 2\n ? body.slice(0, end - 1) + SPACE\n : body.slice(0, end)\n}\n\nconst createRule = ({\n pattern,\n mark\n}, ignoreCase) => {\n // Git drops a BOM before it reads the first line, so before anything else.\n let body = pattern[0] === BOM\n ? pattern.slice(1)\n : pattern\n\n // > A line starting with # serves as a comment.\n if (body[0] === '#') {\n return\n }\n\n let negative = false\n\n // > An optional prefix \"!\" which negates the pattern;\n if (body[0] === '!') {\n negative = true\n body = body.slice(1)\n }\n\n // Normalize the body before checking which slashes anchor the pattern.\n // Otherwise `bar/ ` is mistaken for a pattern containing an inner slash.\n // Only a body ending in a space or a line terminator has anything to trim.\n const last = body[body.length - 1]\n\n if (last === SPACE || last === '\\r' || last === '\\n') {\n body = trimEnd(body)\n }\n\n // > A blank line matches no files, so it can serve as a separator for\n // > readability.\n // Nor does a lone \"!\", or anything else left empty here: an empty pattern\n // would compile to a regex matching every path.\n if (!body) {\n return\n }\n\n body = body\n // > Put a backslash (\"\\\") in front of the first \"!\" for patterns that\n // > begin with a literal \"!\", for example, `\"\\!important!.txt\"`.\n .replace(REGEX_REPLACE_LEADING_EXCAPED_EXCLAMATION, '!')\n // > Put a backslash (\"\\\") in front of the first hash for patterns that\n // > begin with a hash.\n .replace(REGEX_REPLACE_LEADING_EXCAPED_HASH, '#')\n\n const regexPrefix = makeRegexPrefix(body)\n\n return new IgnoreRule(\n pattern,\n mark,\n body,\n ignoreCase,\n negative,\n regexPrefix\n )\n}\n\nclass RuleManager {\n constructor (ignoreCase) {\n this._ignoreCase = ignoreCase\n this._rules = []\n\n // How many of the rules git would tag `EXC_FLAG_NODIR`.\n //\n // The scan uses it to decide, once for the whole set, whether handing\n // those rules the basename is worth what it costs the others. The\n // shortcut saves a full-path scan on every rule it applies to and costs\n // a check on every rule it does not, so a set where almost nothing is\n // basename-only comes out behind -- a 955 pattern set with 44 of them\n // measured 19% slower with the shortcut always on.\n //\n // Deciding this by measurement rather than by meaning is safe: a\n // basename-only pattern gives the very same answer against the whole\n // path, it just takes longer to say so. The choice can only change how\n // fast the scan runs, never what it returns.\n this._basenameCount = 0\n }\n\n _add (pattern) {\n // #32\n if (pattern && pattern[KEY_IGNORE]) {\n this._rules = this._rules.concat(pattern._rules._rules)\n this._basenameCount += pattern._rules._basenameCount\n this._added = true\n return\n }\n\n if (isString(pattern)) {\n pattern = {\n pattern\n }\n }\n\n const rule = checkPattern(pattern.pattern)\n && createRule(pattern, this._ignoreCase)\n\n if (rule) {\n this._added = true\n this._rules.push(rule)\n\n // Deliberately not `rule._basenameOnly`: reading that would materialise\n // the rule's own copy, and the whole point of leaving it lazy is that\n // a rule which is compiled and never matched never pays for it.\n if (matchesBasename(rule.body)) {\n this._basenameCount ++\n }\n }\n }\n\n // @param {Array<string> | string | Ignore} pattern\n add (pattern) {\n this._added = false\n\n makeArray(\n isString(pattern)\n ? splitPattern(pattern)\n : pattern\n ).forEach(this._add, this)\n\n if (this._added) {\n this._literalRules = UNDEFINED\n }\n\n return this._added\n }\n\n // Match the literal 'abc/' for `checkIgnore`, last rule wins. Only a rule\n // ending in a wildcard can match it (see `checkSourceOf`), so the rest\n // are left out once, rather than tested or compiled for every path.\n testLiteral (path) {\n const rules = this._literalRules || (\n this._literalRules = this._rules.filter(\n ({body}) => body[body.length - (\n body[body.length - 1] === SLASH ? 2 : 1\n )] === '*'\n )\n )\n\n let ignored = false\n let unignored = false\n let matchedRule\n\n for (let index = rules.length - 1; index >= 0; index --) {\n const rule = rules[index]\n\n if (rule.checkRegex.test(path)) {\n ignored = !rule.negative\n unignored = rule.negative\n matchedRule = rule.negative\n ? UNDEFINED\n : rule\n break\n }\n }\n\n const ret = {\n ignored,\n unignored\n }\n\n if (matchedRule) {\n ret.rule = matchedRule\n }\n\n return ret\n }\n\n // Test one single path without recursively checking parent directories\n //\n // - mode `string` either `MODE_IGNORE` or `MODE_CHECK_IGNORE`\n\n // @returns {TestResult}\n test (path, mode) {\n // Most of a .gitignore is patterns with no slash in them, and running\n // those against the whole path makes the regular expression engine walk\n // every directory name on the way to the only segment that could match.\n // Handing them the basename instead is what git does, and it is where\n // the time in a directory walk goes: the rule scan was two thirds of it.\n const rules = this._rules\n const {length} = rules\n\n const shortcut = this._basenameCount * 2 >= length\n\n const basename = shortcut\n ? basenameOf(path)\n : path\n\n // The last rule to match decides, as in git, and it is the rule\n // `git check-ignore -v` reports, so the scan runs from the end and stops\n // at the first match.\n // A plain loop rather than `forEach`, so that `path`, `basename` and\n // `shortcut` are locals. As a callback they became closure variables,\n // and reaching for one of those once per rule cost 10% of a scan over a\n // large rule set -- more than the shortcut they were there to serve.\n for (let index = length - 1; index >= 0; index --) {\n const rule = rules[index]\n\n if (rule[mode].test(\n shortcut && rule._basenameOnly\n ? basename\n : path\n )) {\n const {negative} = rule\n\n const ret = {\n ignored: !negative,\n unignored: negative\n }\n\n if (!negative) {\n ret.rule = rule\n }\n\n return ret\n }\n }\n\n return {\n ignored: false,\n unignored: false\n }\n }\n}\n\nconst throwError = (message, Ctor) => {\n throw new Ctor(message)\n}\n\nconst checkPath = (path, originalPath, doThrow) => {\n if (!isString(path)) {\n return doThrow(\n `path must be a string, but got \\`${originalPath}\\``,\n TypeError\n )\n }\n\n // We don't know if we should ignore EMPTY, so throw\n if (!path) {\n return doThrow(`path must not be empty`, TypeError)\n }\n\n // Check if it is a relative path\n if (checkPath.isNotRelative(path)) {\n const r = '`path.relative()`d'\n return doThrow(\n `path should be a ${r} string, but got \"${originalPath}\"`,\n RangeError\n )\n }\n\n return true\n}\n\n// > pathname should be a `path.relative()`d one\n//\n// The same thing `REGEX_TEST_INVALID_PATH` says, spelled out: a path is not\n// relative if it begins with a separator, or with `./` or `../`, or is\n// nothing but `.` or `..`. Every match is decided by the first three\n// characters, and this runs on every path handed to the library -- where it\n// was 55% of a cached lookup, more than the cache lookup itself.\nconst isNotRelative = path => {\n const first = path.charCodeAt(0)\n\n if (first === SLASH_CODE) {\n return true\n }\n\n if (first !== DOT_CODE) {\n return false\n }\n\n // '.'\n if (path.length === 1) {\n return true\n }\n\n const second = path.charCodeAt(1)\n\n // './'\n if (second === SLASH_CODE) {\n return true\n }\n\n if (second !== DOT_CODE) {\n return false\n }\n\n // '..' or '../'\n return path.length === 2 || path.charCodeAt(2) === SLASH_CODE\n}\n\ncheckPath.isNotRelative = isNotRelative\n\n// On windows, the following function will be replaced\n/* istanbul ignore next */\ncheckPath.convert = p => p\n\n\nclass Ignore {\n constructor ({\n ignorecase = true,\n ignoreCase = ignorecase,\n allowRelativePaths = false\n } = {}) {\n define(this, KEY_IGNORE, true)\n\n this._rules = new RuleManager(ignoreCase)\n this._strictPathCheck = !allowRelativePaths\n this._initCache()\n }\n\n _initCache () {\n // A cache for the result of `.ignores()`\n this._ignoreCache = Object.create(null)\n\n // A cache for the result of `.test()`\n this._testCache = Object.create(null)\n }\n\n add (pattern) {\n if (this._rules.add(pattern)) {\n // Some rules have just added to the ignore,\n // making the behavior changed,\n // so we need to re-initialize the result cache\n this._initCache()\n }\n\n return this\n }\n\n // legacy\n addPattern (pattern) {\n return this.add(pattern)\n }\n\n // @returns {TestResult}\n _test (originalPath, cache) {\n const path = originalPath\n // Supports nullable path\n && checkPath.convert(originalPath)\n\n checkPath(\n path,\n originalPath,\n this._strictPathCheck\n ? throwError\n : RETURN_FALSE\n )\n\n return this._t(path, cache)\n }\n\n checkIgnore (path) {\n // If the path doest not end with a slash, `.ignores()` is much equivalent\n // to `git check-ignore`\n if (path.charCodeAt(path.length - 1) !== SLASH_CODE) {\n return this.test(path)\n }\n\n // Like `git check-ignore`: a directory excluded by itself or by an\n // ancestor settles it, and only then is the literal 'abc/' matched\n // against the rules (see `checkSourceOf`).\n const dir = this._t(path, this._testCache)\n\n if (dir.ignored) {\n return dir\n }\n\n const literal = this._rules.testLiteral(path)\n\n return literal.ignored || literal.unignored\n ? literal\n : dir\n }\n\n _t (\n // The path to be tested\n path,\n\n // The cache for the result of a certain checking\n cache\n ) {\n if (path in cache) {\n return cache[path]\n }\n\n const parentPath = parentOf(path)\n\n // If the path contains a parent directory, check the parent first\n const parent = parentPath\n ? this._t(parentPath, cache)\n : UNDEFINED\n\n return cache[path] = parent && parent.ignored\n // > It is not possible to re-include a file if a parent directory of\n // > that file is excluded.\n ? parent\n : this._rules.test(path, MODE_IGNORE)\n }\n\n ignores (path) {\n return this._test(path, this._ignoreCache).ignored\n }\n\n createFilter () {\n return path => !this.ignores(path)\n }\n\n filter (paths) {\n return makeArray(paths).filter(this.createFilter())\n }\n\n // @returns {TestResult}\n test (path) {\n return this._test(path, this._testCache)\n }\n}\n\nconst factory = options => new Ignore(options)\n\nconst isPathValid = path =>\n checkPath(path && checkPath.convert(path), path, RETURN_FALSE)\n\n/* istanbul ignore next */\nconst setupWindows = () => {\n /* eslint no-control-regex: \"off\" */\n const makePosix = str => /^\\\\\\\\\\?\\\\/.test(str)\n || /[\"<>|\\u0000-\\u001F]+/u.test(str)\n ? str\n : str.replace(/\\\\/g, '/')\n\n checkPath.convert = makePosix\n\n // 'C:\\\\foo' <- 'C:\\\\foo' has been converted to 'C:/'\n // 'd:\\\\foo'\n const REGEX_TEST_WINDOWS_PATH_ABSOLUTE = /^[a-z]:\\//i\n checkPath.isNotRelative = path =>\n REGEX_TEST_WINDOWS_PATH_ABSOLUTE.test(path)\n || isNotRelative(path)\n}\n\n\n// Windows\n// --------------------------------------------------------------\n/* istanbul ignore next */\nif (\n // Detect `process` so that it can run in browsers.\n typeof process !== 'undefined'\n && process.platform === 'win32'\n) {\n setupWindows()\n}\n\n// COMMONJS_EXPORTS ////////////////////////////////////////////////////////////\n\nmodule.exports = factory\n\n// Although it is an anti-pattern,\n// it is still widely misused by a lot of libraries in github\n// Ref: https://github.com/search?q=ignore.default%28%29&type=code\nfactory.default = factory\n\nmodule.exports.isPathValid = isPathValid\n\n// For testing purposes\ndefine(module.exports, Symbol.for('setupWindows'), setupWindows)\n","import type { CheckResult, PermissionHandler, Rule } from \"../types.ts\"\n\nimport { normPath, prettyPath } from \"@zaly/shared\"\nimport ignore from \"ignore\"\nimport { dirname, isAbsolute, relative } from \"pathe\"\n\n/**\n * Handler for `Rule<\"read\" | \"write\">` — one impl serves both scopes\n * because they share the same matcher and the same workspace state.\n *\n * Algorithm:\n * 1. Normalize candidate to an absolute path.\n * 2. Sensitive-file check (env, ssh keys, credentials) → deny.\n * 3. Find the longest-prefix workspace containing the path. None →\n * ask, with a `kind: \"workspace\"` suggestion for the containing\n * directory.\n * 4. Inside a workspace: resolve the first matching rule against the\n * workspace-relative path. Earlier rules win.\n * 5. Default when no rule matches but the path is inside a workspace:\n * `allow` for reads (workspace = trust signal), `ask` for writes\n * (mutating ops escalate by default; users add `Write(...)` rules\n * to whitelist).\n *\n * Pattern grammar (per Claude-Code conventions):\n * //abs/path absolute filesystem path\n * ~/path path under home directory\n * /path or path workspace-relative (passed through to gitignore)\n */\nexport const fileHandler: PermissionHandler<\"read\" | \"write\"> = {\n validate(input, ctx): CheckResult {\n const abs = normPath(ctx.cwd, input)\n\n if (isSensitiveFile(abs)) {\n return { reason: `${abs}: sensitive file`, verdict: \"deny\" }\n }\n\n const ws = longestWorkspace(abs, ctx.workspaces)\n const inWorkspace = ws !== undefined\n\n // Inside-workspace + path === root: the workspace itself (e.g. `find .`\n // resolved to cwd). Workspace containment alone is enough to allow.\n if (inWorkspace && abs === ws) return { verdict: \"allow\" }\n\n // Outside any workspace, fall through to rule matching with `/` as\n // synthetic root. Lets blanket rules like `read(*)` (yolo preset)\n // override the default \"ask outside workspace\" verdict, while\n // narrower presets keep the safer default.\n const base = ws ?? \"/\"\n const rel = relative(base, abs)\n\n const verb = ctx.scope === \"read\" ? \"reading\" : \"writing\"\n\n const rule = resolveRule(base, rel, ctx.rules)\n if (rule?.policy === \"deny\") return { reason: `${abs}: denied by rule`, verdict: \"deny\" }\n if (rule?.policy === \"ask\") {\n return {\n ask: `Allow ${verb} ${prettyPath(abs)}?`,\n reason: `${abs}: rule requires confirmation`,\n suggestions: [{ kind: \"rule\", pattern: `/${rel}`, scope: ctx.scope }],\n verdict: \"ask\",\n }\n }\n if (rule?.policy === \"allow\") return { verdict: \"allow\" }\n\n // No rule matched. Defaults differ by location:\n // - Inside a workspace: reads ride on workspace trust → allow;\n // writes escalate → ask.\n // - Outside any workspace: always ask, and surface a\n // workspace-add suggestion so the user can promote the parent\n // dir without composing a rule by hand.\n if (!inWorkspace) {\n const parent = dirname(abs)\n return {\n ask: `Allow ${verb} ${prettyPath(abs)}? (not in any workspace)`,\n reason: `${abs}: outside any workspace`,\n suggestions: [\n { description: `add ${parent} as workspace`, kind: \"workspace\", path: parent },\n ],\n verdict: \"ask\",\n }\n }\n if (ctx.scope === \"read\") return { verdict: \"allow\" }\n return {\n ask: `Allow ${verb} ${prettyPath(abs)}?`,\n reason: `${abs}: write requires confirmation`,\n suggestions: [{ kind: \"rule\", pattern: `/${rel}`, scope: \"write\" }],\n verdict: \"ask\",\n }\n },\n}\n\n/** True if `path` looks like a credentials/keys file we shouldn't\n * expose to the model by default. Conservative — false positives are\n * fine here, and users can override via `allow` rules. */\nexport function isSensitiveFile(path: string): boolean {\n return SENSITIVE_PATTERNS.some((re) => re.test(path))\n}\n\n/** Common locations for credentials, keys, and other sensitive data.\n * Matched against the path string directly — covers both absolute and\n * relative inputs. Add to this list as new gotchas surface. */\nconst SENSITIVE_PATTERNS: RegExp[] = [\n /(?:^|\\/)\\.env(?:\\.|$)/, // .env, .env.local, .env.production, ...\n /(?:^|\\/)\\.git\\/(?!hooks\\/)/, // .git/* but not hooks (commonly inspected)\n /(?:^|\\/)\\.ssh\\//, // ssh keys + config\n /(?:^|\\/)\\.aws\\/credentials/,\n /(?:^|\\/)\\.netrc$/,\n /(?:^|\\/)id_(?:rsa|dsa|ed25519|ecdsa)(?:\\.pub)?$/,\n /(?:^|\\/)\\.npmrc$/, // can hold auth tokens\n /(?:^|\\/)\\.pypirc$/,\n /(?:^|\\/)secrets?\\//,\n /(?:^|\\/)credentials?(?:\\.|\\/)/,\n]\n\n/** Longest-prefix match against the workspace list — returns the\n * containing workspace's absolute path, or undefined if none contain\n * the candidate. Workspaces arrive pre-normalized from the manager. */\nfunction longestWorkspace(abs: string, workspaces: readonly string[]): string | undefined {\n let best: string | undefined\n for (const root of workspaces) {\n if (abs === root || abs.startsWith(root.endsWith(\"/\") ? root : `${root}/`)) {\n if (best === undefined || root.length > best.length) best = root\n }\n }\n return best\n}\n\n/** Resolve the first matching rule.\n * Patterns get normalized (`//abs`, `~/`, `/rel`, `rel`) into\n * workspace-rooted gitignore syntax; patterns that resolve outside the\n * candidate's workspace are dropped (they don't apply here). */\nfunction resolveRule(\n workspace: string,\n rel: string,\n rules: readonly Rule<\"read\" | \"write\">[]\n): Rule<\"read\" | \"write\"> | undefined {\n if (rel === \"\") return undefined\n for (const rule of rules) {\n const norm = normalizePattern(rule.pattern, workspace)\n if (norm === undefined) continue\n try {\n if (ignore().add(norm).ignores(rel)) return rule\n } catch {\n // Skip invalid rels.\n }\n }\n}\n\nfunction normalizePattern(pattern: string, workspace: string): string | undefined {\n if (pattern.startsWith(\"//\")) {\n return relativizeToWorkspace(pattern.slice(1), workspace)\n }\n if (pattern.startsWith(\"~/\")) {\n return relativizeToWorkspace(normPath(pattern), workspace)\n }\n // /pattern or pattern → already workspace-relative gitignore syntax.\n return pattern\n}\n\nfunction relativizeToWorkspace(absPattern: string, workspace: string): string | undefined {\n const rel = relative(workspace, absPattern)\n if (rel === \"\" || rel.startsWith(\"..\") || isAbsolute(rel)) return undefined\n return `/${rel}`\n}\n","import type { CheckResult, PermissionHandler, Rule } from \"../types.ts\"\n\nimport ignore from \"ignore\"\n\n/**\n * Generic tool-scope handler.\n *\n * Used by `Tasks` to gate every tool dispatch on the tool name, and\n * available to tools themselves for richer checks (e.g. fetch passing\n * `fetch:example.com` so users can ask-for-domain).\n *\n * Pattern grammar is gitignore-style — reuses the `ignore` package so\n * the syntax matches `read` / `write` patterns. Common shapes:\n *\n * \"tool\" → bare scope; matches every input (default-allow)\n * \"tool(bash)\" → exact match for `\"bash\"`\n * \"tool(fetch:*)\" → glob match `\"fetch:...\"`\n * \"tool(task_*)\" → glob match `\"task_...\"`\n *\n * Resolution is first-match-wins. Default verdict when no rule matches is\n * `allow` — an unconfigured `tool` scope should not surprise users by\n * gating ordinary tool calls.\n */\nexport const toolHandler: PermissionHandler<\"tool\"> = {\n validate(input, ctx): CheckResult {\n const rule = resolveRule(input, ctx.rules)\n if (rule?.policy === \"deny\") {\n return { reason: `tool ${input}: denied by rule`, verdict: \"deny\" }\n }\n if (rule?.policy === \"ask\") {\n return {\n ask: `Allow tool ${input}?`,\n reason: `tool ${input}: rule requires confirmation`,\n suggestions: [{ kind: \"rule\", pattern: input, scope: \"tool\" }],\n verdict: \"ask\",\n }\n }\n return { verdict: \"allow\" }\n },\n}\n\nfunction resolveRule(input: string, rules: readonly Rule<\"tool\">[]): Rule<\"tool\"> | undefined {\n for (const rule of rules) {\n if (ignore().add(rule.pattern).ignores(input)) return rule\n }\n}\n","import type { PermissionHandler } from \"../types.ts\"\n\nimport { createRegistry } from \"@zaly/shared/registry\"\nimport { bashHandler } from \"./bash.ts\"\nimport { fileHandler } from \"./files.ts\"\nimport { toolHandler } from \"./tool.ts\"\n\nexport type HandlerLoader = () => PermissionHandler<string>\n\nconst builtin = {\n bash: () => bashHandler,\n read: () => fileHandler,\n tool: () => toolHandler,\n write: () => fileHandler,\n} as const satisfies Record<string, HandlerLoader>\n\n/** Open registry of permission scopes — declaration-merge to add your\n * own. The keys give `ctx.need(\"…\", input)` typed autocomplete and\n * catch typos at compile time. The value carries the *input* type for\n * that scope (almost always `string` — files take paths, bash takes\n * commands, the generic `tool` scope takes the tool name).\n *\n * Built-ins:\n * - `bash` → command string\n * - `read` → absolute path\n * - `write` → absolute path\n * - `tool` → tool name (or richer `name:arg` shape per tool)\n *\n * Add your own scope:\n *\n * ```ts\n * declare module \"@zaly/agent\" {\n * interface PermissionScopes {\n * fetch: string // expects a domain (or \"*\" for any)\n * }\n * }\n * ```\n *\n * Then `ctx.need(\"fetch\", domain)` is typed end-to-end. You still need\n * to register a runtime handler via `handlerRegistry.register(\"fetch\", …)`\n * — this interface is only the type-side declaration.\n */\nexport interface PermissionScopes {\n bash: string\n read: string\n tool: string\n write: string\n}\n\nexport type BuiltinScope = keyof typeof builtin\nexport type PermissionScope = keyof PermissionScopes\nexport type AnyScope = PermissionScope | (string & {})\n\nexport const handlerRegistry = createRegistry<HandlerLoader>(\"scope\").from(builtin)\n"],"ignoreList":[1],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AAyBA,MAAa,cAAyC,EACpD,SAAS,OAAO,KAAkB;CAChC,MAAM,SAAS,UAAU,KAAK;CAC9B,IAAI,CAAC,OAAO,IAAI;EACd,IAAI;GAAC;GAAQ;GAAQ;EAAO,CAAC,CAAC,OAAO,UAAU,IAAI,YAAY,KAAK,CAAC,GACnE,OAAO,EAAE,SAAS,QAAQ;EAE5B,OAAO;GACL,KAAK,6BAA6B,OAAO,OAAO;GAChD,QAAQ,OAAO;GACf,SAAS;EACX;CACF;CAEA,IAAI,UAAmB;CACvB,IAAI;CACJ,MAAM,cAA4B,CAAC;CAEnC,KAAK,MAAM,OAAO,OAAO,UAAU;EAIjC,MAAM,aAAa,aAAa,IAAI,OAAO,GAAG,KAAK;EACnD,IAAI,IAAI,mBAAmB,eAAe,SACxC,OAAO;GACL,KAAK,mCAAmC,IAAI,IAAI;GACh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,MAAM,CAAC,GAAG,SAAS;CAE1D,IAAI,QAAQ,WAAW,IAAI,GACzB,OAAO,sBAAsB,SAAS,OAAO,GAAG,SAAS;CAG3D,OAAO;AACT;AAEA,SAAS,sBAAsB,YAAoB,WAAuC;CACxF,MAAM,MAAM,SAAS,WAAW,UAAU;CAC1C,IAAI,QAAQ,MAAM,IAAI,WAAW,IAAI,KAAK,WAAW,GAAG,GAAG,OAAO,KAAA;CAClE,OAAO,IAAI;AACb;;;;;;;;;;;;;;;;;;;;;AC5IA,MAAa,cAAyC,EACpD,SAAS,OAAO,KAAkB;CAChC,MAAM,OAAO,YAAY,OAAO,IAAI,KAAK;CACzC,IAAI,MAAM,WAAW,QACnB,OAAO;EAAE,QAAQ,QAAQ,MAAM;EAAmB,SAAS;CAAO;CAEpE,IAAI,MAAM,WAAW,OACnB,OAAO;EACL,KAAK,cAAc,MAAM;EACzB,QAAQ,QAAQ,MAAM;EACtB,aAAa,CAAC;GAAE,MAAM;GAAQ,SAAS;GAAO,OAAO;EAAO,CAAC;EAC7D,SAAS;CACX;CAEF,OAAO,EAAE,SAAS,QAAQ;AAC5B,EACF;AAEA,SAAS,YAAY,OAAe,OAA0D;CAC5F,KAAK,MAAM,QAAQ,OACjB,KAAA,GAAIC,cAAAA,QAAAA,CAAO,CAAC,CAAC,IAAI,KAAK,OAAO,CAAC,CAAC,QAAQ,KAAK,GAAG,OAAO;AAE1D;ACQA,MAAa,kBAAkB,eAA8B,OAAO,CAAC,CAAC,KAAK;CA3CzE,YAAY;CACZ,YAAY;CACZ,YAAY;CACZ,aAAa;AAwC4D,CAAO"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { createRequire } from "node:module";
|
|
2
|
-
|
|
2
|
+
// \0rolldown/runtime.js
|
|
3
3
|
var __create = Object.create;
|
|
4
4
|
var __defProp = Object.defineProperty;
|
|
5
5
|
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
@@ -31,5 +31,4 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
|
|
|
31
31
|
enumerable: true
|
|
32
32
|
}) : target, mod));
|
|
33
33
|
var __require = /* #__PURE__ */ (() => createRequire(import.meta.url))();
|
|
34
|
-
//#endregion
|
|
35
34
|
export { __toESM as i, __exportAll as n, __require as r, __commonJSMin as t };
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { AiError, defineTool } from "@zaly/ai";
|
|
2
2
|
import { Type } from "typebox";
|
|
3
|
-
|
|
3
|
+
// src/tools/search.ts
|
|
4
4
|
/**
|
|
5
5
|
* Web search via Brave's LLM Context API.
|
|
6
6
|
*
|
|
@@ -119,7 +119,6 @@ const searchTool = defineTool({
|
|
|
119
119
|
return parts;
|
|
120
120
|
}
|
|
121
121
|
});
|
|
122
|
-
//#endregion
|
|
123
122
|
export { searchTool };
|
|
124
123
|
|
|
125
|
-
//# sourceMappingURL=search-
|
|
124
|
+
//# sourceMappingURL=search-B-89W3SM.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"search-
|
|
1
|
+
{"version":3,"file":"search-B-89W3SM.mjs","names":[],"sources":["../src/tools/search.ts"],"sourcesContent":["import type { MetaPart, TextPart } from \"@zaly/ai\"\n\nimport { defineTool, AiError } from \"@zaly/ai\"\nimport { Type } from \"typebox\"\n\n/**\n * Web search via Brave's LLM Context API.\n *\n * Returns extracted snippets pre-chunked from each source page rather\n * than just titles + URLs, so the model gets grounding content in one\n * call without a follow-up `fetch`. Each result lands as one TextPart\n * (snippets joined per-source) preceded by a `<source>` MetaPart with\n * URL / title / age metadata.\n *\n * Authentication: reads `BRAVE_API_KEY` from the environment. Tools\n * don't get config-injected today, so the env var is the simplest\n * surface — same convention `fetch`-style tools use elsewhere.\n *\n * Endpoint: `https://api.search.brave.com/res/v1/llm/context`. Docs:\n * https://api.search.brave.com/app/documentation/llm-context/get-started\n */\n\nconst ENDPOINT = \"https://api.search.brave.com/res/v1/llm/context\"\n\ninterface BraveSourceMeta {\n title?: string\n hostname?: string\n age?: string[] | null\n}\n\ninterface BraveResult {\n url: string\n title?: string\n snippets?: string[]\n}\n\ninterface BraveResponse {\n grounding?: {\n generic?: BraveResult[]\n }\n sources?: Record<string, BraveSourceMeta>\n}\n\n// oxlint-disable-next-line sort-keys -- semantic field order: name, desc, params, call\nexport const searchTool = defineTool({\n name: \"search\",\n desc:\n \"Web search optimised for agents. Returns extracted snippets from each \" +\n \"source page (not just titles + URLs), so you get grounding content in \" +\n \"one call. Use for fact-finding, current events, documentation lookups, \" +\n \"and anything beyond your knowledge cutoff.\",\n parallel: true,\n // oxlint-disable-next-line sort-keys -- semantic param order\n params: Type.Object({\n query: Type.String({\n description: \"The search query. 1–400 characters, max 50 words.\",\n maxLength: 400,\n minLength: 1,\n }),\n count: Type.Optional(\n Type.Integer({\n default: 10,\n description: \"Maximum number of source URLs in the response.\",\n maximum: 50,\n minimum: 1,\n })\n ),\n freshness: Type.Optional(\n Type.Union([Type.Literal(\"pd\"), Type.Literal(\"pw\"), Type.Literal(\"pm\"), Type.Literal(\"py\")], {\n description:\n \"Restrict to recent pages. `pd` = past 24h, `pw` = past week, \" +\n \"`pm` = past month, `py` = past year. Omit for no filter.\",\n })\n ),\n country: Type.Optional(\n Type.String({\n default: \"us\",\n description: \"Two-letter country code for region-specific results.\",\n })\n ),\n }),\n\n async call(args, ctx): Promise<(MetaPart | TextPart)[]> {\n const apiKey = process.env.BRAVE_API_KEY\n if (!apiKey || apiKey === \"\") {\n throw new AiError({\n code: \"MISSING_API_KEY\",\n message:\n \"search requires BRAVE_API_KEY in the environment. Get a key at \" +\n \"https://api.search.brave.com/.\",\n })\n }\n\n const url = new URL(ENDPOINT)\n url.searchParams.set(\"q\", args.query)\n url.searchParams.set(\"count\", String(args.count ?? 10))\n url.searchParams.set(\"country\", args.country ?? \"us\")\n if (args.freshness !== undefined) url.searchParams.set(\"freshness\", args.freshness)\n\n const t0 = Date.now()\n const res = await fetch(url, {\n headers: {\n accept: \"application/json\",\n \"x-subscription-token\": apiKey,\n },\n signal: ctx.signal,\n })\n\n if (!res.ok) {\n const body = await res.text().catch(() => \"\")\n throw new AiError({\n code: \"SEARCH_FAILED\",\n data: { status: res.status, statusText: res.statusText },\n message: `Brave search failed (${res.status} ${res.statusText}): ${body.slice(0, 200)}`,\n retryable: res.status >= 500 || res.status === 429,\n })\n }\n\n const json = (await res.json()) as BraveResponse\n // console.log(json)\n const results = json.grounding?.generic ?? []\n const sources = json.sources ?? {}\n const durationMs = Date.now() - t0\n\n const parts: (MetaPart | TextPart)[] = [\n {\n data: { count: results.length, durationMs, query: args.query },\n tag: \"search\",\n type: \"meta\",\n },\n ]\n\n if (results.length === 0) {\n parts.push({ text: \"No results found.\", type: \"text\" })\n return parts\n }\n\n for (const [ri, r] of results.entries()) {\n const meta = sources[r.url] ?? {}\n const header: Record<string, unknown> = { url: r.url }\n // `age` arrives as a 3-tuple [pretty, ISO, relative]; keep the\n // ISO form (index 1) when available — most useful for the model.\n if (meta.age && meta.age.length > 0) header.age = meta.age[1] ?? meta.age[0]\n\n parts.push({ data: header, tag: \"source\", type: \"meta\" })\n\n const body = r.snippets ?? []\n // Title as a markdown H1 right after the `<source>` tag — the\n // pair reads like a document section. Snippets flow underneath.\n const title = r.title ?? meta.title\n if (title && !body[0]?.includes(title)) body.unshift(`# ${title}`)\n\n if (body.length > 0) {\n if (ri < results.length - 1) body.push(\"\")\n parts.push({ text: body.join(\"\\n\\n\"), type: \"text\" })\n }\n }\n\n return parts\n },\n})\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAsBA,MAAM,WAAW;AAsBjB,MAAa,aAAa,WAAW;CACnC,MAAM;CACN,MACE;CAIF,UAAU;CAEV,QAAQ,KAAK,OAAO;EAClB,OAAO,KAAK,OAAO;GACjB,aAAa;GACb,WAAW;GACX,WAAW;EACb,CAAC;EACD,OAAO,KAAK,SACV,KAAK,QAAQ;GACX,SAAS;GACT,aAAa;GACb,SAAS;GACT,SAAS;EACX,CAAC,CACH;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AAU,KAAK,WAAW,CAAC;EACjC,MAAM,aAAa,KAAK,IAAI,IAAI;EAEhC,MAAM,QAAiC,CACrC;GACE,MAAM;IAAE,OAAO,QAAQ;IAAQ;IAAY,OAAO,KAAK;GAAM;GAC7D,KAAK;GACL,MAAM;EACR,CACF;EAEA,IAAI,QAAQ,WAAW,GAAG;GACxB,MAAM,KAAK;IAAE,MAAM;IAAqB,MAAM;GAAO,CAAC;GACtD,OAAO;EACT;EAEA,KAAK,MAAM,CAAC,IAAI,MAAM,QAAQ,QAAQ,GAAG;GACvC,MAAM,OAAO,QAAQ,EAAE,QAAQ,CAAC;GAChC,MAAM,SAAkC,EAAE,KAAK,EAAE,IAAI;GAGrD,IAAI,KAAK,OAAO,KAAK,IAAI,SAAS,GAAG,OAAO,MAAM,KAAK,IAAI,MAAM,KAAK,IAAI;GAE1E,MAAM,KAAK;IAAE,MAAM;IAAQ,KAAK;IAAU,MAAM;GAAO,CAAC;GAExD,MAAM,OAAO,EAAE,YAAY,CAAC;GAG5B,MAAM,QAAQ,EAAE,SAAS,KAAK;GAC9B,IAAI,SAAS,CAAC,KAAK,EAAE,EAAE,SAAS,KAAK,GAAG,KAAK,QAAQ,KAAK,OAAO;GAEjE,IAAI,KAAK,SAAS,GAAG;IACnB,IAAI,KAAK,QAAQ,SAAS,GAAG,KAAK,KAAK,EAAE;IACzC,MAAM,KAAK;KAAE,MAAM,KAAK,KAAK,MAAM;KAAG,MAAM;IAAO,CAAC;GACtD;EACF;EAEA,OAAO;CACT;AACF,CAAC"}
|
|
@@ -1,5 +1,4 @@
|
|
|
1
1
|
import { Message } from "@zaly/ai";
|
|
2
|
-
//#region src/session/claude.d.ts
|
|
3
2
|
/**
|
|
4
3
|
* Read a Claude Code session file (`.jsonl` from `~/.claude/projects/...`)
|
|
5
4
|
* and return its active conversation chain as zaly `Message[]` — pass
|
|
@@ -54,5 +53,4 @@ export interface ClaudeSessionOptions {
|
|
|
54
53
|
export declare function loadClaudeSession(path: string, opts?: ClaudeSessionOptions): Promise<{
|
|
55
54
|
messages: Message[];
|
|
56
55
|
}>;
|
|
57
|
-
//#endregion
|
|
58
56
|
//# sourceMappingURL=claude.d.mts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"claude.d.mts","names":[],"sources":["../../src/session/claude.ts"],"mappings":"
|
|
1
|
+
{"version":3,"file":"claude.d.mts","names":[],"sources":["../../src/session/claude.ts"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBAsDiB;;;;;;;;;EASf;;wBAaoB,kBACpB,cACA,OAAM,uBACL;EAAU,UAAU"}
|
package/dist/session/claude.mjs
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import { t as JsonlReader } from "../jsonl-
|
|
1
|
+
import { t as JsonlReader } from "../jsonl-BGt7eqPK.mjs";
|
|
2
2
|
import { normPath } from "@zaly/shared";
|
|
3
|
-
|
|
3
|
+
// src/session/claude.ts
|
|
4
4
|
async function loadClaudeSession(path, opts = {}) {
|
|
5
5
|
path = normPath(path);
|
|
6
6
|
const convert = defaultConvertTool;
|
|
@@ -283,9 +283,8 @@ function toToolResultPart(block, toolCalls, toolUseResult) {
|
|
|
283
283
|
};
|
|
284
284
|
}
|
|
285
285
|
/** Map Claude Code's per-tool `toolUseResult` shape onto our flat
|
|
286
|
-
* `meta` schema. mtime is unknown at import time — we set 0 so
|
|
287
|
-
*
|
|
288
|
-
* mutating, rather than trusting potentially-stale bytes. */
|
|
286
|
+
* `meta` schema. mtime is unknown at import time — we set 0 so later
|
|
287
|
+
* reads won't skip content based on potentially-stale imported bytes. */
|
|
289
288
|
function toolUseResultMeta(name, result) {
|
|
290
289
|
if (result === void 0 || typeof result === "string") return void 0;
|
|
291
290
|
switch (name) {
|
|
@@ -449,7 +448,6 @@ function toAssistantPart(block, toolCalls) {
|
|
|
449
448
|
};
|
|
450
449
|
}
|
|
451
450
|
}
|
|
452
|
-
//#endregion
|
|
453
451
|
export { loadClaudeSession };
|
|
454
452
|
|
|
455
453
|
//# sourceMappingURL=claude.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"claude.mjs","names":[],"sources":["../../src/session/claude.ts"],"sourcesContent":["import type {\n Attachment,\n ImagePart,\n Message,\n ReasoningPart,\n TextPart,\n ToolCallPart,\n ToolResultPart,\n Usage,\n} from \"@zaly/ai\"\n\nimport { normPath } from \"@zaly/shared\"\nimport { JsonlReader } from \"./jsonl.ts\"\n\n/**\n * Read a Claude Code session file (`.jsonl` from `~/.claude/projects/...`)\n * and return its active conversation chain as zaly `Message[]` — pass\n * the result to `Agent.load({ messages, ... })` to seed a fresh agent\n * with the imported history.\n *\n * Claude Code stores its conversation as one JSON record per line. The\n * active chain is reconstructed by walking `parentUuid` backward from the\n * most recent on-chain user/assistant message. Non-message records\n * (`permission-mode`, `attachment`, `system`, `summary`, `file-history-\n * snapshot`, ...), sidechain branches (`isSidechain: true`), and orphan\n * lines outside the chain are skipped.\n *\n * Format mapping:\n *\n * - **User message, string content** → zaly `role: \"user\"`, content\n * passed through verbatim.\n * - **User message, array content with `tool_result` blocks** → zaly\n * `role: \"tool\"`. Anthropic's wire format puts tool results in a\n * user message; zaly splits them into a dedicated `tool` role. The\n * tool name (which Claude doesn't store on the result) is resolved\n * from the matching `tool_use` block earlier in the chain.\n * - **User message, array content with text/image blocks** → zaly\n * `role: \"user\"` with the parts converted (text passes through,\n * images become `ImagePart`).\n * - **Assistant message** → zaly `role: \"assistant\"` with each block\n * mapped: `text` → `TextPart`, `tool_use` → `ToolCallPart` (the\n * block's `input` becomes `params`). `thinking` / `redacted_thinking`\n * blocks are intentionally dropped on import — Anthropic requires\n * them to round-trip with the exact original `signature` or the next\n * request 400s, and any intermediate processing risks corrupting it.\n * The visible conversation state survives without them.\n *\n * Lossy by design — tokens, finish reasons, model swaps, and timing\n * info from Claude's records are dropped because zaly's `Session.add`\n * doesn't expose those for arbitrary imports. The returned messages\n * carry no `path` association; pass `session: { path: \"...\" }` to\n * `Agent.load` alongside them if you want to start persisting the\n * imported chain in zaly format.\n */\nexport interface ClaudeSessionOptions {\n /** Which messages to import:\n * - `\"active\"` (default) — walks `parentUuid` back from the most\n * recent on-chain message. Returns the conversation as the model\n * currently sees it: branches not on the active head are skipped,\n * pre-compact history (parented to a summary record) is dropped.\n * - `\"all\"` — every user/assistant message in the file, in\n * chronological order, regardless of branch or compaction. Useful\n * for analytics, fixtures, or recovering pre-compact context. */\n walk?: \"active\" | \"all\"\n}\n\ntype ConvertTool = (call: ClaudeToolCall) => ZalyToolCall | undefined\ninterface ClaudeToolCall {\n name: string\n input: unknown\n}\ninterface ZalyToolCall {\n name: string\n params: unknown\n}\n\nexport async function loadClaudeSession(\n path: string,\n opts: ClaudeSessionOptions = {}\n): Promise<{ messages: Message[] }> {\n // Honor `~` and relative shorthands — config-file / env paths often\n // include them and Node's fs APIs don't expand `~` natively.\n path = normPath(path)\n const convert = defaultConvertTool\n const chain = opts.walk === \"all\" ? await collectAll(path) : await walkChainLazy(path)\n const toolCalls = collectToolCalls(chain, convert)\n\n const messages: Message[] = []\n for (const rec of chain) {\n const msg = toZalyMessage(rec, toolCalls)\n if (!msg) continue\n if (msg.role === \"assistant\") {\n const usage = recordUsage(rec)\n if (usage) msg.meta = { ...msg.meta, usage }\n }\n messages.push(msg)\n }\n messages.sort((a, b) => (a.ts ?? 0) - (b.ts ?? 0))\n // De-duplicate tool_use ids. Claude Code branching / sidechain replay\n // can emit the same tool_use_id across multiple assistant messages\n // (especially with `walk: \"all\"`); downstream consumers like the\n // masker or any (id → call) lookup expect uniqueness.\n dedupCallIds(messages)\n return { messages }\n}\n\n/** Build a `Usage` from a Claude record's `message.usage` block.\n * Returns undefined when no usage info is present (user messages,\n * tool results). The caller stamps it onto `message.meta.usage`. */\nfunction recordUsage(rec: ClaudeRecord): Usage | undefined {\n const u = rec.message?.usage\n if (!u) return undefined\n const usage: Usage = {\n input: u.input_tokens ?? 0,\n output: u.output_tokens ?? 0,\n }\n if (u.cache_read_input_tokens !== undefined) usage.cacheRead = u.cache_read_input_tokens\n if (u.cache_creation_input_tokens !== undefined) usage.cacheWrite = u.cache_creation_input_tokens\n return usage\n}\n\n// ── Parsing ──────────────────────────────────────────────────────────────\n\ninterface ClaudeRecord {\n type: string\n uuid?: string\n parentUuid?: string\n isSidechain?: boolean\n /** Set on the synthetic user-role record Claude Code writes for a\n * `/compact`. The record's content is the summary text; chronologically\n * it sits where the compaction happened, with its `parentUuid` still\n * pointing into pre-compaction history. The active conversation is\n * this summary plus everything after — pre-compaction messages are\n * unreachable from the live agent. */\n isCompactSummary?: boolean\n message?: ClaudeMessage\n /** Wall-clock time the original Claude session recorded the message,\n * ISO 8601 string. Preserved onto `Message.ts` so age-based logic\n * (masker `maxAge`, freshness, replay) sees realistic timestamps\n * rather than the import time. */\n timestamp?: string\n /** Claude Code attaches structured per-tool result info here, alongside\n * the model-visible `tool_result` block. Shape varies by tool:\n * - read → `{ type: \"text\"|\"image\", file: { filePath, ... } }`\n * - write → `{ type: \"create\", filePath, content, originalFile, ... }`\n * - edit → `{ type: \"update\", filePath, content, originalFile, ... }`\n * - bash → `{ stdout, stderr, interrupted, ... }`\n * We mine this for `meta` to populate on imported `ToolResultPart`s.\n */\n toolUseResult?: ClaudeToolUseResult\n}\n\ntype ClaudeToolUseResult =\n | string\n | {\n type?: \"text\" | \"image\" | \"create\" | \"update\" | \"file_unchanged\"\n file?: {\n filePath?: string\n content?: string\n numLines?: number\n startLine?: number\n totalLines?: number\n }\n filePath?: string\n /** Set on MultiEdit / Write results — post-state file content. */\n content?: string\n /** Set on Edit results (single replacement). The post-state must\n * be derived by applying `oldString` → `newString` to\n * `originalFile`. */\n oldString?: string\n newString?: string\n replaceAll?: boolean\n originalFile?: string\n structuredPatch?: ClaudeStructuredHunk[]\n [key: string]: unknown\n }\n\ninterface ClaudeStructuredHunk {\n oldStart: number\n oldLines: number\n newStart: number\n newLines: number\n lines: string[]\n}\n\ninterface ClaudeMessage {\n role?: \"user\" | \"assistant\"\n content?: string | ClaudeBlock[]\n model?: string\n usage?: ClaudeUsage\n stop_reason?: string\n}\n\ninterface ClaudeUsage {\n input_tokens?: number\n output_tokens?: number\n cache_read_input_tokens?: number\n cache_creation_input_tokens?: number\n}\n\ntype ClaudeBlock =\n | { type: \"text\"; text: string }\n | { type: \"thinking\"; thinking: string; signature?: string }\n | { type: \"tool_use\"; id: string; name: string; input: unknown }\n | {\n type: \"tool_result\"\n tool_use_id: string\n content?: string | ClaudeBlock[]\n is_error?: boolean\n }\n | {\n type: \"image\"\n source: { type: \"base64\"; media_type: string; data: string } | { type: \"url\"; url: string }\n }\n | { type: string; [key: string]: unknown } // unknown block — falls through to a placeholder\n\n// ── Chain walk ───────────────────────────────────────────────────────────\n\n/** Walk the parentUuid chain backward from the most recent on-chain\n * user/assistant message and return the chronologically-ordered\n * conversation. Reads the file lazily (backward in chunks) — only the\n * chunks containing the active chain get pulled from disk.\n *\n * Subtlety: Claude Code interleaves non-message records (`attachment`,\n * `system`, `file-history-snapshot`, ...) into the parent chain — an\n * assistant message's `parentUuid` may point at an `attachment`, whose\n * `parentUuid` then points at the prior user message. We step *through*\n * those records (using a uuid → ANY record map), collecting only the\n * user/assistant messages we encounter. Sidechain messages are skipped.\n *\n * For long-running sessions with multiple compactions, the active chain\n * typically lives in the file's most recent chunks — so a 300MB session\n * loads from a few hundred KB rather than reading the whole file. */\nasync function walkChainLazy(path: string): Promise<ClaudeRecord[]> {\n const reader = new JsonlReader<ClaudeRecord>(path)\n const byUuid = new Map<string, ClaudeRecord>()\n try {\n // Phase 1: read backward until we find the most recent on-chain\n // (non-sidechain) user/assistant message.\n let lastOnChain: string | undefined\n let value: ClaudeRecord | undefined\n // eslint-disable-next-line no-await-in-loop\n while ((value = await reader.next()) !== undefined) {\n if (value.uuid !== undefined) byUuid.set(value.uuid, value)\n if (isMessageRecord(value) && value.isSidechain !== true) {\n lastOnChain = value.uuid\n break\n }\n }\n if (lastOnChain === undefined) return []\n\n // Phase 2: walk parentUuid backward, fetching more records lazily\n // as needed to resolve each cursor. A `summary` record is a HARD\n // boundary — Claude Code compactions create a summary node and\n // anything before it is unreachable in the live conversation, so\n // we must not walk past it (would otherwise pull pre-compaction\n // history that the model can no longer see).\n const chain: ClaudeRecord[] = []\n let cursor: string | undefined = lastOnChain\n while (cursor !== undefined) {\n let rec = byUuid.get(cursor)\n if (!rec) {\n // Pull more records from the reader until we find this uuid\n // (or run out). Records pulled along the way get cached for\n // later cursor lookups.\n // eslint-disable-next-line no-await-in-loop\n while ((value = await reader.next()) !== undefined) {\n if (value.uuid !== undefined) byUuid.set(value.uuid, value)\n if (value.uuid === cursor) {\n rec = value\n break\n }\n }\n }\n if (!rec) break\n // Compaction boundary — Claude writes the synthetic summary as a\n // user-role record flagged `isCompactSummary`. Include it (it IS\n // the visible context for the resumed conversation) and stop —\n // anything older than this is unreachable from the live agent.\n if (rec.isCompactSummary === true) {\n chain.push(rec)\n break\n }\n if (isMessageRecord(rec) && rec.isSidechain !== true) chain.push(rec)\n cursor = rec.parentUuid\n }\n return chain.toReversed()\n } finally {\n await reader.close()\n }\n}\n\nfunction isMessageRecord(rec: ClaudeRecord): boolean {\n return rec.type === \"user\" || rec.type === \"assistant\"\n}\n\n/** Every user/assistant message in file order, ignoring branches and\n * compaction boundaries. Sidechain messages are still skipped — those\n * belong to subagent loops and would scramble the main chain.\n *\n * This mode reads the entire file (necessary to find every record),\n * but uses chunked I/O via `JsonlReader` instead of slurping the\n * whole string at once. */\nasync function collectAll(path: string): Promise<ClaudeRecord[]> {\n const reader = new JsonlReader<ClaudeRecord>(path)\n const records: ClaudeRecord[] = []\n try {\n let value: ClaudeRecord | undefined\n // eslint-disable-next-line no-await-in-loop\n while ((value = await reader.next()) !== undefined) {\n if (isMessageRecord(value) && value.isSidechain !== true) records.push(value)\n }\n } finally {\n await reader.close()\n }\n // Reader yields newest-first; flip to chronological.\n return records.toReversed()\n}\n\n/** Build a `tool_use_id → { name, params }` map from the assistant\n * tool_use blocks in the chain, applying `convert` to remap names and\n * params into zaly's tool shapes. Used both to render the converted\n * `tool-call` parts on the assistant side and to fill in the (missing)\n * `name` on Claude `tool_result` blocks at result-conversion time. */\nfunction collectToolCalls(\n chain: readonly ClaudeRecord[],\n convert: ConvertTool\n): Map<string, ZalyToolCall> {\n const out = new Map<string, ZalyToolCall>()\n for (const rec of chain) {\n if (rec.type !== \"assistant\") continue\n const content = rec.message?.content\n if (!Array.isArray(content)) continue\n for (const block of content) {\n if (\n block.type === \"tool_use\" &&\n typeof block.id === \"string\" &&\n typeof block.name === \"string\"\n ) {\n const claude = { input: block.input, name: block.name }\n const zaly = convert(claude) ?? { name: block.name, params: block.input }\n out.set(block.id, zaly)\n }\n }\n }\n return out\n}\n\n/** Default `convertTool` mapping. Handles the standard Claude Code\n * toolbox; everything else falls through to a lowercased name with\n * params untouched. Composable: custom converters can call this for\n * unhandled cases. */\nfunction defaultConvertTool(call: ClaudeToolCall): ZalyToolCall {\n const input = (call.input ?? {}) as Record<string, unknown>\n switch (call.name) {\n case \"Read\": {\n return { name: \"read\", params: renameKey(input, \"file_path\", \"path\") }\n }\n case \"Write\": {\n return { name: \"write\", params: renameKey(input, \"file_path\", \"path\") }\n }\n case \"Edit\": {\n const { file_path, old_string, new_string, replace_all, ...rest } = input\n return {\n name: \"edit\",\n params: {\n edits: [{ newText: new_string, oldText: old_string, replaceAll: replace_all }],\n path: file_path,\n ...rest,\n },\n }\n }\n case \"MultiEdit\": {\n const { file_path, edits, ...rest } = input\n const mapped = Array.isArray(edits)\n ? edits.map((e: Record<string, unknown>) => ({\n newText: e.new_string,\n oldText: e.old_string,\n replaceAll: e.replace_all,\n }))\n : []\n return { name: \"edit\", params: { edits: mapped, path: file_path, ...rest } }\n }\n case \"Bash\": {\n return { name: \"bash\", params: input }\n }\n default: {\n return { name: call.name.toLowerCase(), params: input }\n }\n }\n}\n\nfunction renameKey(\n obj: Record<string, unknown>,\n from: string,\n to: string\n): Record<string, unknown> {\n if (!(from in obj)) return obj\n const { [from]: value, ...rest } = obj\n return { [to]: value, ...rest }\n}\n\n/** Walk messages in chronological order; when a tool-call id reappears,\n * rename the duplicate (and the corresponding tool-result) to a fresh\n * id. Pairs are matched FIFO per-id: each duplicate call's pending\n * rename gets consumed by the next tool-result with that original id.\n * Mutates the message parts in place. */\nfunction dedupCallIds(messages: readonly Message[]): void {\n const seen = new Set<string>()\n // Per-id queue of renames awaiting their tool-result.\n const pending = new Map<string, string[]>()\n let counter = 0\n for (const m of messages) {\n if (m.role === \"assistant\" && Array.isArray(m.content)) {\n for (const p of m.content) {\n if (p.type !== \"tool-call\") continue\n if (!seen.has(p.id)) {\n seen.add(p.id)\n continue\n }\n const newId = `${p.id}-${++counter}`\n const list = pending.get(p.id) ?? []\n list.push(newId)\n pending.set(p.id, list)\n p.id = newId\n }\n } else if (m.role === \"tool\") {\n for (const p of m.content) {\n const origId = p.id\n const list = pending.get(origId)\n if (!list || list.length === 0) continue\n p.id = list.shift()!\n if (list.length === 0) pending.delete(origId)\n }\n }\n }\n}\n\n// ── Conversion ───────────────────────────────────────────────────────────\n\nfunction toZalyMessage(\n rec: ClaudeRecord,\n toolCalls: Map<string, ZalyToolCall>\n): Message | undefined {\n const inner = rec.message\n if (!inner) return undefined\n\n let m: Message | undefined\n if (rec.type === \"user\") m = toUserMessage(inner, toolCalls, rec.toolUseResult)\n else if (rec.type === \"assistant\") m = toAssistantMessage(inner, toolCalls)\n if (!m) return undefined\n\n // Preserve the original Claude timestamp so age-based logic (masker\n // `maxAge`, freshness checks, replay) sees realistic times instead\n // of when the import ran.\n if (rec.timestamp) {\n const ts = Date.parse(rec.timestamp)\n if (!Number.isNaN(ts)) m = { ...m, ts }\n }\n // Carry the record's uuid as the message id so the imported message\n // can be referenced by the session DAG (and so per-message meta lifted\n // off the same record can be looked up back here).\n if (rec.uuid) m = { ...m, id: rec.uuid }\n return m\n}\n\nfunction toUserMessage(\n inner: ClaudeMessage,\n toolCalls: Map<string, ZalyToolCall>,\n toolUseResult: ClaudeToolUseResult | undefined\n): Message | undefined {\n const content = inner.content\n if (typeof content === \"string\") {\n return { content, role: \"user\" }\n }\n if (!Array.isArray(content) || content.length === 0) return undefined\n\n // If every block is a tool_result, this is a zaly tool message.\n if (content.every((b) => b.type === \"tool_result\")) {\n const parts = content\n .map((b) =>\n toToolResultPart(\n b as Extract<ClaudeBlock, { type: \"tool_result\" }>,\n toolCalls,\n toolUseResult\n )\n )\n .filter((p): p is ToolResultPart => p !== undefined)\n if (parts.length === 0) return undefined\n return { content: parts, role: \"tool\" }\n }\n\n // Otherwise treat as a user message with text / image parts. Mixed\n // arrays carrying a tool_result alongside text are rare; we drop the\n // tool_result here (it would belong on its own message) and keep the\n // visible content.\n const parts = content\n .map((b) => toUserPart(b))\n .filter((p): p is TextPart | Attachment => p !== undefined)\n if (parts.length === 0) return undefined\n return { content: parts, role: \"user\" }\n}\n\nfunction toToolResultPart(\n block: Extract<ClaudeBlock, { type: \"tool_result\" }>,\n toolCalls: Map<string, ZalyToolCall>,\n toolUseResult: ClaudeToolUseResult | undefined\n): ToolResultPart | undefined {\n if (typeof block.tool_use_id !== \"string\") return undefined\n const name = toolCalls.get(block.tool_use_id)?.name ?? \"\"\n const meta = toolUseResultMeta(name, toolUseResult)\n return {\n content: toToolResultContent(block.content),\n id: block.tool_use_id,\n isError: block.is_error === true,\n name,\n type: \"tool-result\",\n ...(meta !== undefined ? { meta } : {}),\n }\n}\n\n/** Map Claude Code's per-tool `toolUseResult` shape onto our flat\n * `meta` schema. mtime is unknown at import time — we set 0 so any\n * later `assertFresh` check forces the agent to re-read before\n * mutating, rather than trusting potentially-stale bytes. */\nfunction toolUseResultMeta(\n name: string,\n result: ClaudeToolUseResult | undefined\n): Record<string, unknown> | undefined {\n if (result === undefined || typeof result === \"string\") return undefined\n switch (name) {\n case \"read\": {\n const file = result.file\n if (!file?.filePath) return undefined\n return {\n full: file.totalLines !== undefined && file.numLines === file.totalLines,\n kind: \"read\",\n limit: file.numLines,\n mtime: 0,\n offset: file.startLine,\n path: file.filePath,\n }\n }\n case \"write\": {\n if (!result.filePath) return undefined\n // Post-write content lives on the original tool call's\n // `params.content`; we only stash `original` (pre-write).\n return {\n full: true,\n kind: \"write\",\n mtime: 0,\n original: result.originalFile,\n path: result.filePath,\n }\n }\n case \"edit\": {\n if (!result.filePath) return undefined\n // Several Claude Code shapes to handle:\n // 1. MultiEdit / older Edit: `content` (post-state) is provided\n // directly alongside `originalFile` (pre-state).\n // 2. Single Edit with full pre-state: `oldString`/`newString`\n // swap on top of a populated `originalFile`. Derive content\n // by applying the swap.\n // 3. Single Edit without pre-state but with `structuredPatch`:\n // reconstruct synthetic pre/post strings from the patch hunks\n // (Claude Code's UI does the same trick — the patch carries\n // context + line numbers). The diff widget then renders with\n // the real file line numbers in the gutter.\n // 4. None of the above: fall back to showing just the swap.\n const originalFile =\n typeof result.originalFile === \"string\" && result.originalFile.length > 0\n ? result.originalFile\n : undefined\n let original = originalFile ?? \"\"\n let content = \"\"\n\n if (typeof result.content === \"string\") {\n content = result.content\n } else if (typeof result.oldString === \"string\" && typeof result.newString === \"string\") {\n const { newString, oldString } = result\n const applied = applyClaudeEdit(originalFile, oldString, newString, result.replaceAll)\n if (applied !== undefined) {\n content = applied\n } else {\n const synth = synthesizeFromStructuredPatch(result.structuredPatch)\n if (synth !== undefined) {\n original = synth.original\n content = synth.modified\n } else {\n original = oldString\n content = newString\n }\n }\n }\n return { content, kind: \"edit\", mtime: 0, original, path: result.filePath }\n }\n default: {\n return undefined\n }\n }\n}\n\n/** Apply a Claude single-Edit swap to the pre-edit content. Returns\n * `undefined` when the edit can't be applied (no original file recorded\n * or the search string doesn't appear in it) — caller falls back to\n * showing just the swap. */\nfunction applyClaudeEdit(\n original: string | undefined,\n oldString: string,\n newString: string,\n replaceAll: boolean | undefined\n): string | undefined {\n if (original === undefined || !original.includes(oldString)) return undefined\n return replaceAll === true\n ? original.split(oldString).join(newString)\n : original.replace(oldString, newString)\n}\n\n/** Reconstruct synthetic pre/post strings from a Claude `structuredPatch`.\n * Hunks are placed at their real line numbers (`oldStart`/`newStart`)\n * with empty-line padding outside, so the diff widget's gutter shows\n * accurate file line numbers — same effect as Claude Code's UI. Lines\n * prefixed \" \"/\" -\" go to the original, \" \"/\" +\" go to modified. */\nfunction synthesizeFromStructuredPatch(\n patch: ClaudeStructuredHunk[] | undefined\n): { original: string; modified: string } | undefined {\n if (!Array.isArray(patch) || patch.length === 0) return undefined\n const origLines: string[] = []\n const modLines: string[] = []\n for (const h of patch) {\n padTo(origLines, h.oldStart)\n padTo(modLines, h.newStart)\n for (const raw of h.lines) {\n // Each entry is a unified-diff row: \" ctx\", \"-removed\", \"+added\".\n const tag = raw[0]\n const body = raw.slice(1)\n if (tag === \"-\") origLines.push(body)\n else if (tag === \"+\") modLines.push(body)\n else {\n origLines.push(body)\n modLines.push(body)\n }\n }\n }\n return { modified: modLines.join(\"\\n\"), original: origLines.join(\"\\n\") }\n}\n\n/** 1-based line indexing in the patch; pad with empty strings up to\n * the target line so subsequent pushes land at the right index. */\nfunction padTo(arr: string[], idx: number): void {\n while (arr.length < idx - 1) arr.push(\"\")\n}\n\n/** Tool result content: Claude allows string OR an array of text/image\n * blocks. Map both into zaly's `Content` shape. */\nfunction toToolResultContent(\n content: string | ClaudeBlock[] | undefined\n): ToolResultPart[\"content\"] {\n if (content === undefined) return \"\"\n if (typeof content === \"string\") return content\n const parts = content\n .map((b) => toUserPart(b))\n .filter((p): p is TextPart | Attachment => p !== undefined)\n return parts.length > 0 ? parts : \"\"\n}\n\nfunction toUserPart(block: ClaudeBlock): TextPart | Attachment | undefined {\n if (block.type === \"text\" && typeof block.text === \"string\") {\n return { text: block.text, type: \"text\" }\n }\n if (block.type === \"image\") {\n return toImagePart(block as Extract<ClaudeBlock, { type: \"image\" }>)\n }\n return undefined\n}\n\nfunction toImagePart(block: Extract<ClaudeBlock, { type: \"image\" }>): ImagePart | undefined {\n const src = block.source\n if (src.type === \"base64\") {\n const mime = src.media_type\n if (mime !== \"image/png\" && mime !== \"image/jpeg\" && mime !== \"image/webp\") return undefined\n return { mime, source: { data: src.data, type: \"base64\" }, type: \"image\" }\n }\n // url-source images: zaly's ImagePart only types png/jpeg/webp mimes,\n // and we don't know the mime from a bare URL here. Skip — the model\n // already saw it in the original Claude session; losing it on import\n // is less bad than fabricating a wrong mime.\n return undefined\n}\n\nfunction toAssistantMessage(\n inner: ClaudeMessage,\n toolCalls: Map<string, ZalyToolCall>\n): Message | undefined {\n const content = inner.content\n if (typeof content === \"string\") {\n return { content, role: \"assistant\" }\n }\n if (!Array.isArray(content)) return undefined\n\n const parts: (TextPart | ReasoningPart | ToolCallPart)[] = []\n for (const block of content) {\n const part = toAssistantPart(block, toolCalls)\n if (part) parts.push(part)\n }\n if (parts.length === 0) return undefined\n return { content: parts, role: \"assistant\" }\n}\n\nfunction toAssistantPart(\n block: ClaudeBlock,\n toolCalls: Map<string, ZalyToolCall>\n): TextPart | ReasoningPart | ToolCallPart | undefined {\n if (block.type === \"text\" && typeof block.text === \"string\") {\n return { text: block.text, type: \"text\" }\n }\n // Reasoning / thinking blocks are intentionally dropped on import.\n // Anthropic requires them to round-trip with the exact original\n // `signature`, and any intermediate processing (truncation, reorder,\n // even just a different request shape) trips a 400 in the next turn.\n // The visible text and tool calls carry the conversation's effective\n // state; thinking is recoverable from re-running, so dropping it is\n // strictly safer than risking signature mismatch errors.\n if (block.type === \"tool_use\" && typeof block.id === \"string\" && typeof block.name === \"string\") {\n const call = toolCalls.get(block.id) ?? { name: block.name, params: block.input }\n return { id: block.id, name: call.name, params: call.params, type: \"tool-call\" }\n }\n return undefined\n}\n"],"mappings":";;;AA4EA,eAAsB,kBACpB,MACA,OAA6B,CAAC,GACI;CAGlC,OAAO,SAAS,IAAI;CACpB,MAAM,UAAU;CAChB,MAAM,QAAQ,KAAK,SAAS,QAAQ,MAAM,WAAW,IAAI,IAAI,MAAM,cAAc,IAAI;CACrF,MAAM,YAAY,iBAAiB,OA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AAQ;CAC3E;AAMF;AAEA,SAAS,mBACP,OACA,WACqB;CACrB,MAAM,UAAU,MAAM;CACtB,IAAI,OAAO,YAAY,UACrB,OAAO;EAAE;EAAS,MAAM;CAAY;CAEtC,IAAI,CAAC,MAAM,QAAQ,OAAO,GAAG,OAAO,KAAA;CAEpC,MAAM,QAAqD,CAAC;CAC5D,KAAK,MAAM,SAAS,SAAS;EAC3B,MAAM,OAAO,gBAAgB,OAAO,SAAS;EAC7C,IAAI,MAAM,MAAM,KAAK,IAAI;CAC3B;CACA,IAAI,MAAM,WAAW,GAAG,OAAO,KAAA;CAC/B,OAAO;EAAE,SAAS;EAAO,MAAM;CAAY;AAC7C;AAEA,SAAS,gBACP,OACA,WACqD;CACrD,IAAI,MAAM,SAAS,UAAU,OAAO,MAAM,SAAS,UACjD,OAAO;EAAE,MAAM,MAAM;EAAM,MAAM;CAAO;CAS1C,IAAI,MAAM,SAAS,cAAc,OAAO,MAAM,OAAO,YAAY,OAAO,MAAM,SAAS,UAAU;EAC/F,MAAM,OAAO,UAAU,IAAI,MAAM,EAAE,KAAK;GAAE,MAAM,MAAM;GAAM,QAAQ,MAAM;EAAM;EAChF,OAAO;GAAE,IAAI,MAAM;GAAI,MAAM,KAAK;GAAM,QAAQ,KAAK;GAAQ,MAAM;EAAY;CACjF;AAEF"}
|
|
1
|
+
{"version":3,"file":"claude.mjs","names":[],"sources":["../../src/session/claude.ts"],"sourcesContent":["import type {\n Attachment,\n ImagePart,\n Message,\n ReasoningPart,\n TextPart,\n ToolCallPart,\n ToolResultPart,\n Usage,\n} from \"@zaly/ai\"\n\nimport { normPath } from \"@zaly/shared\"\nimport { JsonlReader } from \"./jsonl.ts\"\n\n/**\n * Read a Claude Code session file (`.jsonl` from `~/.claude/projects/...`)\n * and return its active conversation chain as zaly `Message[]` — pass\n * the result to `Agent.load({ messages, ... })` to seed a fresh agent\n * with the imported history.\n *\n * Claude Code stores its conversation as one JSON record per line. The\n * active chain is reconstructed by walking `parentUuid` backward from the\n * most recent on-chain user/assistant message. Non-message records\n * (`permission-mode`, `attachment`, `system`, `summary`, `file-history-\n * snapshot`, ...), sidechain branches (`isSidechain: true`), and orphan\n * lines outside the chain are skipped.\n *\n * Format mapping:\n *\n * - **User message, string content** → zaly `role: \"user\"`, content\n * passed through verbatim.\n * - **User message, array content with `tool_result` blocks** → zaly\n * `role: \"tool\"`. Anthropic's wire format puts tool results in a\n * user message; zaly splits them into a dedicated `tool` role. The\n * tool name (which Claude doesn't store on the result) is resolved\n * from the matching `tool_use` block earlier in the chain.\n * - **User message, array content with text/image blocks** → zaly\n * `role: \"user\"` with the parts converted (text passes through,\n * images become `ImagePart`).\n * - **Assistant message** → zaly `role: \"assistant\"` with each block\n * mapped: `text` → `TextPart`, `tool_use` → `ToolCallPart` (the\n * block's `input` becomes `params`). `thinking` / `redacted_thinking`\n * blocks are intentionally dropped on import — Anthropic requires\n * them to round-trip with the exact original `signature` or the next\n * request 400s, and any intermediate processing risks corrupting it.\n * The visible conversation state survives without them.\n *\n * Lossy by design — tokens, finish reasons, model swaps, and timing\n * info from Claude's records are dropped because zaly's `Session.add`\n * doesn't expose those for arbitrary imports. The returned messages\n * carry no `path` association; pass `session: { path: \"...\" }` to\n * `Agent.load` alongside them if you want to start persisting the\n * imported chain in zaly format.\n */\nexport interface ClaudeSessionOptions {\n /** Which messages to import:\n * - `\"active\"` (default) — walks `parentUuid` back from the most\n * recent on-chain message. Returns the conversation as the model\n * currently sees it: branches not on the active head are skipped,\n * pre-compact history (parented to a summary record) is dropped.\n * - `\"all\"` — every user/assistant message in the file, in\n * chronological order, regardless of branch or compaction. Useful\n * for analytics, fixtures, or recovering pre-compact context. */\n walk?: \"active\" | \"all\"\n}\n\ntype ConvertTool = (call: ClaudeToolCall) => ZalyToolCall | undefined\ninterface ClaudeToolCall {\n name: string\n input: unknown\n}\ninterface ZalyToolCall {\n name: string\n params: unknown\n}\n\nexport async function loadClaudeSession(\n path: string,\n opts: ClaudeSessionOptions = {}\n): Promise<{ messages: Message[] }> {\n // Honor `~` and relative shorthands — config-file / env paths often\n // include them and Node's fs APIs don't expand `~` natively.\n path = normPath(path)\n const convert = defaultConvertTool\n const chain = opts.walk === \"all\" ? await collectAll(path) : await walkChainLazy(path)\n const toolCalls = collectToolCalls(chain, convert)\n\n const messages: Message[] = []\n for (const rec of chain) {\n const msg = toZalyMessage(rec, toolCalls)\n if (!msg) continue\n if (msg.role === \"assistant\") {\n const usage = recordUsage(rec)\n if (usage) msg.meta = { ...msg.meta, usage }\n }\n messages.push(msg)\n }\n messages.sort((a, b) => (a.ts ?? 0) - (b.ts ?? 0))\n // De-duplicate tool_use ids. Claude Code branching / sidechain replay\n // can emit the same tool_use_id across multiple assistant messages\n // (especially with `walk: \"all\"`); downstream consumers like the\n // masker or any (id → call) lookup expect uniqueness.\n dedupCallIds(messages)\n return { messages }\n}\n\n/** Build a `Usage` from a Claude record's `message.usage` block.\n * Returns undefined when no usage info is present (user messages,\n * tool results). The caller stamps it onto `message.meta.usage`. */\nfunction recordUsage(rec: ClaudeRecord): Usage | undefined {\n const u = rec.message?.usage\n if (!u) return undefined\n const usage: Usage = {\n input: u.input_tokens ?? 0,\n output: u.output_tokens ?? 0,\n }\n if (u.cache_read_input_tokens !== undefined) usage.cacheRead = u.cache_read_input_tokens\n if (u.cache_creation_input_tokens !== undefined) usage.cacheWrite = u.cache_creation_input_tokens\n return usage\n}\n\n// ── Parsing ──────────────────────────────────────────────────────────────\n\ninterface ClaudeRecord {\n type: string\n uuid?: string\n parentUuid?: string\n isSidechain?: boolean\n /** Set on the synthetic user-role record Claude Code writes for a\n * `/compact`. The record's content is the summary text; chronologically\n * it sits where the compaction happened, with its `parentUuid` still\n * pointing into pre-compaction history. The active conversation is\n * this summary plus everything after — pre-compaction messages are\n * unreachable from the live agent. */\n isCompactSummary?: boolean\n message?: ClaudeMessage\n /** Wall-clock time the original Claude session recorded the message,\n * ISO 8601 string. Preserved onto `Message.ts` so age-based logic\n * (masker `maxAge`, freshness, replay) sees realistic timestamps\n * rather than the import time. */\n timestamp?: string\n /** Claude Code attaches structured per-tool result info here, alongside\n * the model-visible `tool_result` block. Shape varies by tool:\n * - read → `{ type: \"text\"|\"image\", file: { filePath, ... } }`\n * - write → `{ type: \"create\", filePath, content, originalFile, ... }`\n * - edit → `{ type: \"update\", filePath, content, originalFile, ... }`\n * - bash → `{ stdout, stderr, interrupted, ... }`\n * We mine this for `meta` to populate on imported `ToolResultPart`s.\n */\n toolUseResult?: ClaudeToolUseResult\n}\n\ntype ClaudeToolUseResult =\n | string\n | {\n type?: \"text\" | \"image\" | \"create\" | \"update\" | \"file_unchanged\"\n file?: {\n filePath?: string\n content?: string\n numLines?: number\n startLine?: number\n totalLines?: number\n }\n filePath?: string\n /** Set on MultiEdit / Write results — post-state file content. */\n content?: string\n /** Set on Edit results (single replacement). The post-state must\n * be derived by applying `oldString` → `newString` to\n * `originalFile`. */\n oldString?: string\n newString?: string\n replaceAll?: boolean\n originalFile?: string\n structuredPatch?: ClaudeStructuredHunk[]\n [key: string]: unknown\n }\n\ninterface ClaudeStructuredHunk {\n oldStart: number\n oldLines: number\n newStart: number\n newLines: number\n lines: string[]\n}\n\ninterface ClaudeMessage {\n role?: \"user\" | \"assistant\"\n content?: string | ClaudeBlock[]\n model?: string\n usage?: ClaudeUsage\n stop_reason?: string\n}\n\ninterface ClaudeUsage {\n input_tokens?: number\n output_tokens?: number\n cache_read_input_tokens?: number\n cache_creation_input_tokens?: number\n}\n\ntype ClaudeBlock =\n | { type: \"text\"; text: string }\n | { type: \"thinking\"; thinking: string; signature?: string }\n | { type: \"tool_use\"; id: string; name: string; input: unknown }\n | {\n type: \"tool_result\"\n tool_use_id: string\n content?: string | ClaudeBlock[]\n is_error?: boolean\n }\n | {\n type: \"image\"\n source: { type: \"base64\"; media_type: string; data: string } | { type: \"url\"; url: string }\n }\n | { type: string; [key: string]: unknown } // unknown block — falls through to a placeholder\n\n// ── Chain walk ───────────────────────────────────────────────────────────\n\n/** Walk the parentUuid chain backward from the most recent on-chain\n * user/assistant message and return the chronologically-ordered\n * conversation. Reads the file lazily (backward in chunks) — only the\n * chunks containing the active chain get pulled from disk.\n *\n * Subtlety: Claude Code interleaves non-message records (`attachment`,\n * `system`, `file-history-snapshot`, ...) into the parent chain — an\n * assistant message's `parentUuid` may point at an `attachment`, whose\n * `parentUuid` then points at the prior user message. We step *through*\n * those records (using a uuid → ANY record map), collecting only the\n * user/assistant messages we encounter. Sidechain messages are skipped.\n *\n * For long-running sessions with multiple compactions, the active chain\n * typically lives in the file's most recent chunks — so a 300MB session\n * loads from a few hundred KB rather than reading the whole file. */\nasync function walkChainLazy(path: string): Promise<ClaudeRecord[]> {\n const reader = new JsonlReader<ClaudeRecord>(path)\n const byUuid = new Map<string, ClaudeRecord>()\n try {\n // Phase 1: read backward until we find the most recent on-chain\n // (non-sidechain) user/assistant message.\n let lastOnChain: string | undefined\n let value: ClaudeRecord | undefined\n // eslint-disable-next-line no-await-in-loop\n while ((value = await reader.next()) !== undefined) {\n if (value.uuid !== undefined) byUuid.set(value.uuid, value)\n if (isMessageRecord(value) && value.isSidechain !== true) {\n lastOnChain = value.uuid\n break\n }\n }\n if (lastOnChain === undefined) return []\n\n // Phase 2: walk parentUuid backward, fetching more records lazily\n // as needed to resolve each cursor. A `summary` record is a HARD\n // boundary — Claude Code compactions create a summary node and\n // anything before it is unreachable in the live conversation, so\n // we must not walk past it (would otherwise pull pre-compaction\n // history that the model can no longer see).\n const chain: ClaudeRecord[] = []\n let cursor: string | undefined = lastOnChain\n while (cursor !== undefined) {\n let rec = byUuid.get(cursor)\n if (!rec) {\n // Pull more records from the reader until we find this uuid\n // (or run out). Records pulled along the way get cached for\n // later cursor lookups.\n // eslint-disable-next-line no-await-in-loop\n while ((value = await reader.next()) !== undefined) {\n if (value.uuid !== undefined) byUuid.set(value.uuid, value)\n if (value.uuid === cursor) {\n rec = value\n break\n }\n }\n }\n if (!rec) break\n // Compaction boundary — Claude writes the synthetic summary as a\n // user-role record flagged `isCompactSummary`. Include it (it IS\n // the visible context for the resumed conversation) and stop —\n // anything older than this is unreachable from the live agent.\n if (rec.isCompactSummary === true) {\n chain.push(rec)\n break\n }\n if (isMessageRecord(rec) && rec.isSidechain !== true) chain.push(rec)\n cursor = rec.parentUuid\n }\n return chain.toReversed()\n } finally {\n await reader.close()\n }\n}\n\nfunction isMessageRecord(rec: ClaudeRecord): boolean {\n return rec.type === \"user\" || rec.type === \"assistant\"\n}\n\n/** Every user/assistant message in file order, ignoring branches and\n * compaction boundaries. Sidechain messages are still skipped — those\n * belong to subagent loops and would scramble the main chain.\n *\n * This mode reads the entire file (necessary to find every record),\n * but uses chunked I/O via `JsonlReader` instead of slurping the\n * whole string at once. */\nasync function collectAll(path: string): Promise<ClaudeRecord[]> {\n const reader = new JsonlReader<ClaudeRecord>(path)\n const records: ClaudeRecord[] = []\n try {\n let value: ClaudeRecord | undefined\n // eslint-disable-next-line no-await-in-loop\n while ((value = await reader.next()) !== undefined) {\n if (isMessageRecord(value) && value.isSidechain !== true) records.push(value)\n }\n } finally {\n await reader.close()\n }\n // Reader yields newest-first; flip to chronological.\n return records.toReversed()\n}\n\n/** Build a `tool_use_id → { name, params }` map from the assistant\n * tool_use blocks in the chain, applying `convert` to remap names and\n * params into zaly's tool shapes. Used both to render the converted\n * `tool-call` parts on the assistant side and to fill in the (missing)\n * `name` on Claude `tool_result` blocks at result-conversion time. */\nfunction collectToolCalls(\n chain: readonly ClaudeRecord[],\n convert: ConvertTool\n): Map<string, ZalyToolCall> {\n const out = new Map<string, ZalyToolCall>()\n for (const rec of chain) {\n if (rec.type !== \"assistant\") continue\n const content = rec.message?.content\n if (!Array.isArray(content)) continue\n for (const block of content) {\n if (\n block.type === \"tool_use\" &&\n typeof block.id === \"string\" &&\n typeof block.name === \"string\"\n ) {\n const claude = { input: block.input, name: block.name }\n const zaly = convert(claude) ?? { name: block.name, params: block.input }\n out.set(block.id, zaly)\n }\n }\n }\n return out\n}\n\n/** Default `convertTool` mapping. Handles the standard Claude Code\n * toolbox; everything else falls through to a lowercased name with\n * params untouched. Composable: custom converters can call this for\n * unhandled cases. */\nfunction defaultConvertTool(call: ClaudeToolCall): ZalyToolCall {\n const input = (call.input ?? {}) as Record<string, unknown>\n switch (call.name) {\n case \"Read\": {\n return { name: \"read\", params: renameKey(input, \"file_path\", \"path\") }\n }\n case \"Write\": {\n return { name: \"write\", params: renameKey(input, \"file_path\", \"path\") }\n }\n case \"Edit\": {\n const { file_path, old_string, new_string, replace_all, ...rest } = input\n return {\n name: \"edit\",\n params: {\n edits: [{ newText: new_string, oldText: old_string, replaceAll: replace_all }],\n path: file_path,\n ...rest,\n },\n }\n }\n case \"MultiEdit\": {\n const { file_path, edits, ...rest } = input\n const mapped = Array.isArray(edits)\n ? edits.map((e: Record<string, unknown>) => ({\n newText: e.new_string,\n oldText: e.old_string,\n replaceAll: e.replace_all,\n }))\n : []\n return { name: \"edit\", params: { edits: mapped, path: file_path, ...rest } }\n }\n case \"Bash\": {\n return { name: \"bash\", params: input }\n }\n default: {\n return { name: call.name.toLowerCase(), params: input }\n }\n }\n}\n\nfunction renameKey(\n obj: Record<string, unknown>,\n from: string,\n to: string\n): Record<string, unknown> {\n if (!(from in obj)) return obj\n const { [from]: value, ...rest } = obj\n return { [to]: value, ...rest }\n}\n\n/** Walk messages in chronological order; when a tool-call id reappears,\n * rename the duplicate (and the corresponding tool-result) to a fresh\n * id. Pairs are matched FIFO per-id: each duplicate call's pending\n * rename gets consumed by the next tool-result with that original id.\n * Mutates the message parts in place. */\nfunction dedupCallIds(messages: readonly Message[]): void {\n const seen = new Set<string>()\n // Per-id queue of renames awaiting their tool-result.\n const pending = new Map<string, string[]>()\n let counter = 0\n for (const m of messages) {\n if (m.role === \"assistant\" && Array.isArray(m.content)) {\n for (const p of m.content) {\n if (p.type !== \"tool-call\") continue\n if (!seen.has(p.id)) {\n seen.add(p.id)\n continue\n }\n const newId = `${p.id}-${++counter}`\n const list = pending.get(p.id) ?? []\n list.push(newId)\n pending.set(p.id, list)\n p.id = newId\n }\n } else if (m.role === \"tool\") {\n for (const p of m.content) {\n const origId = p.id\n const list = pending.get(origId)\n if (!list || list.length === 0) continue\n p.id = list.shift()!\n if (list.length === 0) pending.delete(origId)\n }\n }\n }\n}\n\n// ── Conversion ───────────────────────────────────────────────────────────\n\nfunction toZalyMessage(\n rec: ClaudeRecord,\n toolCalls: Map<string, ZalyToolCall>\n): Message | undefined {\n const inner = rec.message\n if (!inner) return undefined\n\n let m: Message | undefined\n if (rec.type === \"user\") m = toUserMessage(inner, toolCalls, rec.toolUseResult)\n else if (rec.type === \"assistant\") m = toAssistantMessage(inner, toolCalls)\n if (!m) return undefined\n\n // Preserve the original Claude timestamp so age-based logic (masker\n // `maxAge`, freshness checks, replay) sees realistic times instead\n // of when the import ran.\n if (rec.timestamp) {\n const ts = Date.parse(rec.timestamp)\n if (!Number.isNaN(ts)) m = { ...m, ts }\n }\n // Carry the record's uuid as the message id so the imported message\n // can be referenced by the session DAG (and so per-message meta lifted\n // off the same record can be looked up back here).\n if (rec.uuid) m = { ...m, id: rec.uuid }\n return m\n}\n\nfunction toUserMessage(\n inner: ClaudeMessage,\n toolCalls: Map<string, ZalyToolCall>,\n toolUseResult: ClaudeToolUseResult | undefined\n): Message | undefined {\n const content = inner.content\n if (typeof content === \"string\") {\n return { content, role: \"user\" }\n }\n if (!Array.isArray(content) || content.length === 0) return undefined\n\n // If every block is a tool_result, this is a zaly tool message.\n if (content.every((b) => b.type === \"tool_result\")) {\n const parts = content\n .map((b) =>\n toToolResultPart(\n b as Extract<ClaudeBlock, { type: \"tool_result\" }>,\n toolCalls,\n toolUseResult\n )\n )\n .filter((p): p is ToolResultPart => p !== undefined)\n if (parts.length === 0) return undefined\n return { content: parts, role: \"tool\" }\n }\n\n // Otherwise treat as a user message with text / image parts. Mixed\n // arrays carrying a tool_result alongside text are rare; we drop the\n // tool_result here (it would belong on its own message) and keep the\n // visible content.\n const parts = content\n .map((b) => toUserPart(b))\n .filter((p): p is TextPart | Attachment => p !== undefined)\n if (parts.length === 0) return undefined\n return { content: parts, role: \"user\" }\n}\n\nfunction toToolResultPart(\n block: Extract<ClaudeBlock, { type: \"tool_result\" }>,\n toolCalls: Map<string, ZalyToolCall>,\n toolUseResult: ClaudeToolUseResult | undefined\n): ToolResultPart | undefined {\n if (typeof block.tool_use_id !== \"string\") return undefined\n const name = toolCalls.get(block.tool_use_id)?.name ?? \"\"\n const meta = toolUseResultMeta(name, toolUseResult)\n return {\n content: toToolResultContent(block.content),\n id: block.tool_use_id,\n isError: block.is_error === true,\n name,\n type: \"tool-result\",\n ...(meta !== undefined ? { meta } : {}),\n }\n}\n\n/** Map Claude Code's per-tool `toolUseResult` shape onto our flat\n * `meta` schema. mtime is unknown at import time — we set 0 so later\n * reads won't skip content based on potentially-stale imported bytes. */\nfunction toolUseResultMeta(\n name: string,\n result: ClaudeToolUseResult | undefined\n): Record<string, unknown> | undefined {\n if (result === undefined || typeof result === \"string\") return undefined\n switch (name) {\n case \"read\": {\n const file = result.file\n if (!file?.filePath) return undefined\n return {\n full: file.totalLines !== undefined && file.numLines === file.totalLines,\n kind: \"read\",\n limit: file.numLines,\n mtime: 0,\n offset: file.startLine,\n path: file.filePath,\n }\n }\n case \"write\": {\n if (!result.filePath) return undefined\n // Post-write content lives on the original tool call's\n // `params.content`; we only stash `original` (pre-write).\n return {\n full: true,\n kind: \"write\",\n mtime: 0,\n original: result.originalFile,\n path: result.filePath,\n }\n }\n case \"edit\": {\n if (!result.filePath) return undefined\n // Several Claude Code shapes to handle:\n // 1. MultiEdit / older Edit: `content` (post-state) is provided\n // directly alongside `originalFile` (pre-state).\n // 2. Single Edit with full pre-state: `oldString`/`newString`\n // swap on top of a populated `originalFile`. Derive content\n // by applying the swap.\n // 3. Single Edit without pre-state but with `structuredPatch`:\n // reconstruct synthetic pre/post strings from the patch hunks\n // (Claude Code's UI does the same trick — the patch carries\n // context + line numbers). The diff widget then renders with\n // the real file line numbers in the gutter.\n // 4. None of the above: fall back to showing just the swap.\n const originalFile =\n typeof result.originalFile === \"string\" && result.originalFile.length > 0\n ? result.originalFile\n : undefined\n let original = originalFile ?? \"\"\n let content = \"\"\n\n if (typeof result.content === \"string\") {\n content = result.content\n } else if (typeof result.oldString === \"string\" && typeof result.newString === \"string\") {\n const { newString, oldString } = result\n const applied = applyClaudeEdit(originalFile, oldString, newString, result.replaceAll)\n if (applied !== undefined) {\n content = applied\n } else {\n const synth = synthesizeFromStructuredPatch(result.structuredPatch)\n if (synth !== undefined) {\n original = synth.original\n content = synth.modified\n } else {\n original = oldString\n content = newString\n }\n }\n }\n return { content, kind: \"edit\", mtime: 0, original, path: result.filePath }\n }\n default: {\n return undefined\n }\n }\n}\n\n/** Apply a Claude single-Edit swap to the pre-edit content. Returns\n * `undefined` when the edit can't be applied (no original file recorded\n * or the search string doesn't appear in it) — caller falls back to\n * showing just the swap. */\nfunction applyClaudeEdit(\n original: string | undefined,\n oldString: string,\n newString: string,\n replaceAll: boolean | undefined\n): string | undefined {\n if (original === undefined || !original.includes(oldString)) return undefined\n return replaceAll === true\n ? original.split(oldString).join(newString)\n : original.replace(oldString, newString)\n}\n\n/** Reconstruct synthetic pre/post strings from a Claude `structuredPatch`.\n * Hunks are placed at their real line numbers (`oldStart`/`newStart`)\n * with empty-line padding outside, so the diff widget's gutter shows\n * accurate file line numbers — same effect as Claude Code's UI. Lines\n * prefixed \" \"/\" -\" go to the original, \" \"/\" +\" go to modified. */\nfunction synthesizeFromStructuredPatch(\n patch: ClaudeStructuredHunk[] | undefined\n): { original: string; modified: string } | undefined {\n if (!Array.isArray(patch) || patch.length === 0) return undefined\n const origLines: string[] = []\n const modLines: string[] = []\n for (const h of patch) {\n padTo(origLines, h.oldStart)\n padTo(modLines, h.newStart)\n for (const raw of h.lines) {\n // Each entry is a unified-diff row: \" ctx\", \"-removed\", \"+added\".\n const tag = raw[0]\n const body = raw.slice(1)\n if (tag === \"-\") origLines.push(body)\n else if (tag === \"+\") modLines.push(body)\n else {\n origLines.push(body)\n modLines.push(body)\n }\n }\n }\n return { modified: modLines.join(\"\\n\"), original: origLines.join(\"\\n\") }\n}\n\n/** 1-based line indexing in the patch; pad with empty strings up to\n * the target line so subsequent pushes land at the right index. */\nfunction padTo(arr: string[], idx: number): void {\n while (arr.length < idx - 1) arr.push(\"\")\n}\n\n/** Tool result content: Claude allows string OR an array of text/image\n * blocks. Map both into zaly's `Content` shape. */\nfunction toToolResultContent(\n content: string | ClaudeBlock[] | undefined\n): ToolResultPart[\"content\"] {\n if (content === undefined) return \"\"\n if (typeof content === \"string\") return content\n const parts = content\n .map((b) => toUserPart(b))\n .filter((p): p is TextPart | Attachment => p !== undefined)\n return parts.length > 0 ? parts : \"\"\n}\n\nfunction toUserPart(block: ClaudeBlock): TextPart | Attachment | undefined {\n if (block.type === \"text\" && typeof block.text === \"string\") {\n return { text: block.text, type: \"text\" }\n }\n if (block.type === \"image\") {\n return toImagePart(block as Extract<ClaudeBlock, { type: \"image\" }>)\n }\n return undefined\n}\n\nfunction toImagePart(block: Extract<ClaudeBlock, { type: \"image\" }>): ImagePart | undefined {\n const src = block.source\n if (src.type === \"base64\") {\n const mime = src.media_type\n if (mime !== \"image/png\" && mime !== \"image/jpeg\" && mime !== \"image/webp\") return undefined\n return { mime, source: { data: src.data, type: \"base64\" }, type: \"image\" }\n }\n // url-source images: zaly's ImagePart only types png/jpeg/webp mimes,\n // and we don't know the mime from a bare URL here. Skip — the model\n // already saw it in the original Claude session; losing it on import\n // is less bad than fabricating a wrong mime.\n return undefined\n}\n\nfunction toAssistantMessage(\n inner: ClaudeMessage,\n toolCalls: Map<string, ZalyToolCall>\n): Message | undefined {\n const content = inner.content\n if (typeof content === \"string\") {\n return { content, role: \"assistant\" }\n }\n if (!Array.isArray(content)) return undefined\n\n const parts: (TextPart | ReasoningPart | ToolCallPart)[] = []\n for (const block of content) {\n const part = toAssistantPart(block, toolCalls)\n if (part) parts.push(part)\n }\n if (parts.length === 0) return undefined\n return { content: parts, role: \"assistant\" }\n}\n\nfunction toAssistantPart(\n block: ClaudeBlock,\n toolCalls: Map<string, ZalyToolCall>\n): TextPart | ReasoningPart | ToolCallPart | undefined {\n if (block.type === \"text\" && typeof block.text === \"string\") {\n return { text: block.text, type: \"text\" }\n }\n // Reasoning / thinking blocks are intentionally dropped on import.\n // Anthropic requires them to round-trip with the exact original\n // `signature`, and any intermediate processing (truncation, reorder,\n // even just a different request shape) trips a 400 in the next turn.\n // The visible text and tool calls carry the conversation's effective\n // state; thinking is recoverable from re-running, so dropping it is\n // strictly safer than risking signature mismatch errors.\n if (block.type === \"tool_use\" && typeof block.id === \"string\" && typeof block.name === \"string\") {\n const call = toolCalls.get(block.id) ?? { name: block.name, params: block.input }\n return { id: block.id, name: call.name, params: call.params, type: \"tool-call\" }\n }\n return undefined\n}\n"],"mappings":";;;AA4EA,eAAsB,kBACpB,MACA,OAA6B,CAAC,GACI;CAGlC,OAAO,SAAS,IAAI;CACpB,MAAM,UAAU;CAChB,MAAM,QAAQ,KAAK,SAAS,QAAQ,MAAM,WAAW,IAAI,IAAI,MAAM,cAAc,IAAI;CACrF,MAAM,YAAY,iBAAiB,OAAO,OAAO;CAEjD,MAAM,WAAsB,CAAC;CAC7B,KAAK,MAAM,OAAO,OAAO;EACvB,MAAM,MAAM,cAAc,KAAK,SAAS;EACxC,IAAI,CAAC,KAAK;EACV,IAAI,IAAI,SAAS,aAAa;GAC5B,MAAM,QAAQ,YAAY,GAAG;GAC7B,IAAI,OAAO,IAAI,OAAO;IAAE,GAAG,IAAI;IAAM;GAAM;EAC7C;EACA,SAAS,KAAK,GAAG;CACnB;CACA,SAAS,MAAM,GAAG,OAAO,EAAE,MAAM,MAAM,EAAE,MAAM,EAAE;CAKjD,aAAa,QAAQ;CACrB,OAAO,EAAE,SAAS;AACpB;;;;AAKA,SAAS,YAAY,KAAsC;CACzD,MAAM,IAAI,IAAI,SAAS;CACvB,IAAI,CAAC,GAAG,OAAO,KAAA;CACf,MAAM,QAAe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AE,MAAM,MAAM;EAAM,MAAM;CAAO;CAS1C,IAAI,MAAM,SAAS,cAAc,OAAO,MAAM,OAAO,YAAY,OAAO,MAAM,SAAS,UAAU;EAC/F,MAAM,OAAO,UAAU,IAAI,MAAM,EAAE,KAAK;GAAE,MAAM,MAAM;GAAM,QAAQ,MAAM;EAAM;EAChF,OAAO;GAAE,IAAI,MAAM;GAAI,MAAM,KAAK;GAAM,QAAQ,KAAK;GAAQ,MAAM;EAAY;CACjF;AAEF"}
|
|
@@ -1,11 +1,11 @@
|
|
|
1
|
-
import { n as __exportAll } from "./rolldown-runtime-
|
|
2
|
-
import { r as uuidv7 } from "./uuid-
|
|
3
|
-
import { n as JsonlStore } from "./jsonl-
|
|
1
|
+
import { n as __exportAll } from "./rolldown-runtime-DYf_mQCB.mjs";
|
|
2
|
+
import { r as uuidv7 } from "./uuid-rfbQ9ad2.mjs";
|
|
3
|
+
import { n as JsonlStore } from "./jsonl-BGt7eqPK.mjs";
|
|
4
4
|
import { Emitter, normPath } from "@zaly/shared";
|
|
5
5
|
import { join } from "pathe";
|
|
6
6
|
import { isDeepStrictEqual } from "node:util";
|
|
7
7
|
import { zalyPaths } from "@zaly/shared/paths";
|
|
8
|
-
|
|
8
|
+
// src/session/memory.ts
|
|
9
9
|
/**
|
|
10
10
|
* In-memory `SessionStore` — a `Map<uuid, SessionNode>` plus a `root`
|
|
11
11
|
* pointer. No persistence. Construction takes optional initial nodes
|
|
@@ -35,8 +35,7 @@ var MemoryStore = class {
|
|
|
35
35
|
yield* this.#nodes.values();
|
|
36
36
|
}
|
|
37
37
|
};
|
|
38
|
-
|
|
39
|
-
//#region src/session/session.ts
|
|
38
|
+
// src/session/session.ts
|
|
40
39
|
var session_exports = /* @__PURE__ */ __exportAll({ Session: () => Session });
|
|
41
40
|
const VERSION = 2;
|
|
42
41
|
/**
|
|
@@ -444,7 +443,6 @@ var Session = class Session extends Emitter {
|
|
|
444
443
|
}
|
|
445
444
|
}
|
|
446
445
|
};
|
|
447
|
-
//#endregion
|
|
448
446
|
export { session_exports as n, MemoryStore as r, Session as t };
|
|
449
447
|
|
|
450
|
-
//# sourceMappingURL=session-
|
|
448
|
+
//# sourceMappingURL=session-C8zqqbPE.mjs.map
|