@theokit/sdk 4.49.0 → 4.51.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +17 -0
- package/dist/{agent-JA4ILE5O.cjs → agent-B2WU3JP6.cjs} +10 -9
- package/dist/{agent-JA4ILE5O.cjs.map → agent-B2WU3JP6.cjs.map} +1 -1
- package/dist/{agent-GKX5FE5K.js → agent-DI2QQHSJ.js} +9 -8
- package/dist/{agent-GKX5FE5K.js.map → agent-DI2QQHSJ.js.map} +1 -1
- package/dist/{chunk-3NLOQEJR.js → chunk-34XOCZJO.js} +5 -16
- package/dist/chunk-34XOCZJO.js.map +1 -0
- package/dist/{chunk-64TJCXY5.cjs → chunk-3G6ZDZ6L.cjs} +5 -5
- package/dist/{chunk-64TJCXY5.cjs.map → chunk-3G6ZDZ6L.cjs.map} +1 -1
- package/dist/{chunk-JO76RWCA.cjs → chunk-72HEBGWN.cjs} +4 -4
- package/dist/{chunk-JO76RWCA.cjs.map → chunk-72HEBGWN.cjs.map} +1 -1
- package/dist/{chunk-XARLSCKA.js → chunk-ACHVCIDQ.js} +11 -11
- package/dist/chunk-ACHVCIDQ.js.map +1 -0
- package/dist/{chunk-RJBHWM6D.js → chunk-E54KDYOE.js} +3 -3
- package/dist/{chunk-RJBHWM6D.js.map → chunk-E54KDYOE.js.map} +1 -1
- package/dist/{chunk-2S6B5B2A.js → chunk-E7WDXT4X.js} +3 -3
- package/dist/{chunk-2S6B5B2A.js.map → chunk-E7WDXT4X.js.map} +1 -1
- package/dist/{chunk-TSK4VVBW.cjs → chunk-F7OBYH2X.cjs} +52 -52
- package/dist/chunk-F7OBYH2X.cjs.map +1 -0
- package/dist/{chunk-6FSQ3CHQ.js → chunk-JGYYNDAZ.js} +5 -6
- package/dist/chunk-JGYYNDAZ.js.map +1 -0
- package/dist/{chunk-UU7MAO2D.cjs → chunk-OKLYRPKL.cjs} +4 -16
- package/dist/chunk-OKLYRPKL.cjs.map +1 -0
- package/dist/{chunk-EON4YTR6.js → chunk-R2A3WIJY.js} +3 -3
- package/dist/{chunk-EON4YTR6.js.map → chunk-R2A3WIJY.js.map} +1 -1
- package/dist/chunk-RIAM53CP.js +22 -0
- package/dist/chunk-RIAM53CP.js.map +1 -0
- package/dist/{chunk-GH52NOCL.cjs → chunk-RWMNTFHZ.cjs} +9 -9
- package/dist/{chunk-GH52NOCL.cjs.map → chunk-RWMNTFHZ.cjs.map} +1 -1
- package/dist/{chunk-MZQHVN7C.js → chunk-SEZJGV7C.js} +3 -3
- package/dist/{chunk-MZQHVN7C.js.map → chunk-SEZJGV7C.js.map} +1 -1
- package/dist/{chunk-FAUKVJCC.cjs → chunk-UQHIEUDY.cjs} +3 -3
- package/dist/{chunk-FAUKVJCC.cjs.map → chunk-UQHIEUDY.cjs.map} +1 -1
- package/dist/{chunk-UJ7HK7BX.js → chunk-VK7SIDYI.js} +3 -3
- package/dist/{chunk-UJ7HK7BX.js.map → chunk-VK7SIDYI.js.map} +1 -1
- package/dist/chunk-VKJ7V7EB.cjs +25 -0
- package/dist/chunk-VKJ7V7EB.cjs.map +1 -0
- package/dist/{chunk-74VVGK7P.cjs → chunk-WUUSAMFC.cjs} +5 -5
- package/dist/{chunk-74VVGK7P.cjs.map → chunk-WUUSAMFC.cjs.map} +1 -1
- package/dist/{chunk-XA3TSBAH.cjs → chunk-XABN5HY6.cjs} +4 -5
- package/dist/chunk-XABN5HY6.cjs.map +1 -0
- package/dist/{compact-session-UUCBTBCZ.cjs → compact-session-FKYCJRAK.cjs} +4 -3
- package/dist/{compact-session-UUCBTBCZ.cjs.map → compact-session-FKYCJRAK.cjs.map} +1 -1
- package/dist/{compact-session-GF2CBKXB.js → compact-session-LF4YOT5S.js} +4 -3
- package/dist/{compact-session-GF2CBKXB.js.map → compact-session-LF4YOT5S.js.map} +1 -1
- package/dist/context/index.cjs +6 -5
- package/dist/context/index.cjs.map +1 -1
- package/dist/context/index.js +3 -2
- package/dist/context/index.js.map +1 -1
- package/dist/cron.cjs +9 -8
- package/dist/cron.js +8 -7
- package/dist/eval.cjs +8 -7
- package/dist/eval.cjs.map +1 -1
- package/dist/eval.js +7 -6
- package/dist/eval.js.map +1 -1
- package/dist/filesystem/index.cjs +6 -5
- package/dist/filesystem/index.cjs.map +1 -1
- package/dist/filesystem/index.js +2 -1
- package/dist/filesystem/index.js.map +1 -1
- package/dist/{index-manager-YFFEPISE.cjs → index-manager-34ELCOAP.cjs} +6 -5
- package/dist/{index-manager-YFFEPISE.cjs.map → index-manager-34ELCOAP.cjs.map} +1 -1
- package/dist/index-manager-OMJVYS2U.js +12 -0
- package/dist/{index-manager-X5IPG2JL.js.map → index-manager-OMJVYS2U.js.map} +1 -1
- package/dist/index.cjs +183 -35
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +320 -1
- package/dist/index.d.ts +320 -1
- package/dist/index.js +152 -13
- package/dist/index.js.map +1 -1
- package/dist/{inject-session-I3HK3AHB.cjs → inject-session-J7Y6XACY.cjs} +4 -4
- package/dist/{inject-session-I3HK3AHB.cjs.map → inject-session-J7Y6XACY.cjs.map} +1 -1
- package/dist/{inject-session-NR64GB3T.js → inject-session-MWRJENH4.js} +3 -3
- package/dist/{inject-session-NR64GB3T.js.map → inject-session-MWRJENH4.js.map} +1 -1
- package/dist/internal/memory/adapters/index.cjs +2 -1
- package/dist/internal/memory/adapters/index.js +2 -1
- package/dist/internal/security/index.cjs +9 -8
- package/dist/internal/security/index.js +2 -1
- package/dist/path-safety.cjs +9 -8
- package/dist/path-safety.js +2 -1
- package/dist/skills.cjs +5 -4
- package/dist/skills.js +3 -2
- package/dist/workflow.cjs +11 -10
- package/dist/workflow.js +3 -2
- package/package.json +1 -1
- package/dist/chunk-3NLOQEJR.js.map +0 -1
- package/dist/chunk-6FSQ3CHQ.js.map +0 -1
- package/dist/chunk-TSK4VVBW.cjs.map +0 -1
- package/dist/chunk-UU7MAO2D.cjs.map +0 -1
- package/dist/chunk-XA3TSBAH.cjs.map +0 -1
- package/dist/chunk-XARLSCKA.js.map +0 -1
- package/dist/index-manager-X5IPG2JL.js +0 -11
|
@@ -1,7 +1,8 @@
|
|
|
1
|
+
import { atOrInsideRoot } from './chunk-RIAM53CP.js';
|
|
1
2
|
import { ConfigurationError } from './chunk-MRKSSN36.js';
|
|
2
3
|
import { createHash } from 'crypto';
|
|
3
4
|
import { realpathSync, lstatSync, readlinkSync } from 'fs';
|
|
4
|
-
import { resolve, dirname
|
|
5
|
+
import { resolve, dirname } from 'path';
|
|
5
6
|
|
|
6
7
|
var PathTraversalError = class extends ConfigurationError {
|
|
7
8
|
name = "PathTraversalError";
|
|
@@ -23,9 +24,7 @@ var ForbiddenPathError = class extends ConfigurationError {
|
|
|
23
24
|
}
|
|
24
25
|
};
|
|
25
26
|
function isInside(target, base) {
|
|
26
|
-
|
|
27
|
-
const prefix = base.endsWith(sep) ? base : base + sep;
|
|
28
|
-
return target.startsWith(prefix);
|
|
27
|
+
return atOrInsideRoot(target, base);
|
|
29
28
|
}
|
|
30
29
|
function safePathJoin(base, ...parts) {
|
|
31
30
|
if (base === "") {
|
|
@@ -210,5 +209,5 @@ function safeFilenameForId(id, options) {
|
|
|
210
209
|
}
|
|
211
210
|
|
|
212
211
|
export { ForbiddenPathError, PathTraversalError, assertNoSymlinkEscape, isForbiddenPath, safeFilenameForId, safePathJoin, sanitizeIdentifier, validateArtifactPath };
|
|
213
|
-
//# sourceMappingURL=chunk-
|
|
214
|
-
//# sourceMappingURL=chunk-
|
|
212
|
+
//# sourceMappingURL=chunk-JGYYNDAZ.js.map
|
|
213
|
+
//# sourceMappingURL=chunk-JGYYNDAZ.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/internal/security/path-guard.ts"],"names":[],"mappings":";;;;;;AAiCO,IAAM,kBAAA,GAAN,cAAiC,kBAAA,CAAmB;AAAA,EACvC,IAAA,GAAe,oBAAA;AAAA,EAEjC,WAAA,CAAY,OAAe,YAAA,E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AO,MAAM,WAAA,EAAY;AAC3B;AAyBO,SAAS,iBAAA,CAAkB,IAAY,OAAA,EAAuC;AACnF,EAAA,IAAI,EAAA,CAAG,WAAW,CAAA,EAAG;AACnB,IAAA,MAAM,IAAI,mBAAmB,wCAAA,EAA0C;AAAA,MACrE,IAAA,EAAM;AAAA,KACP,CAAA;AAAA,EACH;AACA,EAAA,MAAM,MAAA,GAAS,SAAS,MAAA,IAAU,GAAA;AAClC,EAAA,MAAM,KAAA,GAAQ,GAAG,WAAA,EAAY;AAC7B,EAAA,IAAI,MAAM,MAAA,IAAU,MAAA,IAAU,kBAAA,CAAmB,IAAA,CAAK,KAAK,CAAA,EAAG;AAC5D,IAAA,OAAO,KAAA;AAAA,EACT;AACA,EAAA,OAAO,CAAA,EAAA,EAAK,UAAA,CAAW,QAAQ,CAAA,CAAE,MAAA,CAAO,EAAE,CAAA,CAAE,MAAA,CAAO,KAAK,CAAA,CAAE,KAAA,CAAM,CAAA,EAAG,EAAE,CAAC,CAAA,CAAA;AACxE","file":"chunk-JGYYNDAZ.js","sourcesContent":["/**\n * Canonical path-guard module (ADRs D79-D81).\n *\n * Three primitives + one typed error:\n * - `safePathJoin(base, ...parts)` — resolve THEN prefix-check (ADR D80).\n * - `assertNoSymlinkEscape(path, base)` — `realpathSync` resolves entire\n * symlink chain (EC-1 fix; Hermes v0.2 #386, #61).\n * - `sanitizeIdentifier(input, { maxLen })` — strict grammar\n * `^[a-z0-9][a-z0-9-_]*$` (ADR D81; case-insensitive on input,\n * lowercase on output).\n * - `PathTraversalError` — extends ConfigurationError with code\n * `path_traversal` (ADR D65: no new hierarchy).\n *\n * Wire at all sites where user input becomes a path. CI lint gate\n * `tests/lint/no-unguarded-path-input.test.ts` prevents regression\n * (ADR D85).\n *\n * @internal\n */\n\nimport { createHash } from \"node:crypto\";\nimport { lstatSync, readlinkSync, realpathSync, type Stats } from \"node:fs\";\nimport { dirname, resolve } from \"node:path\";\n\nimport { ConfigurationError } from \"../../errors.js\";\nimport { atOrInsideRoot } from \"../runtime/context/path-containment.js\";\n\n/**\n * Thrown when a path operation would escape its allowed base directory.\n * Extends `ConfigurationError` (no new error hierarchy per ADR D65).\n *\n * @internal\n */\nexport class PathTraversalError extends ConfigurationError {\n override readonly name: string = \"PathTraversalError\";\n\n constructor(input: string, resolvedPath: string) {\n super(`Path traversal attempt: ${input} → ${resolvedPath}`, {\n code: \"path_traversal\",\n });\n }\n}\n\n/**\n * Thrown when an agent tool is asked to read or write a sensitive path\n * that the blocklist forbids (`.env`, `.git/`, `node_modules/`, `.theo/`,\n * lock files). Distinct from `PathTraversalError` because the path is\n * lexically inside the project — it is just sensitive.\n *\n * Extends `ConfigurationError` (no new error hierarchy per ADR D65).\n *\n * @public\n */\nexport class ForbiddenPathError extends ConfigurationError {\n override readonly name: string = \"ForbiddenPathError\";\n\n constructor(path: string) {\n super(\n `Path '${path}' is in the sensitive-file blocklist (.env, .git/, node_modules/, .theo/, lock files)`,\n {\n code: \"forbidden_path\",\n },\n );\n }\n}\n\n/**\n * Is `target` the same as `base`, or strictly under it?\n *\n * The prefix must not double the separator. `resolve` strips a trailing `sep` from every base\n * EXCEPT the filesystem root, where `resolve(sep) === sep`; there `base + sep` would be `//`, which\n * no absolute path starts with, so a root base rejected EVERY path (#149). Only the root takes that\n * branch — for any other base the prefix is unchanged, so containment is not weakened.\n *\n * Both containment checks in this module go through here: they had the same defect and were fixed\n * one at a time, which is exactly how the two drifted apart in the first place.\n *\n * Both arguments MUST already be resolved absolute paths.\n */\nfunction isInside(target: string, base: string): boolean {\n // B-117 — compared after symlink resolution, via the shared rule. A prefix test judges a link by\n // its NAME: `<base>/link/x` where `link` points outside is lexically inside and physically not.\n // Measured reachable from the plugin manager and the MCP client before this was changed.\n //\n // The root itself stays allowed, which `insideRoot` alone does not answer: it returns false for\n // `target === base` (correct for its own caller, wrong here, where `safePathJoin(base)` with no\n // parts must return `base`). Kept as an explicit second clause rather than by weakening the\n // shared rule for everyone.\n return atOrInsideRoot(target, base);\n}\n\n/**\n * Join `base` with `...parts` and ensure the resolved absolute path stays\n * under `base`. Resolves FIRST, then prefix-checks (ADR D80) — prevents\n * normalized-escape bypasses like `subdir/.\\\\./bar`.\n *\n * Returns the safe absolute path. Throws `PathTraversalError` if escape.\n *\n * @internal\n */\nexport function safePathJoin(base: string, ...parts: string[]): string {\n if (base === \"\") {\n throw new Error(\"safePathJoin: base must be non-empty\");\n }\n // T5.5 — NUL byte + C0/DEL control char rejection at the boundary.\n // Apply before path resolution so a malicious input never reaches\n // `resolve` (which on some platforms behaved unexpectedly with NUL\n // and in N-API callers historically silently truncated).\n rejectNulAndControlChars(base, \"base\");\n for (const part of parts) {\n rejectNulAndControlChars(part, \"path segment\");\n }\n const baseResolved = resolve(base);\n const target = resolve(base, ...parts);\n if (!isInside(target, baseResolved)) {\n throw new PathTraversalError(parts.join(\"/\"), target);\n }\n return target;\n}\n\n/**\n * T5.5 — Reject NUL (`\\x00`) and C0/DEL control characters\n * (`\\x01-\\x1F`, `\\x7F`) in any path-shaped or identifier-shaped input.\n * Centralizes the check so every public path-guard / sanitize entrypoint\n * shares the same defense.\n *\n * Throws `PathTraversalError` (the same shape as other path-shape\n * rejections) so callers don't need to learn a new error class.\n *\n * @internal\n */\nfunction rejectNulAndControlChars(input: string, role: string): void {\n for (let i = 0; i < input.length; i++) {\n const code = input.charCodeAt(i);\n if (code === 0x00 || (code >= 0x01 && code <= 0x1f) || code === 0x7f) {\n const label = code === 0x00 ? \"<nul-byte>\" : `<control-char-0x${code.toString(16)}>`;\n throw new PathTraversalError(`${role}: ${input}`, label);\n }\n }\n}\n\n/**\n * Assert that `path` — including every directory component in the chain —\n * stays under `base` after symlink resolution. No-op when nothing on the\n * path exists yet.\n *\n * Two-bug history:\n * 1. **EC-1** (original fix, kept): a multi-level symlink chain A → B → C\n * must be resolved end-to-end. `realpathSync` does this in 1 syscall.\n * 2. **Defence-in-depth** (added v1.x): the previous implementation only\n * called `lstatSync(path)` on the terminal component. If an INTERMEDIATE\n * directory was a symlink (`base/inner-symlink → /outside`), `lstat` on\n * `base/inner-symlink/file.txt` followed the symlink and reported the\n * regular file — escape went undetected. Fix: walk up to the nearest\n * existing ancestor and `realpath` THAT, then re-attach the suffix and\n * check the result against the canonical base.\n *\n * @internal\n */\nexport function assertNoSymlinkEscape(path: string, base: string): void {\n // T5.5 — reject NUL / control chars before any FS call (a NUL byte\n // in the path used to silently truncate at the C boundary on legacy\n // libc — defense in depth even on modern Node).\n rejectNulAndControlChars(path, \"path\");\n rejectNulAndControlChars(base, \"base\");\n // Canonical base — symlinks in the base path itself are absorbed once here.\n let baseResolved: string;\n try {\n baseResolved = realpathSync(base);\n } catch {\n // base doesn't exist as a real directory yet — fall back to lexical resolve.\n baseResolved = resolve(base);\n }\n\n // Find the deepest ancestor of `path` that exists, then realpath it.\n // Anything from there onward is \"not yet on disk\" and contributes only\n // its lexical suffix. This covers three cases:\n // - path exists (regular file or symlink at any depth) → realpath the full path\n // - path doesn't exist but intermediate dir is a symlink → realpath the ancestor\n // - nothing on the path exists → no escape risk (return)\n const resolved = realpathOfDeepestExisting(path);\n if (resolved === undefined) return; // path has no existing prefix — nothing to attack\n\n if (!isInside(resolved, baseResolved)) {\n throw new PathTraversalError(`symlink ${path}`, resolved);\n }\n}\n\n/**\n * Find the deepest ancestor of `path` that exists on disk, resolve all\n * symlinks in that ancestor via `realpathSync`, and re-attach the\n * lexical suffix. Returns `undefined` when no ancestor exists.\n *\n * Handles dangling symlinks: if the terminal IS a symlink but its target\n * is missing, we still detect escape via `readlinkSync` + parent resolve.\n */\nfunction realpathOfDeepestExisting(path: string): string | undefined {\n // First try the full path — the common case.\n try {\n return realpathSync(path);\n } catch {\n // Not resolvable. Two sub-cases.\n }\n\n // Sub-case A: terminal is a dangling symlink.\n try {\n const stat: Stats = lstatSync(path);\n if (stat.isSymbolicLink()) {\n const target = readlinkSync(path);\n // Resolve target relative to the REAL parent dir, so intermediate\n // symlinks in the parent chain are absorbed.\n const parentReal = realpathOfDeepestExisting(dirname(path));\n const parentBase = parentReal ?? dirname(path);\n return resolve(parentBase, target);\n }\n } catch {\n // lstat failed too — terminal doesn't exist at all.\n }\n\n // Sub-case B: walk up to the nearest existing ancestor, then re-attach\n // the suffix lexically.\n let cursor = dirname(path);\n let suffix = path.slice(cursor.length);\n while (cursor !== dirname(cursor)) {\n try {\n const real = realpathSync(cursor);\n // Reconstruct: ancestor's realpath + remaining (still-lexical) suffix\n return resolve(real, `.${suffix}`);\n } catch {\n suffix = path.slice(dirname(cursor).length);\n cursor = dirname(cursor);\n }\n }\n // Reached filesystem root without finding any existing ancestor.\n return undefined;\n}\n\nconst LOCK_FILES = new Set([\"pnpm-lock.yaml\", \"package-lock.json\", \"yarn.lock\", \"bun.lockb\"]);\n\n// T5.6 — top-level credential dot-dirs / dot-files. Matching against\n// the FIRST path segment (lowercase). Adding any entry here costs a\n// CHANGELOG note + an explicit case-fold test (entries are lowercased\n// at module load).\nconst SENSITIVE_FIRST_SEGMENTS = new Set([\n \".ssh\",\n \".aws\",\n \".docker\",\n \".kube\",\n \".npmrc\",\n \".netrc\",\n \".pgpass\",\n]);\n\n// T5.6 — credential basenames blocked at ANY depth (lowercase). Catches\n// the developer-laptop case where an agent recurses into a subdir.\nconst SENSITIVE_BASENAMES = new Set([\n \"id_rsa\",\n \"id_ed25519\",\n \"id_ecdsa\",\n \"id_dsa\",\n \"authorized_keys\",\n \"known_hosts\",\n \".npmrc\",\n \".netrc\",\n \".pgpass\",\n]);\n\n// T5.6 — extension suffixes blocked at ANY depth (lowercase). Covers\n// the entire `*.pem` / `*.key` private-material family.\nconst SENSITIVE_SUFFIXES = [\".pem\", \".key\", \".p12\", \".pfx\"];\n\n/**\n * Decide whether a project-relative path points to a known-sensitive file\n * that a coding agent must not read or write.\n *\n * Universal blocklist (works for any agent operating on a project tree):\n *\n * - `.env`, `.env.<anything>` — except `.env.example` (template safe to read)\n * - `.git/` — version control internals\n * - `node_modules/` — dependency cache (changes don't belong to the user)\n * - `.theo/` — TheoKit build artefacts / state\n * - Lock files at any depth: `pnpm-lock.yaml`, `package-lock.json`,\n * `yarn.lock`, `bun.lockb`\n *\n * Operates on path segments (forward-slash normalized). Cross-platform safe.\n *\n * Use together with `safePathJoin` + `assertNoSymlinkEscape`: the former two\n * defeat traversal, this one defeats reading a file that is lexically inside\n * the project but should not be agent-visible.\n *\n * @public\n */\nexport function isForbiddenPath(input: string): boolean {\n // T5.6 — lowercase normalization defeats case-only bypass on\n // case-insensitive filesystems (Windows/macOS-default) where `.ENV`\n // and `.env` map to the same inode but a case-sensitive string\n // check passes the former.\n const normalized = input.replace(/\\\\/g, \"/\").replace(/^\\.\\//, \"\").toLowerCase();\n if (normalized.length === 0) return false;\n\n const segments = normalized.split(\"/\").filter((s) => s.length > 0);\n if (segments.length === 0) return false;\n\n if (isForbiddenFirstSegment(segments[0]!)) return true;\n if (isForbiddenBasename(segments[segments.length - 1]!)) return true;\n return false;\n}\n\nfunction isForbiddenFirstSegment(first: string): boolean {\n // .env.example is explicitly allowlisted (template safe to read)\n if (first === \".env.example\") return false;\n if (first === \".env\") return true;\n if (/^\\.env\\./.test(first)) return true;\n if (first === \".git\" || first === \"node_modules\" || first === \".theo\") return true;\n return SENSITIVE_FIRST_SEGMENTS.has(first);\n}\n\nfunction isForbiddenBasename(basename: string): boolean {\n if (LOCK_FILES.has(basename)) return true;\n if (SENSITIVE_BASENAMES.has(basename)) return true;\n for (const suffix of SENSITIVE_SUFFIXES) {\n if (basename.endsWith(suffix)) return true;\n }\n return false;\n}\n\nconst IDENTIFIER_PATTERN = /^[a-z0-9][a-z0-9\\-_]*$/i;\n\n/**\n * Validate that `input` is a safe path component (skill name, agent ID,\n * namespace, etc.) and return its lowercase form. Strict grammar\n * `^[a-z0-9][a-z0-9-_]*$` rejects path separators, dots, null bytes,\n * whitespace, unicode invisible chars, and any leading `-`/`_`.\n *\n * @param input - User-supplied identifier candidate.\n * @param options.maxLen - Maximum allowed length (default 64).\n * @returns Lowercase form of `input`.\n * @throws `ConfigurationError` with code `invalid_identifier` on rejection.\n *\n * @internal\n */\n/**\n * T1.4 — validate a relative artifact path string BEFORE it is used to look\n * up a fixture or to fetch from PaaS. Rejects every well-known traversal\n * vector at the boundary, throwing `PathTraversalError`.\n *\n * Vectors rejected:\n * - classic `..` parent-directory traversal (any segment).\n * - backslash separators (Windows-style `..\\\\windows`).\n * - URL-encoded `%2e%2e` / `%2E%2E` (double-decoded traversal).\n * - NUL byte injection (`\\x00`).\n * - Windows drive letter prefix (`C:`, `D:\\\\...`).\n * - Home-tilde expansion (`~/`, `~root/...`).\n * - Absolute paths starting with `/`.\n *\n * Does NOT touch the filesystem — the call is shape-only. Live symlink\n * traversal protection happens via `assertNoSymlinkEscape` at the FS-resolve\n * boundary.\n *\n * @param input - Caller-supplied artifact path.\n * @throws `PathTraversalError` on any rejection.\n *\n * @internal\n */\nexport function validateArtifactPath(input: string): void {\n rejectKnownPrefixVectors(input);\n const normalized = decodeAndNormalize(input);\n rejectParentTraversal(input, normalized);\n}\n\nfunction rejectKnownPrefixVectors(input: string): void {\n if (input.includes(\"\\x00\")) {\n throw new PathTraversalError(input, \"<nul-byte>\");\n }\n if (input.startsWith(\"/\") || input.startsWith(\"~\")) {\n throw new PathTraversalError(input, input);\n }\n if (/^[A-Za-z]:[\\\\/]?/.test(input)) {\n throw new PathTraversalError(input, input);\n }\n}\n\nfunction decodeAndNormalize(input: string): string {\n // URL-encoded traversal — 2 passes catches `%252e%252e`.\n // Malformed sequences (decodeURIComponent throws) are themselves a rejection.\n let decoded = input;\n for (let i = 0; i < 2; i += 1) {\n try {\n const next = decodeURIComponent(decoded);\n if (next === decoded) break;\n decoded = next;\n } catch {\n throw new PathTraversalError(input, \"<malformed-url-encoding>\");\n }\n }\n // Normalize backslash to forward slash before segment-walking.\n return decoded.replace(/\\\\/g, \"/\");\n}\n\nfunction rejectParentTraversal(input: string, normalized: string): void {\n for (const segment of normalized.split(\"/\")) {\n if (segment === \"..\" || segment === \"..%00\") {\n throw new PathTraversalError(input, normalized);\n }\n }\n // Defense in depth: literal `..` anywhere in the normalized string.\n if (normalized.includes(\"..\")) {\n throw new PathTraversalError(input, normalized);\n }\n}\n\nexport function sanitizeIdentifier(input: string, options?: { maxLen?: number }): string {\n const maxLen = options?.maxLen ?? 64;\n if (input.length === 0 || input.length > maxLen) {\n throw new ConfigurationError(`Identifier length out of range (1-${maxLen}): \"${input}\"`, {\n code: \"invalid_identifier\",\n });\n }\n // T5.5 — explicit NUL / control char rejection ahead of the generic\n // pattern check. The IDENTIFIER_PATTERN regex already excludes these\n // (they are not in `[a-z0-9\\-_]`), but routing them through the same\n // helper used by safePathJoin gives operators a precise diagnostic\n // (\"nul-byte\" / \"control-char-0x..\") instead of the generic\n // \"invalid characters\" message — making prompt-injection traces\n // legible per Unbreakable Rule 3.\n rejectNulAndControlChars(input, \"identifier\");\n if (!IDENTIFIER_PATTERN.test(input)) {\n throw new ConfigurationError(`Identifier contains invalid characters: \"${input}\"`, {\n code: \"invalid_identifier\",\n });\n }\n return input.toLowerCase();\n}\n\n/**\n * Convert ANY opaque id (agent id, run id, conversation id, namespace, email,\n * arbitrary string) into a deterministic, filesystem-safe filename component.\n *\n * Unlike {@link sanitizeIdentifier} (which THROWS on non-conforming input),\n * this is a total function: it NEVER throws on a non-empty string. It returns\n * the lowercased id verbatim when it already matches the safe grammar\n * `^[a-z0-9][a-z0-9-_]*$` and fits `maxLen` (so UUIDs, hashes, and slugs stay\n * human-readable), otherwise a deterministic `h-<16 hex>` sha256 token\n * (collision-resistant and always a valid filename). The output charset is\n * always `[a-z0-9_-]`, safe as a literal path segment on every filesystem.\n *\n * @param id - any opaque identifier (must be a non-empty string)\n * @param options.maxLen - max length for the passthrough branch (default 128).\n * Ids longer than this are hashed; the hash token itself is always short.\n * @throws ConfigurationError (code `invalid_filename_id`) only on empty input.\n *\n * @example\n * safeFilenameForId(\"550e8400-e29b-41d4-a716-446655440000\") // passthrough\n * safeFilenameForId(\"user@example.com\") // \"h-<16hex>\"\n *\n * @internal — public via `@theokit/sdk/path-safety`\n */\nexport function safeFilenameForId(id: string, options?: { maxLen?: number }): string {\n if (id.length === 0) {\n throw new ConfigurationError(\"Filename id must be a non-empty string\", {\n code: \"invalid_filename_id\",\n });\n }\n const maxLen = options?.maxLen ?? 128;\n const lower = id.toLowerCase();\n if (lower.length <= maxLen && IDENTIFIER_PATTERN.test(lower)) {\n return lower;\n }\n return `h-${createHash(\"sha256\").update(id).digest(\"hex\").slice(0, 16)}`;\n}\n"]}
|
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
'use strict';
|
|
2
2
|
|
|
3
3
|
var chunkL5YO6PWL_cjs = require('./chunk-L5YO6PWL.cjs');
|
|
4
|
+
var chunkVKJ7V7EB_cjs = require('./chunk-VKJ7V7EB.cjs');
|
|
4
5
|
var os = require('os');
|
|
5
6
|
var path = require('path');
|
|
6
7
|
var promises = require('fs/promises');
|
|
7
|
-
var fs = require('fs');
|
|
8
8
|
var zod = require('zod');
|
|
9
9
|
|
|
10
10
|
var HEAD_RATIO = 0.7;
|
|
@@ -53,17 +53,6 @@ function emitTruncationCounter(source) {
|
|
|
53
53
|
} catch {
|
|
54
54
|
}
|
|
55
55
|
}
|
|
56
|
-
function realOrResolved(path) {
|
|
57
|
-
try {
|
|
58
|
-
return fs.realpathSync(path);
|
|
59
|
-
} catch {
|
|
60
|
-
return path;
|
|
61
|
-
}
|
|
62
|
-
}
|
|
63
|
-
function insideRoot(target, root) {
|
|
64
|
-
const rel = path.relative(realOrResolved(root), realOrResolved(target));
|
|
65
|
-
return rel !== "" && !rel.startsWith("..") && !path.isAbsolute(rel);
|
|
66
|
-
}
|
|
67
56
|
|
|
68
57
|
// src/internal/runtime/context/context-import-resolver.ts
|
|
69
58
|
var IMPORT_RE = /^@(\S+)\s*$/gm;
|
|
@@ -79,7 +68,7 @@ async function resolveImports(content, basePath, opts) {
|
|
|
79
68
|
const baseDir = path.dirname(basePath);
|
|
80
69
|
return replaceAsync(content, IMPORT_RE, async (raw) => {
|
|
81
70
|
const absolute = resolveImportPath(raw, baseDir);
|
|
82
|
-
if (opts.projectRoot !== void 0 && !insideRoot(absolute, opts.projectRoot)) {
|
|
71
|
+
if (opts.projectRoot !== void 0 && !chunkVKJ7V7EB_cjs.insideRoot(absolute, opts.projectRoot)) {
|
|
83
72
|
return `[@import outside the project root, refused: ${raw}]`;
|
|
84
73
|
}
|
|
85
74
|
if (opts.visited.has(absolute)) {
|
|
@@ -342,11 +331,10 @@ async function loadPlainMarkdownSource(spec, path, id, opts, gitRoot) {
|
|
|
342
331
|
}
|
|
343
332
|
|
|
344
333
|
exports.DEFAULT_MAX_BYTES_PER_FILE = DEFAULT_MAX_BYTES_PER_FILE;
|
|
345
|
-
exports.insideRoot = insideRoot;
|
|
346
334
|
exports.parseRules = parseRules;
|
|
347
335
|
exports.resolveImports = resolveImports;
|
|
348
336
|
exports.runDiscovery = runDiscovery;
|
|
349
337
|
exports.shouldActivateRule = shouldActivateRule;
|
|
350
338
|
exports.truncateWithMarker = truncateWithMarker;
|
|
351
|
-
//# sourceMappingURL=chunk-
|
|
352
|
-
//# sourceMappingURL=chunk-
|
|
339
|
+
//# sourceMappingURL=chunk-OKLYRPKL.cjs.map
|
|
340
|
+
//# sourceMappingURL=chunk-OKLYRPKL.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/internal/runtime/context/context-loaders.ts","../src/internal/runtime/context/context-import-resolver.ts","../src/internal/runtime/context/context-glob.ts","../src/internal/runtime/context/context-yaml-lite.ts","../src/internal/runtime/context/context-rules-frontmatter.ts","../src/internal/runtime/context/context-mdc-parser.ts","../src/internal/runtime/context/context-discovery-runner.ts"],"names":["readFile","dirname","insideRoot","resolvePath","join","homedir","isAbsolute","z","findGitRoot","DEFAULT_DISCOVERY_SPECS","walkUpForFile","walkUpForGlob","path","relative"],"mappings":";;;;;;;;;AAaA,IAAM,UAAA,GAAa,GAAA;AACnB,IAAM,UAAA,G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A,IAAiB,IAAA;AAAA,IAAM,IAAA;AAAA,IAAM,EAAA;AAAA,IAAI,UAAA;AAAA,IAAY,CAAC,EAAA,KACnD,kBAAA,CAAmB,IAAI,IAAA,CAAK,YAAA,IAAgB,EAAE;AAAA,GAChD;AACF;AAEA,eAAe,uBAAA,CACb,IAAA,EACA,IAAA,EACA,EAAA,EACA,MACA,OAAA,EACuC;AACvC,EAAA,MAAM,MAAA,GAAS,MAAM,iBAAA,CAAkB,IAAA,EAAM,EAAE,eAAA,EAAiB,IAAA,CAAK,iBAAiB,CAAA;AACtF,EAAA,IAAI,MAAA,KAAW,QAAW,OAAO,MAAA;AACjC,EAAA,IAAI,UAAU,MAAA,CAAO,OAAA;AACrB,EAAA,IAAI,KAAK,aAAA,EAAe;AACtB,IAAA,OAAA,GAAU,MAAM,cAAA,CAAe,OAAA,EAAS,IAAA,EAAM;AAAA,MAC5C,OAAA,kBAAS,IAAI,GAAA,CAAI,CAAC,IAAI,CAAC,CAAA;AAAA,MACvB,KAAA,EAAO,CAAA;AAAA,MACP,iBAAiB,IAAA,CAAK,eAAA;AAAA;AAAA;AAAA;AAAA;AAAA,MAKtB,WAAA,EAAa,IAAA,CAAK,UAAA,IAAc,OAAA,IAAW,IAAA,CAAK;AAAA,KACjD,CAAA;AAAA,EACH;AACA,EAAA,OAAO;AAAA,IACL,EAAA;AAAA,IACA,MAAA,EAAQ,IAAA;AAAA,IACR,OAAA;AAAA,IACA,UAAU,IAAA,CAAK,QAAA;AAAA,IACf,WAAW,MAAA,CAAO;AAAA,GACpB;AACF","file":"chunk-OKLYRPKL.cjs","sourcesContent":["/**\n * Context file loaders + truncation (T1.2, ADRs D154 / D155 / D159).\n *\n * Reads context source files from disk, applies the per-file size cap\n * with 70%/20% head/tail truncation, and emits the\n * `context_files_truncated` telemetry counter when the cap fires.\n * Pure (no I/O) for `truncateWithMarker` — testable in isolation.\n *\n * @internal\n */\n\nimport { readFile } from \"node:fs/promises\";\n\nconst HEAD_RATIO = 0.7;\nconst TAIL_RATIO = 0.2;\nconst MARKER = \"\\n\\n…[truncated by theokit]\\n\\n\";\n\n/** Default per-file cap (40k chars ≈ 10k tokens). D155. */\nexport const DEFAULT_MAX_BYTES_PER_FILE = 40_000;\n\nexport interface LoadedSource {\n /** Absolute path the content came from. */\n readonly source: string;\n readonly content: string;\n readonly originalBytes: number;\n readonly truncated: boolean;\n}\n\nexport interface TruncateResult {\n readonly truncated: boolean;\n readonly finalContent: string;\n}\n\n/**\n * Cap `content` at `max` characters with 70%/20% head/tail truncation\n * and an explicit marker. Pure — no I/O, no telemetry.\n *\n * EC-C: when `max <= MARKER.length`, skip the marker entirely and\n * return a head-only slice. Without this guard, `budget = max -\n * MARKER.length` would go negative and `content.slice(-tailBytes)`\n * would slice from the END of the string rather than truncating.\n *\n * EC-H: codepoint integrity — `String.slice()` operates on UTF-16\n * code units, which can split surrogate pairs. We accept that\n * trailing/leading replacement chars (U+FFFD) may appear at boundaries.\n * Modern LLMs tolerate them; byte-exact safety would require Buffer\n * slicing + TextDecoder with `fatal: true` retry, which adds complexity\n * without value.\n *\n * @public\n */\nexport function truncateWithMarker(content: string, max: number): TruncateResult {\n if (content.length <= max) {\n return { truncated: false, finalContent: content };\n }\n // EC-C: max too small to fit even the marker — return head-only slice.\n if (max <= MARKER.length) {\n return { truncated: true, finalContent: content.slice(0, max) };\n }\n const budget = max - MARKER.length;\n const headBytes = Math.floor(budget * (HEAD_RATIO / (HEAD_RATIO + TAIL_RATIO)));\n const tailBytes = budget - headBytes;\n return {\n truncated: true,\n finalContent: content.slice(0, headBytes) + MARKER + content.slice(-tailBytes),\n };\n}\n\n/**\n * Read a file from disk and apply the per-file cap. Emits telemetry\n * counter when truncation fires.\n *\n * EC-G: file deleted between discovery and read (FS race) → returns\n * `undefined`, never throws.\n *\n * @internal\n */\nexport async function loadPlainMarkdown(\n absPath: string,\n opts: { maxBytesPerFile?: number } = {},\n): Promise<LoadedSource | undefined> {\n const max = opts.maxBytesPerFile ?? DEFAULT_MAX_BYTES_PER_FILE;\n let content: string;\n try {\n content = await readFile(absPath, \"utf8\");\n } catch {\n // EC-G: ENOENT / EACCES / etc → caller treats as missing.\n return undefined;\n }\n const { truncated, finalContent } = truncateWithMarker(content, max);\n if (truncated) {\n emitTruncationCounter(absPath);\n }\n return {\n source: absPath,\n content: finalContent,\n originalBytes: content.length,\n truncated,\n };\n}\n\n/**\n * EC-L: telemetry no-op when OTel is not imported. We import the tracer\n * lazily and use `safeCall` so the lookup never throws and never pulls\n * OTel into the import graph for users without `@opentelemetry/api`\n * installed.\n *\n * @internal\n */\nfunction emitTruncationCounter(source: string): void {\n // Lazy resolution via globalThis avoids static import of telemetry/tracer.\n // Tests can spy via the same path; production users without OTel see no-op.\n const tracer = (\n globalThis as { __theokit_tracer?: { inc?: (k: string, attrs: unknown) => void } }\n ).__theokit_tracer;\n if (tracer?.inc === undefined) return;\n try {\n tracer.inc(\"context_files_truncated\", { file: source });\n } catch {\n // Telemetry must never break the loader.\n }\n}\n","/**\n * `@path/to/file` import resolver (T2.1, ADR D156).\n *\n * Anthropic/Gemini convention: lines that are EXACTLY `@path` get\n * replaced with the imported file's content, recursively (5-hop cap),\n * with cycle detection. Inline `see @x.md, also @y.md` references are\n * NOT resolved (EC-Q — own-line only, mirrors Anthropic's actual\n * behavior).\n *\n * EC-D fix: every imported file is itself capped at `maxBytesPerFile`\n * via `loadPlainMarkdown` BEFORE concatenation. Prevents a CLAUDE.md\n * with 5 imports of 30k each from ballooning to 150k of imported\n * content before the outer cap fires.\n *\n * @internal\n */\n\nimport { homedir } from \"node:os\";\nimport { dirname, isAbsolute, join, resolve as resolvePath } from \"node:path\";\n\nimport { loadPlainMarkdown } from \"./context-loaders.js\";\nimport { insideRoot } from \"./path-containment.js\";\n\n/** EC-Q: line-anchored. `@path` must be alone on its line. */\nconst IMPORT_RE = /^@(\\S+)\\s*$/gm;\nconst MAX_HOPS = 5;\n\nexport interface ResolveImportsOptions {\n /** Absolute paths already resolved (cycle detection). */\n readonly visited: Set<string>;\n /** Current recursion depth — caps at MAX_HOPS. */\n readonly depth: number;\n /** Per-import file cap (EC-D). Forwarded to loadPlainMarkdown. */\n readonly maxBytesPerFile: number;\n /**\n * The directory an import may not escape. When set, a target resolving outside it is\n * refused and replaced with a placeholder.\n *\n * The file carrying the import is REPOSITORY-CONTROLLED — `CLAUDE.md` and `GEMINI.md`\n * are the two default specs with `followImports: true`, and both are found by\n * `git-root-walk` inside the tree the agent was pointed at. Without a root, a cloned\n * repository could name `@~/.ssh/id_rsa` or any absolute path and have its contents\n * inlined into the system prompt, and from there sent to the model provider. The\n * traversal guard that already existed (`isSafePattern`) guards the discovery PATTERN,\n * not the import TARGET, so it never saw this.\n *\n * OPTIONAL, so a caller outside the discovery path keeps the previous behaviour rather\n * than breaking on an upgrade. `runDiscovery` always supplies `gitRoot ?? cwd` — the\n * same value it already uses to keep absolute paths out of `<source name=\"\">`.\n */\n readonly projectRoot?: string;\n}\n\n/**\n * Resolve `@path` directives in `content`. Each match is replaced with\n * the imported file content (already cap-truncated per EC-D), and\n * recursion continues on the resolved content until MAX_HOPS or cycle.\n *\n * Failure modes (placeholders, never throws):\n * - file not found → `[@import not found: <path>]`\n * - cycle detected → `[@import cycle detected: <path>]`\n * - depth exceeded → trailing `\\n\\n…[@import depth limit 5 reached]\\n\\n`\n *\n * @internal\n */\nexport async function resolveImports(\n content: string,\n basePath: string,\n opts: ResolveImportsOptions,\n): Promise<string> {\n if (opts.depth >= MAX_HOPS) {\n return `${content}\\n\\n…[@import depth limit ${MAX_HOPS} reached]\\n\\n`;\n }\n const baseDir = dirname(basePath);\n return replaceAsync(content, IMPORT_RE, async (raw) => {\n const absolute = resolveImportPath(raw, baseDir);\n // Containment BEFORE the read. Reporting the refusal after loading the file would\n // already have put the bytes in memory, and the placeholder names the path the author\n // wrote rather than the resolved one — echoing `/home/<user>/.ssh/id_rsa` back into the\n // prompt would leak the layout of the machine to the same untrusted document.\n if (opts.projectRoot !== undefined && !insideRoot(absolute, opts.projectRoot)) {\n return `[@import outside the project root, refused: ${raw}]`;\n }\n if (opts.visited.has(absolute)) {\n return `[@import cycle detected: ${raw}]`;\n }\n opts.visited.add(absolute);\n const loaded = await loadPlainMarkdown(absolute, { maxBytesPerFile: opts.maxBytesPerFile });\n if (loaded === undefined) {\n return `[@import not found: ${raw}]`;\n }\n // Recurse with same visited set + incremented depth. `projectRoot` is FORWARDED: an\n // imported file is repository-controlled too, so a root that applied only at depth 0\n // would be escapable in one extra hop.\n return resolveImports(loaded.content, absolute, {\n visited: opts.visited,\n depth: opts.depth + 1,\n maxBytesPerFile: opts.maxBytesPerFile,\n ...(opts.projectRoot === undefined ? {} : { projectRoot: opts.projectRoot }),\n });\n });\n}\n\nfunction resolveImportPath(raw: string, baseDir: string): string {\n if (raw.startsWith(\"~/\")) {\n return resolvePath(join(homedir(), raw.slice(2)));\n }\n if (isAbsolute(raw)) {\n return resolvePath(raw);\n }\n return resolvePath(join(baseDir, raw));\n}\n\n/**\n * Async equivalent of `String.prototype.replace` — sequential. Returns\n * `content` with every `re` match replaced by `await replacer(match)`.\n *\n * @internal\n */\nasync function replaceAsync(\n content: string,\n re: RegExp,\n replacer: (raw: string) => Promise<string>,\n): Promise<string> {\n const matches: Array<{ match: string; raw: string; index: number }> = [];\n // Reset lastIndex; clone the regex to avoid stateful traps.\n const localRe = new RegExp(re.source, re.flags);\n let m: RegExpExecArray | null;\n // biome-ignore lint/suspicious/noAssignInExpressions: idiomatic regex loop\n while ((m = localRe.exec(content)) !== null) {\n matches.push({ match: m[0], raw: m[1] ?? \"\", index: m.index });\n if (m.index === localRe.lastIndex) localRe.lastIndex += 1;\n }\n if (matches.length === 0) return content;\n let result = \"\";\n let cursor = 0;\n for (const entry of matches) {\n result += content.slice(cursor, entry.index);\n result += await replacer(entry.raw);\n cursor = entry.index + entry.match.length;\n }\n result += content.slice(cursor);\n return result;\n}\n","/**\n * Shared glob → RegExp compiler for context discovery (extracted from the\n * MDC parser so the `.cursor/rules/*.mdc` and `.theokit/rules/*.md` parsers\n * share ONE implementation — DRY, no new dependency).\n *\n * Supports `**` (any depth), `*` (single path segment, no `/`), `?` (single\n * non-separator char). Sufficient for the patterns Cursor and Claude Code\n * themselves recommend.\n *\n * @internal\n */\nexport function globToRegex(glob: string): RegExp {\n // Support **/ (zero-or-more path segments), ** (any depth), * (single\n // segment), ? (single non-separator char). `**/` collapses so `src/**/*.ts`\n // matches `src/foo.ts` AND `src/a/b/foo.ts` — the semantics Cursor and Claude\n // Code document (\"src/**/* → all files under src/\"). `*` and `?` never cross a\n // `/` (strict glob segment semantics). Escape other regex metas.\n const compiled = glob\n .replace(/[.+^${}()|[\\]\\\\]/g, \"\\\\$&\")\n .replace(/\\*\\*\\//g, \"::GLOBSTAR_SLASH::\")\n .replace(/\\*\\*/g, \"::GLOBSTAR::\")\n .replace(/\\*/g, \"[^/]*\")\n .replace(/\\?/g, \"[^/]\")\n .replace(/::GLOBSTAR_SLASH::/g, \"(?:.*/)?\")\n .replace(/::GLOBSTAR::/g, \".*\");\n return new RegExp(`^${compiled}$`);\n}\n\n/**\n * True when any of `patterns` glob-matches any of `paths`. Central helper so\n * both rule parsers agree on activation semantics.\n *\n * @internal\n */\nexport function anyGlobMatches(\n patterns: ReadonlyArray<string>,\n paths: ReadonlyArray<string>,\n): boolean {\n if (patterns.length === 0 || paths.length === 0) return false;\n const res = patterns.map(globToRegex);\n return paths.some((p) => res.some((re) => re.test(p)));\n}\n","/**\n * Minimal YAML-subset frontmatter parsing shared by the `.cursor/rules/*.mdc`\n * and `.theokit/rules/*.md` parsers (extracted for DRY — one parser, one set\n * of edge-case behaviours, no new dependency).\n *\n * Handles `key: value` lines (string scalars, booleans, integers) and `key:`\n * followed by indented `- item` arrays or inline `[a, b]` arrays. Sufficient\n * for the small, fixed frontmatter field sets these rule files use. Throws on\n * a truly malformed line (no colon).\n *\n * NOTE — distinct from the sibling `yaml-frontmatter.ts` `parseSimpleYaml` on\n * purpose: that one parses INLINE arrays only (`key: [a, b]`), whereas rule\n * files (`.cursor/rules/*.mdc`, `.theokit/rules/*.md`) use MULTI-LINE `- item`\n * lists (`paths:` / `globs:`), which this parser adds. Unifying onto the inline\n * parser would drop multi-line list support; unifying the other way would touch\n * the skills/subagents/persistence loaders that depend on the inline one. The\n * two intentionally coexist until a shared parser handles both shapes.\n *\n * @internal\n */\n\nconst FRONTMATTER_RE = /^---\\s*\\n([\\s\\S]*?)\\n---\\s*\\n([\\s\\S]*)$/;\n\nexport interface FrontmatterSplit {\n /** Raw YAML block between the `---` fences, or undefined when absent. */\n readonly yaml: string | undefined;\n /** The markdown body after the frontmatter (or the whole content). */\n readonly body: string;\n}\n\n/**\n * Split `---`-fenced frontmatter from the body. When no frontmatter fence is\n * present, `yaml` is undefined and `body` is the whole content.\n *\n * @internal\n */\nexport function splitFrontmatter(content: string): FrontmatterSplit {\n const m = FRONTMATTER_RE.exec(content);\n if (m === null) return { yaml: undefined, body: content };\n return { yaml: m[1] ?? \"\", body: m[2] ?? \"\" };\n}\n\n/**\n * Parse the minimal YAML subset. Throws on a line without a colon (malformed).\n *\n * @internal\n */\n// biome-ignore lint/complexity/noExcessiveCognitiveComplexity: YAML-subset parser handles scalars + multi-line arrays + inline arrays in a single pass; extracting helpers fragments the line-state machine.\nexport function parseSimpleYaml(yaml: string): Record<string, unknown> {\n const out: Record<string, unknown> = {};\n const lines = yaml.split(/\\r?\\n/);\n let i = 0;\n while (i < lines.length) {\n const line = lines[i];\n i += 1;\n if (line === undefined) continue;\n const trimmed = line.trim();\n if (trimmed === \"\" || trimmed.startsWith(\"#\")) continue;\n const colon = trimmed.indexOf(\":\");\n if (colon === -1) throw new Error(`Invalid YAML line: ${trimmed}`);\n const key = trimmed.slice(0, colon).trim();\n const rest = trimmed.slice(colon + 1).trim();\n if (rest === \"\") {\n // Possible array; collect indented `- item` lines.\n const items: string[] = [];\n while (i < lines.length) {\n const next = lines[i];\n if (next === undefined) break;\n const nextTrim = next.trim();\n if (nextTrim.startsWith(\"- \")) {\n items.push(parseScalar(nextTrim.slice(2).trim()) as string);\n i += 1;\n } else if (nextTrim === \"\") {\n i += 1;\n } else {\n break;\n }\n }\n out[key] = items;\n } else if (rest.startsWith(\"[\") && rest.endsWith(\"]\")) {\n // Inline array `globs: [\"**/*.ts\", \"**/*.tsx\"]`\n const inner = rest.slice(1, -1).trim();\n out[key] =\n inner === \"\"\n ? []\n : inner.split(\",\").map((s) => parseScalar(s.trim().replace(/^[\"']|[\"']$/g, \"\")));\n } else {\n out[key] = parseScalar(rest);\n }\n }\n return out;\n}\n\nfunction parseScalar(s: string): string | boolean | number {\n if (s === \"true\") return true;\n if (s === \"false\") return false;\n if (/^-?\\d+$/.test(s)) return parseInt(s, 10);\n // Strip surrounding quotes if present.\n return s.replace(/^[\"']|[\"']$/g, \"\");\n}\n","/**\n * Parser for `.theokit/rules/*.md` — theokit-native path-scoped rules,\n * mirroring Claude Code's `.claude/rules/`.\n *\n * Frontmatter fields:\n * - `paths` — glob-pattern array (Claude Code parity: `.claude/rules` uses `paths:`).\n * - `globs` — glob-pattern array (Cursor-compatible alias; unioned with `paths`).\n * - `alwaysApply` — activate unconditionally (no scope needed).\n * - `enabled` — set `false` to disable the rule entirely (wins over everything).\n * - `description` — human note; not used for activation in v1.\n *\n * Activation (`shouldActivateRule`):\n * - `enabled: false` → never activates.\n * - `alwaysApply: true` → always activates.\n * - otherwise → activates iff a `paths`/`globs` pattern matches an in-scope\n * file (the caller's `agent.send(..., { contextPaths })`). With no in-scope\n * files, a scoped rule stays dormant (parity with Cursor `.mdc`).\n *\n * A file with no `---` frontmatter is treated as an unconditional rule\n * (`alwaysApply: true`). Malformed YAML → `undefined` (caller drops + counts).\n *\n * Glob + YAML subset are shared with the MDC parser (DRY, no new dependency).\n *\n * @internal\n */\n\nimport { z } from \"zod\";\n\nimport { anyGlobMatches } from \"./context-glob.js\";\nimport { parseSimpleYaml, splitFrontmatter } from \"./context-yaml-lite.js\";\n\n/** YAML frontmatter schema for `.theokit/rules/*.md` files. @internal */\nexport const RulesFrontmatterSchema = z.object({\n description: z.string().optional(),\n paths: z.array(z.string()).optional(),\n globs: z.array(z.string()).optional(),\n alwaysApply: z.boolean().optional(),\n enabled: z.boolean().optional(),\n});\n\nexport type RulesFrontmatter = z.infer<typeof RulesFrontmatterSchema>;\n\nexport interface RulesParseResult {\n readonly frontmatter: RulesFrontmatter;\n readonly body: string;\n}\n\n/**\n * Parse `.theokit/rules/*.md` content into frontmatter + body. No frontmatter\n * fence → unconditional rule. Malformed YAML → `undefined`.\n *\n * @internal\n */\nexport function parseRules(content: string): RulesParseResult | undefined {\n const { yaml, body } = splitFrontmatter(content);\n if (yaml === undefined) {\n return { frontmatter: { alwaysApply: true }, body: content };\n }\n try {\n const parsed = parseSimpleYaml(yaml);\n const validated = RulesFrontmatterSchema.safeParse(parsed);\n if (!validated.success) return undefined;\n return { frontmatter: validated.data, body };\n } catch {\n return undefined;\n }\n}\n\n/**\n * Decide whether a rule activates given the in-scope files. `paths` and\n * `globs` are unioned; both are glob patterns matched against the caller's\n * declared scope.\n *\n * @internal\n */\nexport function shouldActivateRule(\n fm: RulesFrontmatter,\n inScopePaths: ReadonlyArray<string>,\n): boolean {\n if (fm.enabled === false) return false;\n if (fm.alwaysApply === true) return true;\n const patterns = [...(fm.paths ?? []), ...(fm.globs ?? [])];\n if (patterns.length === 0) return false;\n return anyGlobMatches(patterns, inScopePaths);\n}\n","/**\n * MDC (Markdown Cursor) parser for `.cursor/rules/*.mdc` (T3.1, ADR D154).\n *\n * Parses YAML frontmatter with `description` / `globs` / `alwaysApply`\n * fields. Honors activation per Cursor's docs:\n * - `alwaysApply: true` → activates unconditionally.\n * - `alwaysApply: false` + matching glob in `touchedFiles` → activates.\n * - `alwaysApply: false` + no glob match → skipped.\n *\n * **EC-I (v1 semantic):** at `agent.send()` time, `touchedFiles` is empty\n * UNLESS the caller passes `contextPaths` (the in-scope file set). When\n * `contextPaths` is provided, per-glob activation fires; otherwise only\n * `alwaysApply: true` rules activate. Description-based \"agent requested\"\n * classification is out of scope.\n *\n * Glob matching + the YAML subset are shared with the `.theokit/rules/*.md`\n * parser via `context-glob.ts` / `context-yaml-lite.ts` (DRY, no new dep).\n *\n * @internal\n */\n\nimport { z } from \"zod\";\n\nimport { anyGlobMatches } from \"./context-glob.js\";\nimport { parseSimpleYaml, splitFrontmatter } from \"./context-yaml-lite.js\";\n\n/** YAML frontmatter schema for MDC files. @internal */\nexport const McdFrontmatterSchema = z.object({\n description: z.string().optional(),\n globs: z.array(z.string()).optional(),\n alwaysApply: z.boolean().optional(),\n});\n\nexport type McdFrontmatter = z.infer<typeof McdFrontmatterSchema>;\n\nexport interface McdParseResult {\n readonly frontmatter: McdFrontmatter;\n readonly body: string;\n}\n\n/**\n * Parse `.mdc` content. Returns frontmatter + body. EC-18: when the\n * file has no `---` frontmatter, returns `frontmatter: {alwaysApply:\n * true}` so the body is treated as an unconditional rule.\n *\n * On YAML parse error, returns `undefined` and the caller emits a\n * telemetry counter (EC-21).\n *\n * @internal\n */\nexport function parseMdc(content: string): McdParseResult | undefined {\n const { yaml, body } = splitFrontmatter(content);\n if (yaml === undefined) {\n // EC-18: no frontmatter — treat as alwaysApply\n return { frontmatter: { alwaysApply: true }, body: content };\n }\n try {\n const parsed = parseSimpleYaml(yaml);\n const validated = McdFrontmatterSchema.safeParse(parsed);\n if (!validated.success) return undefined;\n return { frontmatter: validated.data, body };\n } catch {\n return undefined;\n }\n}\n\n/**\n * Decide whether an MDC rule activates given the currently-touched\n * files. EC-I: empty `touchedFiles` → only `alwaysApply: true`\n * activates.\n *\n * @internal\n */\nexport function shouldActivate(fm: McdFrontmatter, touchedFiles: ReadonlyArray<string>): boolean {\n if (fm.alwaysApply === true) return true;\n if (fm.globs === undefined || fm.globs.length === 0) return false;\n return anyGlobMatches(fm.globs, touchedFiles);\n}\n","/**\n * Multi-format context discovery runner (T5.1, ADRs D150-D156).\n *\n * Walks `DEFAULT_DISCOVERY_SPECS` (or caller override), loads each\n * spec via the appropriate parser, applies `@import` resolution where\n * declared, and returns a flat list of `AggregatorSource[]` ready for\n * the aggregate cap.\n *\n * **EC-E privacy fix:** source disambiguation uses\n * `relative(gitRoot ?? cwd, ...)` — NEVER absolute paths in\n * `<source name=\"\">`.\n *\n * @internal\n */\n\nimport { readFile } from \"node:fs/promises\";\nimport { dirname, relative } from \"node:path\";\n\nimport type { AggregatorSource } from \"./context-aggregator.js\";\nimport {\n DEFAULT_DISCOVERY_SPECS,\n type DiscoverySpec,\n findGitRoot,\n walkUpForFile,\n walkUpForGlob,\n} from \"./context-discovery.js\";\nimport { resolveImports } from \"./context-import-resolver.js\";\nimport { loadPlainMarkdown } from \"./context-loaders.js\";\nimport { parseMdc, shouldActivate } from \"./context-mdc-parser.js\";\nimport { parseRules, shouldActivateRule } from \"./context-rules-frontmatter.js\";\n\nexport interface DiscoveryRunnerOptions {\n /** Workspace root passed to all discovery scopes. */\n readonly cwd: string;\n /** Per-file truncation cap (D155). */\n readonly maxBytesPerFile: number;\n /** Optional override of the default registry. */\n readonly specs?: ReadonlyArray<DiscoverySpec>;\n /** Cursor MDC: file paths the LLM has touched this turn (EC-I: empty at send-time). */\n readonly touchedFiles?: ReadonlyArray<string>;\n /** When true, skip `theokit-context` spec — caller already handles the legacy path. */\n readonly skipLegacyTheokitContext?: boolean;\n /**\n * The root an `@import` may not escape. Defaults to `gitRoot ?? cwd` — the same value\n * this runner already uses to keep absolute paths out of `<source name=\"\">`.\n *\n * Present so an embedder with a trust boundary narrower than the repository can declare\n * it. Absent, the repository IS the boundary, which is the honest default for a document\n * discovered by walking the repository.\n */\n readonly importRoot?: string;\n}\n\n/**\n * Run discovery + loading across all specs. Returns sources ready for\n * the aggregator (priority + content fields populated).\n *\n * @internal\n */\n// biome-ignore lint/complexity/noExcessiveCognitiveComplexity: per-spec dispatch ladder + cross-spec dedup is a flat orchestrator; splitting would obscure the priority-merge invariant.\nexport async function runDiscovery(opts: DiscoveryRunnerOptions): Promise<AggregatorSource[]> {\n const gitRoot = findGitRoot(opts.cwd);\n const specs = opts.specs ?? DEFAULT_DISCOVERY_SPECS;\n const out: AggregatorSource[] = [];\n const seenReal = new Set<string>();\n\n for (const spec of specs) {\n if (opts.skipLegacyTheokitContext && spec.id === \"theokit-context\") continue;\n const paths = await resolvePathsForSpec(spec, opts.cwd, gitRoot);\n for (const path of paths) {\n if (seenReal.has(path)) continue;\n seenReal.add(path);\n const source = await loadOneSource(spec, path, opts, gitRoot);\n if (source !== undefined) out.push(source);\n }\n }\n return out;\n}\n\nasync function resolvePathsForSpec(\n spec: DiscoverySpec,\n cwd: string,\n gitRoot: string | undefined,\n): Promise<string[]> {\n if (spec.scope === \"cwd-only\") {\n return walkUpForFile(cwd, spec.pattern, cwd);\n }\n if (spec.scope === \"git-root-walk\") {\n return walkUpForFile(cwd, spec.pattern, gitRoot ?? cwd);\n }\n // globbed\n return walkUpForGlob(cwd, spec.pattern);\n}\n\nasync function loadOneSource(\n spec: DiscoverySpec,\n path: string,\n opts: DiscoveryRunnerOptions,\n gitRoot: string | undefined,\n): Promise<AggregatorSource | undefined> {\n // EC-E privacy: name uses relative-to-git-root for disambiguation;\n // NEVER absolute paths in the public `<source name=\"\">` attribute.\n // For cwd-only specs (THEO.md), no disambiguation is needed because\n // the scope can only ever match a single file.\n const relPath = relative(gitRoot ?? opts.cwd, dirname(path));\n const needsSuffix = spec.scope !== \"cwd-only\" && relPath !== \"\" && relPath !== \".\";\n const id = needsSuffix ? `${spec.id}@${relPath}` : spec.id;\n\n if (spec.parser === \"mdc\") {\n return loadMdcSource(spec, path, id, opts);\n }\n if (spec.parser === \"rules-frontmatter\") {\n return loadRulesSource(spec, path, id, opts);\n }\n if (spec.parser === \"frontmatter-zod\") {\n // Legacy `.theokit/context/*.md` — handled by `loadContextConfig` in\n // `context-manager.ts` for backward compat. We skip here unless caller\n // explicitly wants us to load it (currently always skipped).\n return undefined;\n }\n // plain-markdown\n return loadPlainMarkdownSource(spec, path, id, opts, gitRoot);\n}\n\n/**\n * Shared read → parse → activation-gate → source pipeline for the frontmatter\n * discovery parsers (mdc, rules). Binds the parser + the activation predicate so\n * the mdc and rules loaders differ only in those two, not in the surrounding\n * read/guard/shape boilerplate (DRY).\n */\nasync function loadParsedSource<F>(\n spec: DiscoverySpec,\n path: string,\n id: string,\n parse: (raw: string) => { frontmatter: F; body: string } | undefined,\n isActive: (frontmatter: F) => boolean,\n): Promise<AggregatorSource | undefined> {\n let raw: string;\n try {\n raw = await readFile(path, \"utf8\");\n } catch {\n return undefined;\n }\n const parsed = parse(raw);\n if (parsed === undefined || !isActive(parsed.frontmatter)) return undefined;\n return { id, source: path, content: parsed.body, priority: spec.priority, truncated: false };\n}\n\nfunction loadMdcSource(\n spec: DiscoverySpec,\n path: string,\n id: string,\n opts: DiscoveryRunnerOptions,\n): Promise<AggregatorSource | undefined> {\n return loadParsedSource(spec, path, id, parseMdc, (fm) =>\n shouldActivate(fm, opts.touchedFiles ?? []),\n );\n}\n\nfunction loadRulesSource(\n spec: DiscoverySpec,\n path: string,\n id: string,\n opts: DiscoveryRunnerOptions,\n): Promise<AggregatorSource | undefined> {\n return loadParsedSource(spec, path, id, parseRules, (fm) =>\n shouldActivateRule(fm, opts.touchedFiles ?? []),\n );\n}\n\nasync function loadPlainMarkdownSource(\n spec: DiscoverySpec,\n path: string,\n id: string,\n opts: DiscoveryRunnerOptions,\n gitRoot: string | undefined,\n): Promise<AggregatorSource | undefined> {\n const loaded = await loadPlainMarkdown(path, { maxBytesPerFile: opts.maxBytesPerFile });\n if (loaded === undefined) return undefined;\n let content = loaded.content;\n if (spec.followImports) {\n content = await resolveImports(content, path, {\n visited: new Set([path]),\n depth: 0,\n maxBytesPerFile: opts.maxBytesPerFile,\n // The document carrying the import is repository-controlled, so the repository is the\n // boundary it may not cross. Without this, `CLAUDE.md` / `GEMINI.md` — the two specs\n // with `followImports: true` — could name any absolute or `~/` path and have it\n // inlined into the system prompt.\n projectRoot: opts.importRoot ?? gitRoot ?? opts.cwd,\n });\n }\n return {\n id,\n source: path,\n content,\n priority: spec.priority,\n truncated: loaded.truncated,\n };\n}\n"]}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { WorkflowNestedError, WorkflowDuplicateStepIdError } from './chunk-HK4HRLWE.js';
|
|
2
2
|
import { PersistenceSchema } from './chunk-CAH3G4IS.js';
|
|
3
3
|
import { toJsonSchema } from './chunk-4VPXM6UU.js';
|
|
4
|
-
import { sanitizeIdentifier } from './chunk-
|
|
4
|
+
import { sanitizeIdentifier } from './chunk-JGYYNDAZ.js';
|
|
5
5
|
import { z } from 'zod';
|
|
6
6
|
|
|
7
7
|
// src/internal/workflow/event-stream.ts
|
|
@@ -411,5 +411,5 @@ function walkStepsValidating(steps, seen) {
|
|
|
411
411
|
}
|
|
412
412
|
|
|
413
413
|
export { Workflow, WorkflowBuilder, WorkflowToolError, agentStep, cloneWorkflow, fn, workflowAsTool, workflowStep };
|
|
414
|
-
//# sourceMappingURL=chunk-
|
|
415
|
-
//# sourceMappingURL=chunk-
|
|
414
|
+
//# sourceMappingURL=chunk-R2A3WIJY.js.map
|
|
415
|
+
//# sourceMappingURL=chunk-R2A3WIJY.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/internal/workflow/event-stream.ts","../src/workflow.ts"],"names":[],"mappings":";;;;;;;AAgBO,SAAS,iBAAA,GAAyC;AACvD,EAAA,MAAM,SAA0B,EAAC;AACjC,EAAA,MAAM,UAA6D,EAAC;AACpE,EAAA,IAAI,KAAA,GAAQ,KAAA;AAEZ,EAAA,MAAM,MAAA,GAA8B;AAAA,IAClC,KAAK,KAAA,EAA4B;AAC/B,MAAA,IAAI,KAAA,EAAO;AACX,MAAA,MAAM,MAAA,GAAS,QAAQ,KAAA,EAAM;AAC7B,MAAA,IAAI,MAAA,KAAW,QAAW,MAAA,CAAO,EAAE,OAAO,KAAA,EAAO,IAAA,EAAM,OAAO,CAAA;AAAA,WACzD,MAAA,CAAO,KAAK,KAAK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E,GAAG,MAAM,IAAI,4BAAA,CAA6B,CAAA,CAAE,EAAE,CAAA;AAC/D,IAAA,IAAA,CAAK,GAAA,CAAI,EAAE,EAAE,CAAA;AACb,IAAA,KAAA,MAAW,MAAA,IAAU,aAAA,CAAc,CAAC,CAAA,EAAG;AACrC,MAAA,mBAAA,CAAoB,QAAQ,IAAI,CAAA;AAAA,IAClC;AAAA,EACF;AACF","file":"chunk-EON4YTR6.js","sourcesContent":["/**\n * SE28 — a minimal pushable async iterator for `Workflow.stream()`. The executor\n * pushes {@link WorkflowEvent}s as steps run; the consumer drains them via\n * `for await`. Buffers events emitted before the consumer is ready; `end()`\n * closes the iterator so a pending/next `next()` resolves `done: true`.\n *\n * @internal\n */\n\nimport type { WorkflowEvent } from \"../../types/workflow.js\";\n\nexport interface PushableEventStream extends AsyncIterableIterator<WorkflowEvent> {\n push(event: WorkflowEvent): void;\n end(): void;\n}\n\nexport function createEventStream(): PushableEventStream {\n const buffer: WorkflowEvent[] = [];\n const waiters: Array<(r: IteratorResult<WorkflowEvent>) => void> = [];\n let ended = false;\n\n const stream: PushableEventStream = {\n push(event: WorkflowEvent): void {\n if (ended) return;\n const waiter = waiters.shift();\n if (waiter !== undefined) waiter({ value: event, done: false });\n else buffer.push(event);\n },\n end(): void {\n if (ended) return;\n ended = true;\n for (const waiter of waiters.splice(0)) waiter({ value: undefined, done: true });\n },\n next(): Promise<IteratorResult<WorkflowEvent>> {\n const buffered = buffer.shift();\n if (buffered !== undefined) return Promise.resolve({ value: buffered, done: false });\n if (ended) return Promise.resolve({ value: undefined, done: true });\n return new Promise((resolve) => waiters.push(resolve));\n },\n // `for await` calls return() on break/throw — close early so events stop\n // buffering in memory for a consumer that stopped iterating.\n return(): Promise<IteratorResult<WorkflowEvent>> {\n stream.end();\n buffer.length = 0;\n return Promise.resolve({ value: undefined, done: true });\n },\n [Symbol.asyncIterator](): PushableEventStream {\n return stream;\n },\n };\n return stream;\n}\n","/**\n * Public `Workflow` class — declarative multi-step orchestration over\n * `Agent.send`, `Handoff`, `Agent.batch` and friends (Adoption Roadmap #5;\n * ADRs D230-D248).\n *\n * Usage:\n *\n * import { Agent } from \"@theokit/sdk\";\n * import { Workflow, fn, agentStep } from \"@theokit/sdk/workflow\";\n *\n * const classifier = await Agent.create({ ... });\n * const wf = Workflow.create({ name: \"demo\" })\n * .then(fn(\"validate\", (input: { id: string }) => {\n * if (!input.id) throw new Error(\"missing id\");\n * return input;\n * }))\n * .then(agentStep(\"classify\", classifier, (i) => `Classify: ${JSON.stringify(i)}`))\n * .commit();\n *\n * const run = await wf.run({ id: \"x\" });\n * console.log(run.status, run.output);\n *\n * @public\n */\n\nimport type { ZodType } from \"zod\";\nimport { z } from \"zod\";\nimport { PersistenceSchema } from \"./internal/persistence/persistence-schema.js\";\nimport { sanitizeIdentifier } from \"./internal/security/path-guard.js\";\nimport { createEventStream } from \"./internal/workflow/event-stream.js\";\nimport { toJsonSchema } from \"./internal/zod/to-json-schema.js\";\nimport type { CustomTool, SDKAgent } from \"./types/agent.js\";\nimport type { MessageOrigin } from \"./types/run.js\";\nimport type {\n AgentStep,\n BranchStep,\n DowhileStep,\n FnStep,\n ForeachStep,\n ParallelStep,\n RetryPolicy,\n SleepStep,\n Step,\n StepContext,\n SuspendStep,\n WorkflowDescription,\n WorkflowEvent,\n WorkflowOptions,\n WorkflowResumeOptions,\n WorkflowRun,\n WorkflowRunOptions,\n WorkflowStepDescription,\n WorkflowStream,\n} from \"./types/workflow.js\";\nimport { WorkflowDuplicateStepIdError, WorkflowNestedError } from \"./types/workflow.js\";\n\n/* ─── Zod validation schemas ─── */\n\nconst RetryPolicySchema = z.object({\n // EC-3 absorbed: maxAttempts MUST be a finite int in [1, 20].\n maxAttempts: z\n .number()\n .int(\"retry.maxAttempts must be integer\")\n .min(1, \"retry.maxAttempts must be >= 1\")\n .max(20, \"retry.maxAttempts must be <= 20\"),\n initialBackoffMs: z.number().int().min(0).optional(),\n backoffCoefficient: z.number().min(1).optional(),\n maximumBackoffMs: z.number().int().min(0).optional(),\n nonRetryableErrors: z.array(z.string()).optional(),\n});\n\nconst WorkflowOptionsSchema = z.object({\n name: z.string().min(1).max(128),\n persistence: PersistenceSchema,\n // SE27 — declared so a future `new WorkflowBuilder(parsed)` refactor cannot\n // silently drop them (create() passes the ORIGINAL options today, but the\n // schema is also the documentation of the shape).\n inputSchema: z.custom<ZodType>().optional(),\n outputSchema: z.custom<ZodType>().optional(),\n});\n\n/* ─── Builder ─── */\n\nexport class WorkflowBuilder<TInput = unknown, TOutput = unknown> {\n private readonly _steps: Step[] = [];\n private _committed = false;\n\n /** @internal */\n constructor(private readonly options: WorkflowOptions) {}\n\n /** @internal — only the executor reads this. */\n get __steps(): ReadonlyArray<Step> {\n return this._steps;\n }\n\n // biome-ignore lint/suspicious/noThenProperty: D233 locks the a peer framework-style `.then(step)` builder DSL. The method is fluent, never awaited.\n then<TO = unknown>(step: Step): WorkflowBuilder<TInput, TO> {\n this.assertNotCommitted();\n validateStepId(step.id);\n this._steps.push(step);\n return this as unknown as WorkflowBuilder<TInput, TO>;\n }\n\n parallel(\n branches: ReadonlyArray<ReadonlyArray<Step>>,\n opts?: { id?: string; concurrency?: number; errorPolicy?: \"fail-fast\" | \"collect\" },\n ): WorkflowBuilder<TInput, unknown[]> {\n this.assertNotCommitted();\n const id = opts?.id ?? `parallel_${this._steps.length}`;\n validateStepId(id);\n for (const branch of branches) {\n for (const inner of branch) validateStepId(inner.id);\n }\n const step: ParallelStep = {\n kind: \"parallel\",\n id,\n branches,\n ...(opts?.concurrency !== undefined ? { concurrency: opts.concurrency } : {}),\n ...(opts?.errorPolicy !== undefined ? { errorPolicy: opts.errorPolicy } : {}),\n };\n this._steps.push(step);\n return this as unknown as WorkflowBuilder<TInput, unknown[]>;\n }\n\n branch(\n predicates: BranchStep[\"predicates\"],\n opts?: { id?: string; fallback?: ReadonlyArray<Step> },\n ): WorkflowBuilder<TInput, unknown> {\n this.assertNotCommitted();\n const id = opts?.id ?? `branch_${this._steps.length}`;\n validateStepId(id);\n const step: BranchStep = {\n kind: \"branch\",\n id,\n predicates,\n ...(opts?.fallback !== undefined ? { fallback: opts.fallback } : {}),\n };\n this._steps.push(step);\n return this as unknown as WorkflowBuilder<TInput, unknown>;\n }\n\n foreach(\n iterableFrom: string,\n step: Step,\n opts?: { id?: string; concurrency?: number },\n ): WorkflowBuilder<TInput, unknown[]> {\n this.assertNotCommitted();\n const id = opts?.id ?? `foreach_${this._steps.length}`;\n validateStepId(id);\n validateStepId(iterableFrom);\n validateStepId(step.id);\n const node: ForeachStep = {\n kind: \"foreach\",\n id,\n iterableFrom,\n step,\n ...(opts?.concurrency !== undefined ? { concurrency: opts.concurrency } : {}),\n };\n this._steps.push(node);\n return this as unknown as WorkflowBuilder<TInput, unknown[]>;\n }\n\n dowhile(\n step: Step,\n condFn: DowhileStep[\"condFn\"],\n opts?: { id?: string; maxIterations?: number },\n ): WorkflowBuilder<TInput, unknown> {\n this.assertNotCommitted();\n const id = opts?.id ?? `dowhile_${this._steps.length}`;\n validateStepId(id);\n validateStepId(step.id);\n const node: DowhileStep = {\n kind: \"dowhile\",\n id,\n step,\n condFn,\n ...(opts?.maxIterations !== undefined ? { maxIterations: opts.maxIterations } : {}),\n };\n this._steps.push(node);\n return this as unknown as WorkflowBuilder<TInput, unknown>;\n }\n\n sleep(durationMs: number, id?: string): WorkflowBuilder<TInput, TOutput> {\n this.assertNotCommitted();\n const stepId = id ?? `sleep_${this._steps.length}`;\n validateStepId(stepId);\n if (!Number.isFinite(durationMs) || durationMs < 0) {\n throw new Error(`sleep durationMs must be finite non-negative: ${durationMs}`);\n }\n const step: SleepStep = { kind: \"sleep\", id: stepId, durationMs };\n this._steps.push(step);\n return this;\n }\n\n suspend(opts?: { id?: string; payloadSchema?: ZodType }): WorkflowBuilder<TInput, unknown> {\n this.assertNotCommitted();\n const id = opts?.id ?? `suspend_${this._steps.length}`;\n validateStepId(id);\n const step: SuspendStep = {\n kind: \"suspend\",\n id,\n ...(opts?.payloadSchema !== undefined ? { payloadSchema: opts.payloadSchema } : {}),\n };\n this._steps.push(step);\n return this as unknown as WorkflowBuilder<TInput, unknown>;\n }\n\n commit(): Workflow<TInput, TOutput> {\n this.assertNotCommitted();\n this.validateUniqueIds();\n this._committed = true;\n // EC-5 absorbed: mint unique workflowId so single-flight lock is per-instance\n const workflowId = `wf-${mintShortId()}`;\n return new Workflow<TInput, TOutput>({ ...this.options, workflowId }, [...this._steps]);\n }\n\n private validateUniqueIds(): void {\n const seen = new Set<string>();\n walkStepsValidating(this._steps, seen);\n }\n\n private assertNotCommitted(): void {\n if (this._committed) {\n throw new Error(\"Workflow already committed; create a fresh Workflow.create(...) call.\");\n }\n }\n}\n\n/* ─── Workflow class ─── */\n\n/**\n * theokit#161 — project one step to its reflectable shape, recursing into the variants that nest.\n *\n * `parallel` branches are FLATTENED: the grouping is a scheduling detail (which steps may run\n * concurrently), not shape a reader of the workflow needs, and preserving it would put a second,\n * branch-shaped level into a type whose whole purpose is to be renderable.\n */\nfunction describeStep(step: Step): WorkflowStepDescription {\n const base = { id: step.id, kind: step.kind } as const;\n if (step.kind === \"parallel\") {\n return { ...base, steps: step.branches.flat().map(describeStep) };\n }\n if (step.kind === \"branch\") {\n const fromPredicates = step.predicates.flatMap(([, steps]) => steps.map(describeStep));\n const fromFallback = (step.fallback ?? []).map(describeStep);\n return { ...base, steps: [...fromPredicates, ...fromFallback] };\n }\n if (step.kind === \"foreach\" || step.kind === \"dowhile\") {\n return { ...base, steps: [describeStep(step.step)] };\n }\n return base;\n}\n\nexport class Workflow<TInput = unknown, TOutput = unknown> {\n /** @internal */\n constructor(\n private readonly _options: WorkflowOptions,\n private readonly _steps: ReadonlyArray<Step>,\n ) {}\n\n /** @internal — only the executor reads these. */\n get __options(): WorkflowOptions {\n return this._options;\n }\n /** @internal */\n get __steps(): ReadonlyArray<Step> {\n return this._steps;\n }\n\n /**\n * Construct a workflow builder. Validate options via Zod and return a\n * `WorkflowBuilder` for fluent chaining. Call `.commit()` to obtain the\n * immutable `Workflow`.\n */\n static create<TI = unknown, TO = unknown>(options: WorkflowOptions): WorkflowBuilder<TI, TO> {\n WorkflowOptionsSchema.parse(options);\n return new WorkflowBuilder<TI, TO>(options);\n }\n\n /**\n * theokit#161 — describe this workflow's shape, for a reflection surface.\n *\n * Returns `{ name, steps }`, each step carrying its `id` and `kind`, recursing into `parallel`,\n * `branch`, `foreach` and `dowhile`. Every executable a step holds — predicates, conditions,\n * agents, prompt templates — is omitted: it cannot cross a process boundary and says nothing about\n * shape.\n *\n * There is deliberately no `Workflow.list()`. A workflow is a value the caller constructs and\n * holds, so the caller already knows which ones exist; a registry would add process-global state\n * nothing releases in order to re-answer a question the host can answer itself. A reflection\n * endpoint maps over its own workflows and calls this.\n *\n * @public\n */\n describe(): WorkflowDescription {\n return {\n name: this._options.name,\n steps: this._steps.map(describeStep),\n };\n }\n\n /**\n * Run this workflow with the given input. Returns a populated\n * `WorkflowRun`. Errors inside a step DO NOT throw — they propagate via\n * `run.status === \"failed\"`.\n */\n async run(input: TInput, opts?: WorkflowRunOptions): Promise<WorkflowRun<TOutput>> {\n // Lazy import to keep the public façade lean.\n const { executeWorkflow } = await import(\"./internal/workflow/executor.js\");\n const result = await executeWorkflow<TInput, TOutput>(this._options, this._steps, input, opts);\n // T3.4: opt-in Task wrapping (ADRs D363, D374). Workflows are\n // observable via Task.list/get/subscribe; the underlying run is\n // already terminal here (executor returned), so the Task just\n // records the outcome for inspection.\n if (opts?.task !== undefined) {\n const { submit: taskSubmit } = await import(\"./internal/task/registry.js\");\n const taskOpts = opts.task === true ? {} : opts.task;\n const id = taskOpts.id ?? `wf-${result.id}`;\n await taskSubmit({\n kind: \"workflow\",\n work: async (ctx) => {\n ctx.emit({ status: result.status, runId: result.id });\n return { status: result.status, runId: result.id, output: result.output };\n },\n id,\n meta: {\n workflowName: this._options.name,\n runId: result.id,\n status: result.status,\n ...(taskOpts.meta ?? {}),\n },\n allowReservedPrefix: true,\n });\n }\n return result;\n }\n\n /**\n * SE28 — run the workflow and STREAM step-level events as they happen. Returns\n * an async iterator of {@link WorkflowEvent}s (`step_started` / `step_completed`\n * / `step_failed` / `workflow_suspended` / `workflow_completed`, top-level\n * steps) plus a `result` promise resolving to the same terminal\n * {@link WorkflowRun} `run()` returns. Iterate for progress; await `result` for\n * the outcome. The stream ends when the run terminates.\n *\n * `result` is the AUTHORITATIVE terminal status. Not every terminal state has a\n * closing event: a step failure emits `step_failed`, but an `outputSchema`\n * rejection (SE27) or an abort ends the stream WITHOUT `workflow_completed` —\n * always `await result` to read the final `status`. Consuming order is free:\n * awaiting `result` without draining, or draining without awaiting `result`,\n * both work (breaking out of `for await` stops the buffering early).\n */\n stream(input: TInput, opts?: WorkflowRunOptions): WorkflowStream<TOutput> {\n const queue = createEventStream();\n const result = (async (): Promise<WorkflowRun<TOutput>> => {\n const { executeWorkflow } = await import(\"./internal/workflow/executor.js\");\n try {\n return await executeWorkflow<TInput, TOutput>(this._options, this._steps, input, {\n ...opts,\n onStepEvent: (event: WorkflowEvent) => queue.push(event),\n } as WorkflowRunOptions);\n } finally {\n queue.end(); // authoritative terminal is `result`; close the stream\n }\n })();\n return Object.assign(queue, { result });\n }\n\n /**\n * Resume a suspended workflow from its snapshot. Throws\n * `WorkflowSnapshotNotFoundError` if `runId` is unknown.\n */\n static async resume<TO = unknown>(opts: WorkflowResumeOptions): Promise<WorkflowRun<TO>> {\n const { resumeWorkflow } = await import(\"./internal/workflow/executor.js\");\n return resumeWorkflow<TO>(opts);\n }\n}\n\n/* ─── Helper factory functions ─── */\n\n/**\n * Build a `FnStep`. `id` must match `^[a-z0-9][a-z0-9_-]*$`.\n */\nexport function fn<I = unknown, O = unknown>(\n id: string,\n step: (input: I, ctx: StepContext) => Promise<O> | O,\n opts?: { inputSchema?: ZodType; outputSchema?: ZodType; retry?: RetryPolicy },\n): FnStep {\n validateStepId(id);\n if (opts?.retry !== undefined) RetryPolicySchema.parse(opts.retry);\n return {\n kind: \"fn\",\n id,\n fn: step as FnStep[\"fn\"],\n ...(opts?.inputSchema !== undefined ? { inputSchema: opts.inputSchema } : {}),\n ...(opts?.outputSchema !== undefined ? { outputSchema: opts.outputSchema } : {}),\n ...(opts?.retry !== undefined ? { retry: opts.retry } : {}),\n };\n}\n\n/**\n * Build an `AgentStep`. The `promptTemplate` can be a static string or a\n * function that receives the input and returns the prompt.\n */\nexport function agentStep(\n id: string,\n agent: SDKAgent,\n promptTemplate: string | ((input: unknown) => string),\n opts?: { retry?: RetryPolicy; origin?: MessageOrigin },\n): AgentStep {\n validateStepId(id);\n if (opts?.retry !== undefined) RetryPolicySchema.parse(opts.retry);\n return {\n kind: \"agent\",\n id,\n agent,\n promptTemplate,\n ...(opts?.retry !== undefined ? { retry: opts.retry } : {}),\n // SE3 — carry the turn's provenance down to `agent.send()` (metadata-only).\n ...(opts?.origin !== undefined ? { origin: opts.origin } : {}),\n };\n}\n\n/**\n * SE30 — use a committed {@link Workflow} as a step inside another workflow.\n * Wraps the child as an `FnStep` (opaque — the child runs in its OWN executor\n * with its own id-space, so nested step-ids never collide with the parent's).\n * The child's output becomes the step output. A non-`completed` child fails the\n * parent step with a typed {@link WorkflowNestedError}: nested `suspended` is NOT\n * resumable in v1 (resume continues AFTER the step — the child would be skipped;\n * use a top-level suspend). See ADR 0010.\n *\n * @public\n */\nexport function workflowStep<TI = unknown, TO = unknown>(\n child: Workflow<TI, TO>,\n opts?: { id?: string },\n): FnStep {\n const id = opts?.id ?? `workflow_${child.__options.name}`;\n validateStepId(id);\n return {\n kind: \"fn\",\n id,\n fn: async (input: unknown, ctx: StepContext): Promise<unknown> => {\n const run = await child.run(input as TI, { signal: ctx.signal });\n if (run.status === \"completed\") return run.output;\n throw new WorkflowNestedError(id, child.__options.name, run.status, run.error);\n },\n };\n}\n\n/**\n * SE30 — clone a committed workflow under a new id/name. The clone runs\n * independently (its own single-flight lock + observability identity) with the\n * same committed steps. Mirrors a peer framework's `cloneWorkflow`.\n *\n * @public\n */\nexport function cloneWorkflow<TI = unknown, TO = unknown>(\n wf: Workflow<TI, TO>,\n opts: { id: string },\n): Workflow<TI, TO> {\n return new Workflow<TI, TO>(\n { ...wf.__options, name: opts.id, workflowId: `wf-${mintShortId()}` },\n [...wf.__steps],\n );\n}\n\n/* ─── Test seam re-export ─── */\n\nexport { __resetSnapshotStoresForTests } from \"./internal/workflow/snapshot-store.js\";\n\n/* ─── Re-exports for ergonomics (errors + all public types). After the\n sub-path extraction `@theokit/sdk/workflow` is the single import site,\n so type aliases must surface here (previously they reached consumers\n via `types/index.ts:25 export type * from \"./workflow.js\"`, which the\n extraction removes). ─── */\n\nexport type * from \"./types/workflow.js\";\nexport {\n WorkflowAlreadyRunningError,\n WorkflowCompensateNotImplementedError,\n WorkflowDuplicateStepIdError,\n WorkflowInputError,\n WorkflowMaxIterationsExceededError,\n WorkflowNestedError,\n WorkflowNotSerializableError,\n WorkflowOutputError,\n WorkflowParallelError,\n WorkflowResumeStepNotFoundError,\n WorkflowSnapshotNotFoundError,\n WorkflowStateError,\n} from \"./types/workflow.js\";\n\n/* ─── SE19 — workflowAsTool (expose a Workflow as an agent tool) ─── */\n\n/**\n * Raised by a {@link workflowAsTool} tool when the wrapped workflow run does not\n * reach `status: \"completed\"` (a step failed, the run was cancelled/suspended).\n * The dispatch converts it to a `tool_result(isError)`.\n *\n * @public\n */\nexport class WorkflowToolError extends Error {\n readonly code = \"workflow_tool_failed\" as const;\n constructor(\n readonly toolName: string,\n readonly workflowStatus: string,\n readonly workflowError?: { name: string; message: string },\n ) {\n super(\n `workflowAsTool(\"${toolName}\"): workflow ${workflowStatus}${\n workflowError ? `: ${workflowError.message}` : \"\"\n }`,\n );\n this.name = \"WorkflowToolError\";\n }\n}\n\n/** Spec for {@link workflowAsTool}. `inputSchema` is the workflow's input shape (Zod). */\nexport interface WorkflowAsToolSpec<T extends ZodType> {\n /** Tool name surfaced to the LLM. Same constraints as a `CustomTool.name`. */\n name: string;\n /** Description surfaced to the LLM — when the agent should trigger the workflow. */\n description: string;\n /** Zod schema for the workflow's input (a `Workflow` carries no top-level schema). */\n inputSchema: T;\n}\n\n/**\n * SE19 — expose a {@link Workflow} as an agent {@link CustomTool}, completing the\n * \"X as tools\" trio (tools; agents-as-tools via `defineSubAgent`; workflows-as-tools).\n * The handler validates the model's args against `spec.inputSchema`, runs the\n * workflow, and returns its output (a string as-is, else JSON). A run that does not\n * reach `status: \"completed\"` raises a typed {@link WorkflowToolError} (workflow\n * step errors do NOT throw — they surface via `run.status === \"failed\"`).\n *\n * Accepts any `{ run }`-shaped workflow (structural), so it never imports the\n * `Workflow` class directly.\n *\n * @public\n */\nexport function workflowAsTool<T extends ZodType, TOutput = unknown>(\n workflow: { run: (input: z.infer<T>) => Promise<WorkflowRun<TOutput>> },\n spec: WorkflowAsToolSpec<T>,\n): CustomTool {\n const inputSchema = toJsonSchema(spec.inputSchema, { unrepresentable: \"any\" });\n return {\n name: spec.name,\n description: spec.description,\n inputSchema,\n handler: async (rawInput: Record<string, unknown>): Promise<string> => {\n const parsed = spec.inputSchema.parse(rawInput) as z.infer<T>;\n const run = await workflow.run(parsed);\n if (run.status !== \"completed\") {\n throw new WorkflowToolError(spec.name, run.status, run.error);\n }\n const output = run.output;\n return typeof output === \"string\" ? output : JSON.stringify(output ?? null);\n },\n };\n}\n\n/* ─── Internal helpers ─── */\n\nfunction validateStepId(id: string): void {\n // Reuses D81 grammar: ^[a-z0-9][a-z0-9_-]*$\n sanitizeIdentifier(id, { maxLen: 64 });\n}\n\nfunction mintShortId(): string {\n return globalThis.crypto.randomUUID().replace(/-/g, \"\").slice(0, 8);\n}\n\nfunction nestedStepsOf(s: Step): ReadonlyArray<ReadonlyArray<Step>> {\n if (s.kind === \"parallel\") return s.branches;\n if (s.kind === \"branch\") {\n const groups = s.predicates.map(([, branch]) => branch);\n return s.fallback !== undefined ? [...groups, s.fallback] : groups;\n }\n if (s.kind === \"foreach\" || s.kind === \"dowhile\") return [[s.step]];\n return [];\n}\n\nfunction walkStepsValidating(steps: ReadonlyArray<Step>, seen: Set<string>): void {\n for (const s of steps) {\n if (seen.has(s.id)) throw new WorkflowDuplicateStepIdError(s.id);\n seen.add(s.id);\n for (const nested of nestedStepsOf(s)) {\n walkStepsValidating(nested, seen);\n }\n }\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/internal/workflow/event-stream.ts","../src/workflow.ts"],"names":[],"mappings":";;;;;;;AAgBO,SAAS,iBAAA,GAAyC;AACvD,EAAA,MAAM,SAA0B,EAAC;AACjC,EAAA,MAAM,UAA6D,EAAC;AACpE,EAAA,IAAI,KAAA,GAAQ,KAAA;AAEZ,EAAA,MAAM,MAAA,GAA8B;AAAA,IAClC,KAAK,KAAA,EAA4B;AAC/B,MAAA,IAAI,KAAA,EAAO;AACX,MAAA,MAAM,MAAA,GAAS,QAAQ,KAAA,EAAM;AAC7B,MAAA,IAAI,MAAA,KAAW,QAAW,MAAA,CAAO,EAAE,OAAO,KAAA,EAAO,IAAA,EAAM,OAAO,CAAA;AAAA,WACzD,MAAA,CAAO,KAAK,KAAK,CAAA;AAAA,IACxB,CAAA;AAAA,IACA,GAAA,GAAY;AACV,MAAA,IAAI,KAAA,EAAO;AACX,MAAA,KAAA,GAAQ,IAAA;AACR,MAAA,KAAA,MAAW,MAAA,IAAU,OAAA,CAAQ,MAAA,CAAO,CAAC,CAAA,EAAG,MAAA,CAAO,EAAE,KAAA,EAAO,MAAA,EAAW,IAAA,EAAM,IAAA,EAAM,CAAA;AAAA,IACjF,CAAA;AAAA,IACA,IAAA,GAA+C;AAC7C,MAAA,MAAM,QAAA,GAAW,OAAO,KAAA,EAAM;AAC9B,MAAA,IAAI,QAAA,KAAa,MAAA,EAAW,OAAO,OAAA,CAAQ,OAAA,CAAQ,EAAE,KAAA,EAAO,QAAA,EAAU,IAAA,EAAM,KAAA,EAAO,CAAA;AACnF,MAAA,IAAI,KAAA,SAAc,OAAA,CAAQ,OAAA,CAAQ,EAAE,KAAA,EAAO,MAAA,EAAW,IAA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ClE,EAAA,IAAI,CAAA,CAAE,IAAA,KAAS,UAAA,EAAY,OAAO,CAAA,CAAE,QAAA;AACpC,EAAA,IAAI,CAAA,CAAE,SAAS,QAAA,EAAU;AACvB,IAAA,MAAM,MAAA,GAAS,EAAE,UAAA,CAAW,GAAA,CAAI,CAAC,GAAG,MAAM,CAAA,KAAM,MAAM,CAAA;AACtD,IAAA,OAAO,CAAA,CAAE,aAAa,MAAA,GAAY,CAAC,GAAG,MAAA,EAAQ,CAAA,CAAE,QAAQ,CAAA,GAAI,MAAA;AAAA,EAC9D;AACA,EAAA,IAAI,CAAA,CAAE,IAAA,KAAS,SAAA,IAAa,CAAA,CAAE,IAAA,KAAS,SAAA,EAAW,OAAO,CAAC,CAAC,CAAA,CAAE,IAAI,CAAC,CAAA;AAClE,EAAA,OAAO,EAAC;AACV;AAEA,SAAS,mBAAA,CAAoB,OAA4B,IAAA,EAAyB;AAChF,EAAA,KAAA,MAAW,KAAK,KAAA,EAAO;AACrB,IAAA,IAAI,IAAA,CAAK,IAAI,CAAA,CAAE,EAAE,GAAG,MAAM,IAAI,4BAAA,CAA6B,CAAA,CAAE,EAAE,CAAA;AAC/D,IAAA,IAAA,CAAK,GAAA,CAAI,EAAE,EAAE,CAAA;AACb,IAAA,KAAA,MAAW,MAAA,IAAU,aAAA,CAAc,CAAC,CAAA,EAAG;AACrC,MAAA,mBAAA,CAAoB,QAAQ,IAAI,CAAA;AAAA,IAClC;AAAA,EACF;AACF","file":"chunk-R2A3WIJY.js","sourcesContent":["/**\n * SE28 — a minimal pushable async iterator for `Workflow.stream()`. The executor\n * pushes {@link WorkflowEvent}s as steps run; the consumer drains them via\n * `for await`. Buffers events emitted before the consumer is ready; `end()`\n * closes the iterator so a pending/next `next()` resolves `done: true`.\n *\n * @internal\n */\n\nimport type { WorkflowEvent } from \"../../types/workflow.js\";\n\nexport interface PushableEventStream extends AsyncIterableIterator<WorkflowEvent> {\n push(event: WorkflowEvent): void;\n end(): void;\n}\n\nexport function createEventStream(): PushableEventStream {\n const buffer: WorkflowEvent[] = [];\n const waiters: Array<(r: IteratorResult<WorkflowEvent>) => void> = [];\n let ended = false;\n\n const stream: PushableEventStream = {\n push(event: WorkflowEvent): void {\n if (ended) return;\n const waiter = waiters.shift();\n if (waiter !== undefined) waiter({ value: event, done: false });\n else buffer.push(event);\n },\n end(): void {\n if (ended) return;\n ended = true;\n for (const waiter of waiters.splice(0)) waiter({ value: undefined, done: true });\n },\n next(): Promise<IteratorResult<WorkflowEvent>> {\n const buffered = buffer.shift();\n if (buffered !== undefined) return Promise.resolve({ value: buffered, done: false });\n if (ended) return Promise.resolve({ value: undefined, done: true });\n return new Promise((resolve) => waiters.push(resolve));\n },\n // `for await` calls return() on break/throw — close early so events stop\n // buffering in memory for a consumer that stopped iterating.\n return(): Promise<IteratorResult<WorkflowEvent>> {\n stream.end();\n buffer.length = 0;\n return Promise.resolve({ value: undefined, done: true });\n },\n [Symbol.asyncIterator](): PushableEventStream {\n return stream;\n },\n };\n return stream;\n}\n","/**\n * Public `Workflow` class — declarative multi-step orchestration over\n * `Agent.send`, `Handoff`, `Agent.batch` and friends (Adoption Roadmap #5;\n * ADRs D230-D248).\n *\n * Usage:\n *\n * import { Agent } from \"@theokit/sdk\";\n * import { Workflow, fn, agentStep } from \"@theokit/sdk/workflow\";\n *\n * const classifier = await Agent.create({ ... });\n * const wf = Workflow.create({ name: \"demo\" })\n * .then(fn(\"validate\", (input: { id: string }) => {\n * if (!input.id) throw new Error(\"missing id\");\n * return input;\n * }))\n * .then(agentStep(\"classify\", classifier, (i) => `Classify: ${JSON.stringify(i)}`))\n * .commit();\n *\n * const run = await wf.run({ id: \"x\" });\n * console.log(run.status, run.output);\n *\n * @public\n */\n\nimport type { ZodType } from \"zod\";\nimport { z } from \"zod\";\nimport { PersistenceSchema } from \"./internal/persistence/persistence-schema.js\";\nimport { sanitizeIdentifier } from \"./internal/security/path-guard.js\";\nimport { createEventStream } from \"./internal/workflow/event-stream.js\";\nimport { toJsonSchema } from \"./internal/zod/to-json-schema.js\";\nimport type { CustomTool, SDKAgent } from \"./types/agent.js\";\nimport type { MessageOrigin } from \"./types/run.js\";\nimport type {\n AgentStep,\n BranchStep,\n DowhileStep,\n FnStep,\n ForeachStep,\n ParallelStep,\n RetryPolicy,\n SleepStep,\n Step,\n StepContext,\n SuspendStep,\n WorkflowDescription,\n WorkflowEvent,\n WorkflowOptions,\n WorkflowResumeOptions,\n WorkflowRun,\n WorkflowRunOptions,\n WorkflowStepDescription,\n WorkflowStream,\n} from \"./types/workflow.js\";\nimport { WorkflowDuplicateStepIdError, WorkflowNestedError } from \"./types/workflow.js\";\n\n/* ─── Zod validation schemas ─── */\n\nconst RetryPolicySchema = z.object({\n // EC-3 absorbed: maxAttempts MUST be a finite int in [1, 20].\n maxAttempts: z\n .number()\n .int(\"retry.maxAttempts must be integer\")\n .min(1, \"retry.maxAttempts must be >= 1\")\n .max(20, \"retry.maxAttempts must be <= 20\"),\n initialBackoffMs: z.number().int().min(0).optional(),\n backoffCoefficient: z.number().min(1).optional(),\n maximumBackoffMs: z.number().int().min(0).optional(),\n nonRetryableErrors: z.array(z.string()).optional(),\n});\n\nconst WorkflowOptionsSchema = z.object({\n name: z.string().min(1).max(128),\n persistence: PersistenceSchema,\n // SE27 — declared so a future `new WorkflowBuilder(parsed)` refactor cannot\n // silently drop them (create() passes the ORIGINAL options today, but the\n // schema is also the documentation of the shape).\n inputSchema: z.custom<ZodType>().optional(),\n outputSchema: z.custom<ZodType>().optional(),\n});\n\n/* ─── Builder ─── */\n\nexport class WorkflowBuilder<TInput = unknown, TOutput = unknown> {\n private readonly _steps: Step[] = [];\n private _committed = false;\n\n /** @internal */\n constructor(private readonly options: WorkflowOptions) {}\n\n /** @internal — only the executor reads this. */\n get __steps(): ReadonlyArray<Step> {\n return this._steps;\n }\n\n // biome-ignore lint/suspicious/noThenProperty: D233 locks the a peer framework-style `.then(step)` builder DSL. The method is fluent, never awaited.\n then<TO = unknown>(step: Step): WorkflowBuilder<TInput, TO> {\n this.assertNotCommitted();\n validateStepId(step.id);\n this._steps.push(step);\n return this as unknown as WorkflowBuilder<TInput, TO>;\n }\n\n parallel(\n branches: ReadonlyArray<ReadonlyArray<Step>>,\n opts?: { id?: string; concurrency?: number; errorPolicy?: \"fail-fast\" | \"collect\" },\n ): WorkflowBuilder<TInput, unknown[]> {\n this.assertNotCommitted();\n const id = opts?.id ?? `parallel_${this._steps.length}`;\n validateStepId(id);\n for (const branch of branches) {\n for (const inner of branch) validateStepId(inner.id);\n }\n const step: ParallelStep = {\n kind: \"parallel\",\n id,\n branches,\n ...(opts?.concurrency !== undefined ? { concurrency: opts.concurrency } : {}),\n ...(opts?.errorPolicy !== undefined ? { errorPolicy: opts.errorPolicy } : {}),\n };\n this._steps.push(step);\n return this as unknown as WorkflowBuilder<TInput, unknown[]>;\n }\n\n branch(\n predicates: BranchStep[\"predicates\"],\n opts?: { id?: string; fallback?: ReadonlyArray<Step> },\n ): WorkflowBuilder<TInput, unknown> {\n this.assertNotCommitted();\n const id = opts?.id ?? `branch_${this._steps.length}`;\n validateStepId(id);\n const step: BranchStep = {\n kind: \"branch\",\n id,\n predicates,\n ...(opts?.fallback !== undefined ? { fallback: opts.fallback } : {}),\n };\n this._steps.push(step);\n return this as unknown as WorkflowBuilder<TInput, unknown>;\n }\n\n foreach(\n iterableFrom: string,\n step: Step,\n opts?: { id?: string; concurrency?: number },\n ): WorkflowBuilder<TInput, unknown[]> {\n this.assertNotCommitted();\n const id = opts?.id ?? `foreach_${this._steps.length}`;\n validateStepId(id);\n validateStepId(iterableFrom);\n validateStepId(step.id);\n const node: ForeachStep = {\n kind: \"foreach\",\n id,\n iterableFrom,\n step,\n ...(opts?.concurrency !== undefined ? { concurrency: opts.concurrency } : {}),\n };\n this._steps.push(node);\n return this as unknown as WorkflowBuilder<TInput, unknown[]>;\n }\n\n dowhile(\n step: Step,\n condFn: DowhileStep[\"condFn\"],\n opts?: { id?: string; maxIterations?: number },\n ): WorkflowBuilder<TInput, unknown> {\n this.assertNotCommitted();\n const id = opts?.id ?? `dowhile_${this._steps.length}`;\n validateStepId(id);\n validateStepId(step.id);\n const node: DowhileStep = {\n kind: \"dowhile\",\n id,\n step,\n condFn,\n ...(opts?.maxIterations !== undefined ? { maxIterations: opts.maxIterations } : {}),\n };\n this._steps.push(node);\n return this as unknown as WorkflowBuilder<TInput, unknown>;\n }\n\n sleep(durationMs: number, id?: string): WorkflowBuilder<TInput, TOutput> {\n this.assertNotCommitted();\n const stepId = id ?? `sleep_${this._steps.length}`;\n validateStepId(stepId);\n if (!Number.isFinite(durationMs) || durationMs < 0) {\n throw new Error(`sleep durationMs must be finite non-negative: ${durationMs}`);\n }\n const step: SleepStep = { kind: \"sleep\", id: stepId, durationMs };\n this._steps.push(step);\n return this;\n }\n\n suspend(opts?: { id?: string; payloadSchema?: ZodType }): WorkflowBuilder<TInput, unknown> {\n this.assertNotCommitted();\n const id = opts?.id ?? `suspend_${this._steps.length}`;\n validateStepId(id);\n const step: SuspendStep = {\n kind: \"suspend\",\n id,\n ...(opts?.payloadSchema !== undefined ? { payloadSchema: opts.payloadSchema } : {}),\n };\n this._steps.push(step);\n return this as unknown as WorkflowBuilder<TInput, unknown>;\n }\n\n commit(): Workflow<TInput, TOutput> {\n this.assertNotCommitted();\n this.validateUniqueIds();\n this._committed = true;\n // EC-5 absorbed: mint unique workflowId so single-flight lock is per-instance\n const workflowId = `wf-${mintShortId()}`;\n return new Workflow<TInput, TOutput>({ ...this.options, workflowId }, [...this._steps]);\n }\n\n private validateUniqueIds(): void {\n const seen = new Set<string>();\n walkStepsValidating(this._steps, seen);\n }\n\n private assertNotCommitted(): void {\n if (this._committed) {\n throw new Error(\"Workflow already committed; create a fresh Workflow.create(...) call.\");\n }\n }\n}\n\n/* ─── Workflow class ─── */\n\n/**\n * theokit#161 — project one step to its reflectable shape, recursing into the variants that nest.\n *\n * `parallel` branches are FLATTENED: the grouping is a scheduling detail (which steps may run\n * concurrently), not shape a reader of the workflow needs, and preserving it would put a second,\n * branch-shaped level into a type whose whole purpose is to be renderable.\n */\nfunction describeStep(step: Step): WorkflowStepDescription {\n const base = { id: step.id, kind: step.kind } as const;\n if (step.kind === \"parallel\") {\n return { ...base, steps: step.branches.flat().map(describeStep) };\n }\n if (step.kind === \"branch\") {\n const fromPredicates = step.predicates.flatMap(([, steps]) => steps.map(describeStep));\n const fromFallback = (step.fallback ?? []).map(describeStep);\n return { ...base, steps: [...fromPredicates, ...fromFallback] };\n }\n if (step.kind === \"foreach\" || step.kind === \"dowhile\") {\n return { ...base, steps: [describeStep(step.step)] };\n }\n return base;\n}\n\nexport class Workflow<TInput = unknown, TOutput = unknown> {\n /** @internal */\n constructor(\n private readonly _options: WorkflowOptions,\n private readonly _steps: ReadonlyArray<Step>,\n ) {}\n\n /** @internal — only the executor reads these. */\n get __options(): WorkflowOptions {\n return this._options;\n }\n /** @internal */\n get __steps(): ReadonlyArray<Step> {\n return this._steps;\n }\n\n /**\n * Construct a workflow builder. Validate options via Zod and return a\n * `WorkflowBuilder` for fluent chaining. Call `.commit()` to obtain the\n * immutable `Workflow`.\n */\n static create<TI = unknown, TO = unknown>(options: WorkflowOptions): WorkflowBuilder<TI, TO> {\n WorkflowOptionsSchema.parse(options);\n return new WorkflowBuilder<TI, TO>(options);\n }\n\n /**\n * theokit#161 — describe this workflow's shape, for a reflection surface.\n *\n * Returns `{ name, steps }`, each step carrying its `id` and `kind`, recursing into `parallel`,\n * `branch`, `foreach` and `dowhile`. Every executable a step holds — predicates, conditions,\n * agents, prompt templates — is omitted: it cannot cross a process boundary and says nothing about\n * shape.\n *\n * There is deliberately no `Workflow.list()`. A workflow is a value the caller constructs and\n * holds, so the caller already knows which ones exist; a registry would add process-global state\n * nothing releases in order to re-answer a question the host can answer itself. A reflection\n * endpoint maps over its own workflows and calls this.\n *\n * @public\n */\n describe(): WorkflowDescription {\n return {\n name: this._options.name,\n steps: this._steps.map(describeStep),\n };\n }\n\n /**\n * Run this workflow with the given input. Returns a populated\n * `WorkflowRun`. Errors inside a step DO NOT throw — they propagate via\n * `run.status === \"failed\"`.\n */\n async run(input: TInput, opts?: WorkflowRunOptions): Promise<WorkflowRun<TOutput>> {\n // Lazy import to keep the public façade lean.\n const { executeWorkflow } = await import(\"./internal/workflow/executor.js\");\n const result = await executeWorkflow<TInput, TOutput>(this._options, this._steps, input, opts);\n // T3.4: opt-in Task wrapping (ADRs D363, D374). Workflows are\n // observable via Task.list/get/subscribe; the underlying run is\n // already terminal here (executor returned), so the Task just\n // records the outcome for inspection.\n if (opts?.task !== undefined) {\n const { submit: taskSubmit } = await import(\"./internal/task/registry.js\");\n const taskOpts = opts.task === true ? {} : opts.task;\n const id = taskOpts.id ?? `wf-${result.id}`;\n await taskSubmit({\n kind: \"workflow\",\n work: async (ctx) => {\n ctx.emit({ status: result.status, runId: result.id });\n return { status: result.status, runId: result.id, output: result.output };\n },\n id,\n meta: {\n workflowName: this._options.name,\n runId: result.id,\n status: result.status,\n ...(taskOpts.meta ?? {}),\n },\n allowReservedPrefix: true,\n });\n }\n return result;\n }\n\n /**\n * SE28 — run the workflow and STREAM step-level events as they happen. Returns\n * an async iterator of {@link WorkflowEvent}s (`step_started` / `step_completed`\n * / `step_failed` / `workflow_suspended` / `workflow_completed`, top-level\n * steps) plus a `result` promise resolving to the same terminal\n * {@link WorkflowRun} `run()` returns. Iterate for progress; await `result` for\n * the outcome. The stream ends when the run terminates.\n *\n * `result` is the AUTHORITATIVE terminal status. Not every terminal state has a\n * closing event: a step failure emits `step_failed`, but an `outputSchema`\n * rejection (SE27) or an abort ends the stream WITHOUT `workflow_completed` —\n * always `await result` to read the final `status`. Consuming order is free:\n * awaiting `result` without draining, or draining without awaiting `result`,\n * both work (breaking out of `for await` stops the buffering early).\n */\n stream(input: TInput, opts?: WorkflowRunOptions): WorkflowStream<TOutput> {\n const queue = createEventStream();\n const result = (async (): Promise<WorkflowRun<TOutput>> => {\n const { executeWorkflow } = await import(\"./internal/workflow/executor.js\");\n try {\n return await executeWorkflow<TInput, TOutput>(this._options, this._steps, input, {\n ...opts,\n onStepEvent: (event: WorkflowEvent) => queue.push(event),\n } as WorkflowRunOptions);\n } finally {\n queue.end(); // authoritative terminal is `result`; close the stream\n }\n })();\n return Object.assign(queue, { result });\n }\n\n /**\n * Resume a suspended workflow from its snapshot. Throws\n * `WorkflowSnapshotNotFoundError` if `runId` is unknown.\n */\n static async resume<TO = unknown>(opts: WorkflowResumeOptions): Promise<WorkflowRun<TO>> {\n const { resumeWorkflow } = await import(\"./internal/workflow/executor.js\");\n return resumeWorkflow<TO>(opts);\n }\n}\n\n/* ─── Helper factory functions ─── */\n\n/**\n * Build a `FnStep`. `id` must match `^[a-z0-9][a-z0-9_-]*$`.\n */\nexport function fn<I = unknown, O = unknown>(\n id: string,\n step: (input: I, ctx: StepContext) => Promise<O> | O,\n opts?: { inputSchema?: ZodType; outputSchema?: ZodType; retry?: RetryPolicy },\n): FnStep {\n validateStepId(id);\n if (opts?.retry !== undefined) RetryPolicySchema.parse(opts.retry);\n return {\n kind: \"fn\",\n id,\n fn: step as FnStep[\"fn\"],\n ...(opts?.inputSchema !== undefined ? { inputSchema: opts.inputSchema } : {}),\n ...(opts?.outputSchema !== undefined ? { outputSchema: opts.outputSchema } : {}),\n ...(opts?.retry !== undefined ? { retry: opts.retry } : {}),\n };\n}\n\n/**\n * Build an `AgentStep`. The `promptTemplate` can be a static string or a\n * function that receives the input and returns the prompt.\n */\nexport function agentStep(\n id: string,\n agent: SDKAgent,\n promptTemplate: string | ((input: unknown) => string),\n opts?: { retry?: RetryPolicy; origin?: MessageOrigin },\n): AgentStep {\n validateStepId(id);\n if (opts?.retry !== undefined) RetryPolicySchema.parse(opts.retry);\n return {\n kind: \"agent\",\n id,\n agent,\n promptTemplate,\n ...(opts?.retry !== undefined ? { retry: opts.retry } : {}),\n // SE3 — carry the turn's provenance down to `agent.send()` (metadata-only).\n ...(opts?.origin !== undefined ? { origin: opts.origin } : {}),\n };\n}\n\n/**\n * SE30 — use a committed {@link Workflow} as a step inside another workflow.\n * Wraps the child as an `FnStep` (opaque — the child runs in its OWN executor\n * with its own id-space, so nested step-ids never collide with the parent's).\n * The child's output becomes the step output. A non-`completed` child fails the\n * parent step with a typed {@link WorkflowNestedError}: nested `suspended` is NOT\n * resumable in v1 (resume continues AFTER the step — the child would be skipped;\n * use a top-level suspend). See ADR 0010.\n *\n * @public\n */\nexport function workflowStep<TI = unknown, TO = unknown>(\n child: Workflow<TI, TO>,\n opts?: { id?: string },\n): FnStep {\n const id = opts?.id ?? `workflow_${child.__options.name}`;\n validateStepId(id);\n return {\n kind: \"fn\",\n id,\n fn: async (input: unknown, ctx: StepContext): Promise<unknown> => {\n const run = await child.run(input as TI, { signal: ctx.signal });\n if (run.status === \"completed\") return run.output;\n throw new WorkflowNestedError(id, child.__options.name, run.status, run.error);\n },\n };\n}\n\n/**\n * SE30 — clone a committed workflow under a new id/name. The clone runs\n * independently (its own single-flight lock + observability identity) with the\n * same committed steps. Mirrors a peer framework's `cloneWorkflow`.\n *\n * @public\n */\nexport function cloneWorkflow<TI = unknown, TO = unknown>(\n wf: Workflow<TI, TO>,\n opts: { id: string },\n): Workflow<TI, TO> {\n return new Workflow<TI, TO>(\n { ...wf.__options, name: opts.id, workflowId: `wf-${mintShortId()}` },\n [...wf.__steps],\n );\n}\n\n/* ─── Test seam re-export ─── */\n\nexport { __resetSnapshotStoresForTests } from \"./internal/workflow/snapshot-store.js\";\n\n/* ─── Re-exports for ergonomics (errors + all public types). After the\n sub-path extraction `@theokit/sdk/workflow` is the single import site,\n so type aliases must surface here (previously they reached consumers\n via `types/index.ts:25 export type * from \"./workflow.js\"`, which the\n extraction removes). ─── */\n\nexport type * from \"./types/workflow.js\";\nexport {\n WorkflowAlreadyRunningError,\n WorkflowCompensateNotImplementedError,\n WorkflowDuplicateStepIdError,\n WorkflowInputError,\n WorkflowMaxIterationsExceededError,\n WorkflowNestedError,\n WorkflowNotSerializableError,\n WorkflowOutputError,\n WorkflowParallelError,\n WorkflowResumeStepNotFoundError,\n WorkflowSnapshotNotFoundError,\n WorkflowStateError,\n} from \"./types/workflow.js\";\n\n/* ─── SE19 — workflowAsTool (expose a Workflow as an agent tool) ─── */\n\n/**\n * Raised by a {@link workflowAsTool} tool when the wrapped workflow run does not\n * reach `status: \"completed\"` (a step failed, the run was cancelled/suspended).\n * The dispatch converts it to a `tool_result(isError)`.\n *\n * @public\n */\nexport class WorkflowToolError extends Error {\n readonly code = \"workflow_tool_failed\" as const;\n constructor(\n readonly toolName: string,\n readonly workflowStatus: string,\n readonly workflowError?: { name: string; message: string },\n ) {\n super(\n `workflowAsTool(\"${toolName}\"): workflow ${workflowStatus}${\n workflowError ? `: ${workflowError.message}` : \"\"\n }`,\n );\n this.name = \"WorkflowToolError\";\n }\n}\n\n/** Spec for {@link workflowAsTool}. `inputSchema` is the workflow's input shape (Zod). */\nexport interface WorkflowAsToolSpec<T extends ZodType> {\n /** Tool name surfaced to the LLM. Same constraints as a `CustomTool.name`. */\n name: string;\n /** Description surfaced to the LLM — when the agent should trigger the workflow. */\n description: string;\n /** Zod schema for the workflow's input (a `Workflow` carries no top-level schema). */\n inputSchema: T;\n}\n\n/**\n * SE19 — expose a {@link Workflow} as an agent {@link CustomTool}, completing the\n * \"X as tools\" trio (tools; agents-as-tools via `defineSubAgent`; workflows-as-tools).\n * The handler validates the model's args against `spec.inputSchema`, runs the\n * workflow, and returns its output (a string as-is, else JSON). A run that does not\n * reach `status: \"completed\"` raises a typed {@link WorkflowToolError} (workflow\n * step errors do NOT throw — they surface via `run.status === \"failed\"`).\n *\n * Accepts any `{ run }`-shaped workflow (structural), so it never imports the\n * `Workflow` class directly.\n *\n * @public\n */\nexport function workflowAsTool<T extends ZodType, TOutput = unknown>(\n workflow: { run: (input: z.infer<T>) => Promise<WorkflowRun<TOutput>> },\n spec: WorkflowAsToolSpec<T>,\n): CustomTool {\n const inputSchema = toJsonSchema(spec.inputSchema, { unrepresentable: \"any\" });\n return {\n name: spec.name,\n description: spec.description,\n inputSchema,\n handler: async (rawInput: Record<string, unknown>): Promise<string> => {\n const parsed = spec.inputSchema.parse(rawInput) as z.infer<T>;\n const run = await workflow.run(parsed);\n if (run.status !== \"completed\") {\n throw new WorkflowToolError(spec.name, run.status, run.error);\n }\n const output = run.output;\n return typeof output === \"string\" ? output : JSON.stringify(output ?? null);\n },\n };\n}\n\n/* ─── Internal helpers ─── */\n\nfunction validateStepId(id: string): void {\n // Reuses D81 grammar: ^[a-z0-9][a-z0-9_-]*$\n sanitizeIdentifier(id, { maxLen: 64 });\n}\n\nfunction mintShortId(): string {\n return globalThis.crypto.randomUUID().replace(/-/g, \"\").slice(0, 8);\n}\n\nfunction nestedStepsOf(s: Step): ReadonlyArray<ReadonlyArray<Step>> {\n if (s.kind === \"parallel\") return s.branches;\n if (s.kind === \"branch\") {\n const groups = s.predicates.map(([, branch]) => branch);\n return s.fallback !== undefined ? [...groups, s.fallback] : groups;\n }\n if (s.kind === \"foreach\" || s.kind === \"dowhile\") return [[s.step]];\n return [];\n}\n\nfunction walkStepsValidating(steps: ReadonlyArray<Step>, seen: Set<string>): void {\n for (const s of steps) {\n if (seen.has(s.id)) throw new WorkflowDuplicateStepIdError(s.id);\n seen.add(s.id);\n for (const nested of nestedStepsOf(s)) {\n walkStepsValidating(nested, seen);\n }\n }\n}\n"]}
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import { realpathSync } from 'fs';
|
|
2
|
+
import { relative, isAbsolute } from 'path';
|
|
3
|
+
|
|
4
|
+
// src/internal/runtime/context/path-containment.ts
|
|
5
|
+
function realOrResolved(path) {
|
|
6
|
+
try {
|
|
7
|
+
return realpathSync(path);
|
|
8
|
+
} catch {
|
|
9
|
+
return path;
|
|
10
|
+
}
|
|
11
|
+
}
|
|
12
|
+
function insideRoot(target, root) {
|
|
13
|
+
const rel = relative(realOrResolved(root), realOrResolved(target));
|
|
14
|
+
return rel !== "" && !rel.startsWith("..") && !isAbsolute(rel);
|
|
15
|
+
}
|
|
16
|
+
function atOrInsideRoot(target, root) {
|
|
17
|
+
return insideRoot(target, root) || realOrResolved(target) === realOrResolved(root);
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
export { atOrInsideRoot, insideRoot };
|
|
21
|
+
//# sourceMappingURL=chunk-RIAM53CP.js.map
|
|
22
|
+
//# sourceMappingURL=chunk-RIAM53CP.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/internal/runtime/context/path-containment.ts"],"names":[],"mappings":";;;;AAoCO,SAAS,eAAe,IAAA,EAAsB;AACnD,EAAA,IAAI;AACF,IAAA,OAAO,aAAa,IAAI,CAAA;AAAA,EAC1B,CAAA,CAAA,MAAQ;AACN,IAAA,OAAO,IAAA;AAAA,EACT;AACF;AAUO,SAAS,UAAA,CAAW,QAAgB,IAAA,EAAuB;AAChE,EAAA,MAAM,MAAM,QAAA,CAAS,cAAA,CAAe,IAAI,CAAA,EAAG,cAAA,CAAe,MAAM,CAAC,CAAA;AACjE,EAAA,OAAO,GAAA,KAAQ,MAAM,CAAC,GAAA,CAAI,WAAW,IAAI,CAAA,IAAK,CAAC,UAAA,CAAW,GAAG,CAAA;AAC/D;AAgBO,SAAS,cAAA,CAAe,QAAgB,IAAA,EAAuB;AACpE,EAAA,OAAO,UAAA,CAAW,QAAQ,IAAI,CAAA,IAAK,eAAe,MAAM,CAAA,KAAM,eAAe,IAAI,CAAA;AACnF","file":"chunk-RIAM53CP.js","sourcesContent":["/**\n * The one rule for \"is this resolved path inside that root\".\n *\n * Extracted because the package held it twice, at different strengths, for the same question. The\n * correct version lived as a private function in `context-import-resolver.ts`, written for the\n * 4.41.1 patch; the context manager had its own `absolute.startsWith(resolvePath(cwd))`, which\n * admits two escapes:\n *\n * - **No separator boundary.** With `root = /home/user/proj`, the path `/home/user/proj-evil/x`\n * starts with the root string and is NOT inside it. A sibling directory whose name merely\n * extends the project's is enough; no `..` past the parent is needed.\n * - **Lexical, not real.** A symlink whose name sits inside the root and whose target does not\n * passes any comparison made before symlink resolution.\n *\n * The obvious escapes (`../../etc/passwd`, an absolute path) ARE refused by a prefix test, which is\n * why the weaker version survived review: it looks like it works on the inputs a reader tries.\n *\n * Both readers of repository-supplied paths now share this module. That is DRY about the RULE\n * rather than about line count — one piece of knowledge, one representation, so the two cannot\n * drift apart again.\n *\n * @internal\n */\n\nimport { realpathSync } from \"node:fs\";\nimport { isAbsolute, relative } from \"node:path\";\n\n/**\n * The real path, or the lexical one when it cannot be resolved.\n *\n * The fallback is load-bearing rather than defensive: the context manager checks containment BEFORE\n * it stats the file, so a source that is legitimately absent must still be judged on its declared\n * location instead of being refused for the wrong reason.\n *\n * @internal\n */\nexport function realOrResolved(path: string): string {\n try {\n return realpathSync(path);\n } catch {\n return path;\n }\n}\n\n/**\n * Whether `target` is inside `root`, compared AFTER symlink resolution.\n *\n * `relative()` supplies the separator boundary that a prefix test lacks: it answers `..` for a\n * sibling, `''` for the root itself, and an absolute path when the two are on different roots.\n *\n * @internal\n */\nexport function insideRoot(target: string, root: string): boolean {\n const rel = relative(realOrResolved(root), realOrResolved(target));\n return rel !== \"\" && !rel.startsWith(\"..\") && !isAbsolute(rel);\n}\n\n/**\n * Whether `target` is the root ITSELF or inside it, compared after symlink resolution.\n *\n * Separate from {@link insideRoot} because the two answer a genuinely different question and their\n * callers need different ones. The context manager asks \"is this source under the project?\", where\n * the project directory itself is not a source. A path JOIN asks \"did this stay within its base?\",\n * where joining nothing and getting the base back is the ordinary case — `safePathJoin(base)` must\n * return `base`.\n *\n * Named here rather than written out at each call site: it appeared twice within one change, which\n * is how this rule ended up with three copies at three strengths the first time.\n *\n * @internal\n */\nexport function atOrInsideRoot(target: string, root: string): boolean {\n return insideRoot(target, root) || realOrResolved(target) === realOrResolved(root);\n}\n"]}
|
|
@@ -4,7 +4,7 @@ var chunk2RW7K6FN_cjs = require('./chunk-2RW7K6FN.cjs');
|
|
|
4
4
|
var chunkBV42CCRP_cjs = require('./chunk-BV42CCRP.cjs');
|
|
5
5
|
var chunkYLQQX5W2_cjs = require('./chunk-YLQQX5W2.cjs');
|
|
6
6
|
var chunkNETYW4V3_cjs = require('./chunk-NETYW4V3.cjs');
|
|
7
|
-
var
|
|
7
|
+
var chunkXABN5HY6_cjs = require('./chunk-XABN5HY6.cjs');
|
|
8
8
|
var chunkYULF6FPB_cjs = require('./chunk-YULF6FPB.cjs');
|
|
9
9
|
var chunkZHPET3LZ_cjs = require('./chunk-ZHPET3LZ.cjs');
|
|
10
10
|
var crypto = require('crypto');
|
|
@@ -72,7 +72,7 @@ function defaultIndexPath(cwd) {
|
|
|
72
72
|
}
|
|
73
73
|
function requireLance() {
|
|
74
74
|
try {
|
|
75
|
-
const r = module$1.createRequire((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('chunk-
|
|
75
|
+
const r = module$1.createRequire((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('chunk-RWMNTFHZ.cjs', document.baseURI).href)));
|
|
76
76
|
return r("@lancedb/lancedb");
|
|
77
77
|
} catch (cause) {
|
|
78
78
|
throw new chunkYULF6FPB_cjs.ConfigurationError(
|
|
@@ -299,10 +299,10 @@ function legacyMemoryJsonPath(cwd, config) {
|
|
|
299
299
|
if (config.storePath !== void 0) {
|
|
300
300
|
return path.resolve(cwd, config.storePath);
|
|
301
301
|
}
|
|
302
|
-
const namespace =
|
|
303
|
-
const scope =
|
|
304
|
-
const userId =
|
|
305
|
-
return
|
|
302
|
+
const namespace = chunkXABN5HY6_cjs.sanitizeIdentifier(config.namespace ?? "default");
|
|
303
|
+
const scope = chunkXABN5HY6_cjs.sanitizeIdentifier(config.scope ?? "agent", { maxLen: 16 });
|
|
304
|
+
const userId = chunkXABN5HY6_cjs.sanitizeIdentifier(config.userId ?? "default");
|
|
305
|
+
return chunkXABN5HY6_cjs.safePathJoin(cwd, ".theokit", "memory", namespace, `${scope}-${userId}.json`);
|
|
306
306
|
}
|
|
307
307
|
|
|
308
308
|
// src/internal/memory/storage/markdown-store.ts
|
|
@@ -391,7 +391,7 @@ function sessionsDir(cwd) {
|
|
|
391
391
|
return path.join(memoryDir(cwd), "sessions");
|
|
392
392
|
}
|
|
393
393
|
function sessionSummaryPath(cwd, runId) {
|
|
394
|
-
return path.join(sessionsDir(cwd), `${
|
|
394
|
+
return path.join(sessionsDir(cwd), `${chunkXABN5HY6_cjs.safeFilenameForId(runId, { maxLen: 128 })}.md`);
|
|
395
395
|
}
|
|
396
396
|
function truncate(text) {
|
|
397
397
|
if (text.length <= MAX_TURN_CHARS) return text;
|
|
@@ -978,5 +978,5 @@ exports.openMemoryDb = openMemoryDb;
|
|
|
978
978
|
exports.readFacts = readFacts;
|
|
979
979
|
exports.readFactsFromMarkdown = readFactsFromMarkdown;
|
|
980
980
|
exports.writeSessionSummary = writeSessionSummary;
|
|
981
|
-
//# sourceMappingURL=chunk-
|
|
982
|
-
//# sourceMappingURL=chunk-
|
|
981
|
+
//# sourceMappingURL=chunk-RWMNTFHZ.cjs.map
|
|
982
|
+
//# sourceMappingURL=chunk-RWMNTFHZ.cjs.map
|