@elisym/sdk 0.22.0 → 0.24.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/dist/node.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/primitives/encryption.ts","../src/agent-store/writer.ts","../src/config/global-schema.ts","../src/config/global.ts"],"names":["randomBytes","YAML"],"mappings":";;;;;;;;AAcA,IAAM,MAAA,GAAS,eAAA;AACf,IAAM,WAAA,GAAc,EAAA;AACpB,IAAM,SAAA,GAAY,EAAA;AAClB,IAAM,UAAA,GAAa,EAAA;AACnB,IAAM,UAAA,GAAa,EAAA;AAEnB,IAAM,WAAW,CAAA,IAAK,EAAA;AACtB,IAAM,QAAA,GAAW,CAAA;AACjB,IAAM,QAAA,GAAW,CAAA;AACjB,IAAM,aAAA,GAAgB,GAAA,GAAM,QAAA,GAAW,QAAA,GAAW,CAAA;AAG3C,SAAS,YAAY,KAAA,EAAwB;AAClD,EAAA,OAAO,KAAA,CAAM,WAAW,MAAM,CAAA;AAChC;AAGO,SAAS,aAAA,CAAc,WAAmB,UAAA,EAA4B;AAC3E,EAAA,IAAI,CAAC,UAAA,EAAY;AACf,IAAA,MAAM,IAAI,MAAM,+BAA+B,CAAA;AAAA,EACjD;AAEA,EAAA,MAAM,IAAA,GAAO,YAAY,WAAW,CAAA;AACpC,EAAA,MAAM,GAAA,GAAM,UAAA,CAAW,UAAA,EAAY,IAAA,EAAM,UAAA,EAAY;AAAA,IACnD,CAAA,EAAG,QAAA;AAAA,IACH,CAAA,EAAG,QAAA;AAAA,IACH,CAAA,EAAG,QAAA;AAAA,IACH,MAAA,EAAQ;AAAA,GACT,CAAA;AACD,EAAA,MAAM,EAAA,GAAK,YAAY,SAAS,CAAA;AAEhC,EAAA,MAAM,MAAA,GAAS,cAAA,CAAe,aAAA,EAAe,GAAA,EAAK,EAAE,CAAA;AACpD,EAAA,MAAM,SAAA,GAAY,MAAA,CAAO,MAAA,CAAO,C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AA,CAAmB,KAAA,CAAM,MAAA,IAAU,EAAE,CAAA;AAC9C;AAGA,eAAsB,iBAAA,CAAkB,MAAc,MAAA,EAAqC;AACzF,EAAA,MAAM,SAAA,GAAY,kBAAA,CAAmB,KAAA,CAAM,MAAM,CAAA;AACjD,EAAA,MAAM,IAAA,GAAOA,KAAAA,CAAK,SAAA,CAAU,SAAS,CAAA;AACrC,EAAA,MAAM,eAAA,CAAgB,IAAA,EAAM,IAAA,EAAM,GAAK,CAAA;AACzC","file":"node.js","sourcesContent":["/**\n * Secret encryption/decryption for agent config files.\n * Uses scrypt (KDF) + AES-256-GCM (cipher).\n * Format: \"encrypted:v1:\" + base64(salt[16] + iv[12] + ciphertext + tag[16])\n *\n * scrypt params: N=2^17, r=8, p=1 (~128 MB RAM per derivation).\n *\n * Node.js/Bun only - not available in browsers. Reachable only via the\n * '@elisym/sdk/node' subpath, which browser bundlers will not resolve.\n */\n\nimport { Buffer } from 'node:buffer';\nimport { createCipheriv, createDecipheriv, randomBytes, scryptSync } from 'node:crypto';\n\nconst PREFIX = 'encrypted:v1:';\nconst SALT_LENGTH = 16;\nconst IV_LENGTH = 12;\nconst TAG_LENGTH = 16;\nconst KEY_LENGTH = 32; // AES-256\n// v1: N=2^17 (OWASP minimum). v2 will use N=2^20 with format migration.\nconst SCRYPT_N = 2 ** 17;\nconst SCRYPT_R = 8;\nconst SCRYPT_P = 1;\nconst SCRYPT_MAXMEM = 128 * SCRYPT_N * SCRYPT_R * 2; // 2x the minimum required memory\n\n/** Check if a value is encrypted (has the encrypted:v1: prefix). */\nexport function isEncrypted(value: string): boolean {\n return value.startsWith(PREFIX);\n}\n\n/** Encrypt a plaintext secret with a passphrase. Returns \"encrypted:v1:base64...\". Node.js/Bun only. */\nexport function encryptSecret(plaintext: string, passphrase: string): string {\n if (!passphrase) {\n throw new Error('Passphrase must not be empty.');\n }\n\n const salt = randomBytes(SALT_LENGTH);\n const key = scryptSync(passphrase, salt, KEY_LENGTH, {\n N: SCRYPT_N,\n r: SCRYPT_R,\n p: SCRYPT_P,\n maxmem: SCRYPT_MAXMEM,\n });\n const iv = randomBytes(IV_LENGTH);\n\n const cipher = createCipheriv('aes-256-gcm', key, iv);\n const encrypted = Buffer.concat([cipher.update(plaintext, 'utf8'), cipher.final()]);\n const tag = cipher.getAuthTag();\n\n const payload = Buffer.concat([salt, iv, encrypted, tag]);\n return PREFIX + payload.toString('base64');\n}\n\n/** Decrypt an encrypted secret with a passphrase. Throws on wrong passphrase or corrupted data. Node.js/Bun only. */\nexport function decryptSecret(encrypted: string, passphrase: string): string {\n if (!isEncrypted(encrypted)) {\n throw new Error('Value is not encrypted (missing encrypted:v1: prefix).');\n }\n if (!passphrase) {\n throw new Error('Passphrase must not be empty.');\n }\n\n const payload = Buffer.from(encrypted.slice(PREFIX.length), 'base64');\n if (payload.length < SALT_LENGTH + IV_LENGTH + TAG_LENGTH) {\n throw new Error('Encrypted payload is too short.');\n }\n\n const salt = payload.subarray(0, SALT_LENGTH);\n const iv = payload.subarray(SALT_LENGTH, SALT_LENGTH + IV_LENGTH);\n const tag = payload.subarray(payload.length - TAG_LENGTH);\n const ciphertext = payload.subarray(SALT_LENGTH + IV_LENGTH, payload.length - TAG_LENGTH);\n\n const key = scryptSync(passphrase, salt, KEY_LENGTH, {\n N: SCRYPT_N,\n r: SCRYPT_R,\n p: SCRYPT_P,\n maxmem: SCRYPT_MAXMEM,\n });\n\n const decipher = createDecipheriv('aes-256-gcm', key, iv);\n decipher.setAuthTag(tag);\n\n try {\n const decrypted = Buffer.concat([decipher.update(ciphertext), decipher.final()]);\n return decrypted.toString('utf8');\n } catch {\n throw new Error('Decryption failed. Wrong passphrase or corrupted data.');\n }\n}\n","/**\n * Write agent files: elisym.yaml, .secrets.json, .gitignore, and create agent dirs.\n */\n\nimport { randomBytes } from 'node:crypto';\nimport { mkdir, rename, writeFile } from 'node:fs/promises';\nimport { dirname, join } from 'node:path';\nimport YAML from 'yaml';\nimport { encryptSecret, isEncrypted } from '../primitives/encryption';\nimport { agentPaths, type AgentPaths } from './paths';\nimport { elisymRootFor, type AgentSource } from './resolver';\nimport { ElisymYamlSchema, SecretsSchema, type ElisymYaml, type Secrets } from './schema';\nimport { renderInitialYaml } from './template';\n\nconst GITIGNORE_CONTENT = [\n '# elisym private state - do not commit.',\n '.secrets.json',\n '.media-cache.json',\n '.jobs.json',\n '.jobs.json.corrupt.*',\n '.customer-history.json',\n '.contacts.json',\n '',\n].join('\\n');\n\nexport interface CreateAgentDirOptions {\n target: AgentSource;\n name: string;\n cwd: string;\n /**\n * For `target: 'project'`: if no .elisym/ dir exists above cwd,\n * where should we create one? Defaults to cwd.\n */\n projectRoot?: string;\n}\n\nexport interface CreatedAgentDir {\n dir: string;\n paths: AgentPaths;\n source: AgentSource;\n createdNewElisymRoot: boolean;\n}\n\n/**\n * Create (or reuse) the directory layout for a new agent. Idempotent: if the\n * agent directory already exists, returns its paths without overwriting.\n * Writes `.gitignore` in project-local .elisym/ on first creation.\n */\nexport async function createAgentDir(options: CreateAgentDirOptions): Promise<CreatedAgentDir> {\n const { target, name, cwd, projectRoot } = options;\n\n const existingRoot = elisymRootFor(target, cwd);\n let elisymRoot: string;\n let createdNewElisymRoot = false;\n\n if (existingRoot) {\n elisymRoot = existingRoot;\n } else if (target === 'project') {\n elisymRoot = join(projectRoot ?? cwd, '.elisym');\n createdNewElisymRoot = true;\n } else {\n throw new Error('homeElisymDir should always exist conceptually - this is unreachable');\n }\n\n const agentDir = join(elisymRoot, name);\n const mode = target === 'home' ? 0o700 : 0o755;\n await mkdir(agentDir, { recursive: true, mode });\n await mkdir(join(agentDir, 'skills'), { recursive: true, mode });\n\n if (target === 'project') {\n const gitignorePath = join(elisymRoot, '.gitignore');\n await writeFileIfMissing(gitignorePath, GITIGNORE_CONTENT, 0o644);\n }\n\n return {\n dir: agentDir,\n paths: agentPaths(agentDir),\n source: target,\n createdNewElisymRoot,\n };\n}\n\n/** Write elisym.yaml atomically. Validates via Zod before writing. */\nexport async function writeYaml(agentDir: string, yaml: ElisymYaml): Promise<void> {\n const validated = ElisymYamlSchema.parse(yaml);\n const body = YAML.stringify(validated);\n const target = agentPaths(agentDir).yaml;\n await writeFileAtomic(target, body, 0o644);\n}\n\n/**\n * Write a brand-new elisym.yaml with descriptive header comments and\n * commented-out examples for unset optional fields. Use only at agent\n * creation time (CLI `init`, MCP `create_agent`). Subsequent edits go\n * through `writeYaml`, which discards comments.\n */\nexport async function writeYamlInitial(agentDir: string, yaml: ElisymYaml): Promise<void> {\n const validated = ElisymYamlSchema.parse(yaml);\n const body = renderInitialYaml(validated);\n const target = agentPaths(agentDir).yaml;\n await writeFileAtomic(target, body, 0o644);\n}\n\n/**\n * Create a skills directory placeholder file with a commented-out SKILL.md\n * template covering every supported field, so operators have a reference\n * for what they can declare without having to read source. The file is\n * named `EXAMPLE.md` (not `SKILL.md`) and lives directly in `skills/`\n * (not in a subdirectory), so the skill loader skips it - it's reference\n * material, not an active skill. To turn it into a real skill: copy it\n * into `skills/<your-skill-name>/SKILL.md` and uncomment the lines you\n * need.\n *\n * Idempotent: written with `wx` flag so we never overwrite an operator's\n * edits on re-run of `init`.\n */\nexport async function writeExampleSkillTemplate(agentDir: string): Promise<void> {\n const target = join(agentDir, 'skills', 'EXAMPLE.md');\n await writeFileIfMissing(target, EXAMPLE_SKILL_TEMPLATE, 0o644);\n}\n\nconst EXAMPLE_SKILL_TEMPLATE = `# elisym skill template\n#\n# This is reference material, not an active skill. The agent runtime\n# only loads skills from \\`skills/<name>/SKILL.md\\` (one folder per\n# skill). To turn this template into a real skill:\n#\n# 1. mkdir skills/my-skill\n# 2. cp skills/EXAMPLE.md skills/my-skill/SKILL.md\n# 3. uncomment the fields you need and fill in real values\n# 4. delete this comment block from the new file\n#\n# Full reference: see packages/cli/SKILLS.md in the elisym monorepo.\n\n# ---\n# # Required fields ---------------------------------------------------\n#\n# # Skill name. Must be unique within the agent. Used as the d-tag for\n# # routing incoming jobs (NIP-89/NIP-90).\n# name: My Skill\n#\n# # One-line description shown to customers in discovery UIs. Keep it\n# # short and concrete - this is the \"elevator pitch\" for the skill.\n# description: Send a prompt, get back a poem about it.\n#\n# # Capability tags. Customers filter and discover skills by these.\n# # At least one entry required. Use lowercase kebab-case.\n# capabilities:\n# - poetry\n# - text-generation\n#\n# # Price the customer pays per job. Number or numeric string. Free\n# # skills (price: 0) are allowed only when the agent runtime is\n# # configured with \\`allowFreeSkills\\`.\n# price: 0.05\n#\n# # Asset the price is denominated in. Defaults to \"sol\" for back-compat\n# # but USDC is the canonical paid-skill currency for examples.\n# token: usdc\n# # Optional explicit mint (base58). Resolved automatically for known\n# # tokens, so usually omit this.\n# # mint: 4zMMC9srt5Ri5X14GAgXhaHii3GnPAEERYPJgZJDncDU\n#\n# # Execution mode. Defaults to \"llm\" if omitted.\n# # - llm: feed input to an LLM with the system prompt below.\n# # - static-file: return the contents of a fixed file (no input read).\n# # - static-script: spawn a script with no stdin (no input read).\n# # - dynamic-script: spawn a script and pipe the customer's input to stdin.\n# mode: llm\n#\n# # ---\n# # LLM configuration / dependency -----------------------------------\n# #\n# # For mode: 'llm', \\`provider\\` + \\`model\\` override the agent default\n# # for runtime LLM execution. \\`max_tokens\\` overrides the default cap.\n# #\n# # For script modes (static-script / dynamic-script / static-file):\n# # \\`provider\\` + \\`model\\` declare which LLM API key the script\n# # depends on. The agent registers the (provider, model) pair with\n# # the health monitor so it can:\n# # - probe the key at startup (refuse to start on invalid/billing-out)\n# # - reactively flip the pair to unhealthy if the script exits with\n# # SCRIPT_EXIT_BILLING_EXHAUSTED (= 42), refusing future jobs\n# # before payment until the key recovers\n# # - run a 5-min lazy recovery probe loop that flips the pair back\n# # to healthy as soon as the key works again\n# # \\`max_tokens\\` is rejected for script modes (the script controls\n# # its own token limits).\n# # provider: anthropic\n# # model: claude-haiku-4-5-20251001\n# # max_tokens: 4096\n#\n# # ---\n# # mode-specific fields -------------------------------------------\n#\n# # Required when mode === 'static-file'.\n# # output_file: ./output.txt\n#\n# # Required when mode === 'static-script' | 'dynamic-script'.\n# # script: ./scripts/run.sh\n# # script_args:\n# # - --flag\n# # - value\n# # script_timeout_ms: 60000\n#\n# # ---\n# # mode === 'llm' extras ------------------------------------------\n# #\n# # External tools the LLM can invoke during a job. Each tool is a\n# # named subprocess; the LLM decides whether/when to call it.\n# # tools:\n# # - name: lookup\n# # description: Look up a record by id.\n# # command:\n# # - ./tools/lookup.sh\n# # parameters:\n# # - name: id\n# # description: Record identifier (UUID).\n# # required: true\n#\n# # Cap on tool-use rounds (LLM <-> tools loop). Default 10.\n# # max_tool_rounds: 10\n#\n# # ---\n# # Per-skill rate limit (any mode) --------------------------------\n# # Snake-case in YAML, applied by the runtime regardless of mode.\n# # rate_limit:\n# # per_window_secs: 60\n# # max_per_window: 30\n#\n# # ---\n# # Per-skill execution budget (any mode) --------------------------\n# # Caps skill.execute (seconds). 0 = unlimited; omit to inherit the\n# # agent-level execution_timeout_secs (unlimited if that is unset too).\n# # max_execution_secs: 1800\n#\n# # ---\n# # Imagery ---------------------------------------------------------\n# # Either a local file path (uploaded on first start) or an absolute\n# # URL. Local paths must stay inside the skill directory.\n# # image_file: ./skill-icon.png\n# # image: https://example.com/icon.png\n# ---\n#\n# Markdown body below the frontmatter is the system prompt for\n# mode === 'llm'. For other modes it's ignored.\n#\n# You are a helpful assistant. Reply concisely.\n`;\n\n/**\n * Write .secrets.json atomically. If `passphrase` is given, encrypts all\n * plaintext secret fields (already-encrypted values are left as-is).\n * Generic over `llm_api_keys` so any registered provider's key is\n * encrypted without per-provider plumbing here.\n */\nexport async function writeSecrets(\n agentDir: string,\n secrets: Secrets,\n passphrase?: string,\n): Promise<void> {\n const validated = SecretsSchema.parse(secrets);\n let encryptedLlmKeys: Record<string, string> | undefined;\n if (validated.llm_api_keys) {\n encryptedLlmKeys = {};\n for (const [providerId, value] of Object.entries(validated.llm_api_keys)) {\n if (value) {\n encryptedLlmKeys[providerId] = maybeEncrypt(value, passphrase);\n }\n }\n if (Object.keys(encryptedLlmKeys).length === 0) {\n encryptedLlmKeys = undefined;\n }\n }\n const finalSecrets: Secrets = {\n nostr_secret_key: maybeEncrypt(validated.nostr_secret_key, passphrase),\n solana_secret_key: validated.solana_secret_key\n ? maybeEncrypt(validated.solana_secret_key, passphrase)\n : undefined,\n llm_api_keys: encryptedLlmKeys,\n };\n const body = JSON.stringify(finalSecrets, null, 2) + '\\n';\n const target = agentPaths(agentDir).secrets;\n await writeFileAtomic(target, body, 0o600);\n}\n\nfunction maybeEncrypt(value: string, passphrase: string | undefined): string {\n if (!passphrase) {\n return value;\n }\n if (isEncrypted(value)) {\n return value;\n }\n return encryptSecret(value, passphrase);\n}\n\n/** Atomic write: temp file + rename. Preserves mode. */\nexport async function writeFileAtomic(\n path: string,\n data: string | Buffer,\n mode: number,\n): Promise<void> {\n await mkdir(dirname(path), { recursive: true });\n const tmpPath = `${path}.tmp.${randomBytes(6).toString('hex')}`;\n await writeFile(tmpPath, data, { mode });\n try {\n await rename(tmpPath, path);\n } catch (e) {\n // Best-effort cleanup of temp file on rename failure.\n try {\n const { unlink } = await import('node:fs/promises');\n await unlink(tmpPath);\n } catch {\n /* ignore */\n }\n throw e;\n }\n}\n\nasync function writeFileIfMissing(path: string, data: string, mode: number): Promise<void> {\n try {\n await writeFile(path, data, { mode, flag: 'wx' });\n } catch (e: unknown) {\n // wx fails with EEXIST if file exists - that's fine.\n if (!isEexist(e)) {\n throw e;\n }\n }\n}\n\nfunction isEexist(e: unknown): boolean {\n return (\n typeof e === 'object' && e !== null && 'code' in e && (e as { code: string }).code === 'EEXIST'\n );\n}\n","/**\n * Zod schemas and types for `~/.elisym/config.yaml`.\n *\n * Split from `./global` so the schemas can be re-exported from the\n * browser-safe `@elisym/sdk` entry point without dragging in `node:fs/promises`\n * (which the loader/writer in `./global` needs).\n */\n\nimport { z } from 'zod';\n\nexport const SessionSpendLimitEntrySchema = z\n .object({\n chain: z.enum(['solana']),\n token: z\n .string()\n .min(1)\n .max(16)\n .regex(/^[a-z0-9]+$/, 'token must be lowercase alphanumeric'),\n mint: z.string().min(1).max(64).optional(),\n amount: z.number().positive().finite(),\n })\n .strict();\n\nexport const GlobalConfigSchema = z\n .object({\n session_spend_limits: z.array(SessionSpendLimitEntrySchema).max(16).optional(),\n })\n .strict();\n\nexport type SessionSpendLimitEntry = z.infer<typeof SessionSpendLimitEntrySchema>;\nexport type GlobalConfig = z.infer<typeof GlobalConfigSchema>;\n","/**\n * Global (not per-agent) config stored at `~/.elisym/config.yaml`.\n *\n * Node.js/Bun only - reads and writes the filesystem. Browser code must not\n * import this module; import the schemas from `./global-schema` instead, or\n * the loader/writer from `@elisym/sdk/node`.\n */\n\nimport { readFile } from 'node:fs/promises';\nimport YAML from 'yaml';\nimport { writeFileAtomic } from '../agent-store/writer';\nimport { GlobalConfigSchema, type GlobalConfig } from './global-schema';\n\nexport {\n GlobalConfigSchema,\n SessionSpendLimitEntrySchema,\n type GlobalConfig,\n type SessionSpendLimitEntry,\n} from './global-schema';\n\nfunction isEnoent(e: unknown): boolean {\n return (\n typeof e === 'object' && e !== null && 'code' in e && (e as { code: string }).code === 'ENOENT'\n );\n}\n\n/**\n * Read and validate `~/.elisym/config.yaml`. Returns `{}` if missing. Throws\n * on malformed YAML or schema violations — the MCP server treats these as fatal\n * at startup rather than silently ignoring bad overrides.\n */\nexport async function loadGlobalConfig(path: string): Promise<GlobalConfig> {\n let raw: string;\n try {\n raw = await readFile(path, 'utf-8');\n } catch (e) {\n if (isEnoent(e)) {\n return {};\n }\n throw e;\n }\n if (raw.trim() === '') {\n return {};\n }\n const parsed: unknown = YAML.parse(raw);\n return GlobalConfigSchema.parse(parsed ?? {});\n}\n\n/** Write the config YAML atomically. Validates via Zod before writing. */\nexport async function writeGlobalConfig(path: string, config: GlobalConfig): Promise<void> {\n const validated = GlobalConfigSchema.parse(config);\n const body = YAML.stringify(validated);\n await writeFileAtomic(path, body, 0o644);\n}\n"]}
1
+ {"version":3,"sources":["../src/primitives/encryption.ts","../src/constants.ts","../src/agent-store/writer.ts","../src/config/global-schema.ts","../src/config/global.ts","../src/transport/iroh.ts"],"names":["randomBytes","readFile","YAML"],"mappings":";;;;;;;;AAcA,IAAM,MAAA,GAAS,eAAA;AACf,IAAM,WAAA,GAAc,EAAA;AACpB,IAAM,SAAA,GAAY,EAAA;AAClB,IAAM,UAAA,GAAa,EAAA;AACnB,IAAM,UAAA,GAAa,EAAA;AAEnB,IAAM,WAAW,CAAA,IAAK,EAAA;AACtB,IAAM,QAAA,GAAW,CAAA;AACjB,IAAM,QAAA,GAAW,CAAA;AACjB,IAAM,aAAA,GAAgB,GAAA,GAAM,QAAA,GAAW,QAAA,GAAW,CAAA;AAG3C,SAAS,YAAY,KAAA,EAAwB;AAClD,EAAA,OAAO,KAAA,CAAM,WAAW,MAAM,CAAA;AAChC;AAGO,SAAS,aAAA,CAAc,WAAmB,UAAA,EAA4B;AAC3E,EAAA,IAAI,CAAC,UAAA,EAAY;AACf,IAAA,MAAM,IAAI,MAAM,+BAA+B,CAAA;AAAA,EACjD;AAEA,EAAA,MAAM,IAAA,GAAO,YAAY,WAAW,CAAA;AACpC,EAAA,MAAM,GAAA,GAAM,UAAA,CAAW,UAAA,EAAY,IAAA,EAAM,UAAA,EAAY;AAAA,IACnD,CAAA,EAAG,QAAA;AAAA,IACH,CAAA,EAAG,QAAA;AAAA,IACH,CAAA,EAAG,QAAA;AAAA,IACH,MAAA,EAAQ;AAAA,GACT,CAAA;AACD,EAAA,MAAM,EAAA,GAAK,YAAY,SAAS,CAAA;AAEhC,EAAA,MAAM,MAAA,GAAS,cAAA,CAAe,aAAA,EAAe,GAAA,EAAK,EAAE,CAAA;AACpD,EAAA,MAAM,SAAA,GAAY,MAAA,CAAO,MAAA,CAAO,CAAC,MAAA,CAAO,MAAA,CAAO,SAAA,EAAW,MAAM,CAAA,EAAG,MAAA,CAAO,KAAA,EAAO,CAAC,CAAA;AAClF,EAAA,MAAM,GAAA,GAAM,OAAO,UAAA,EAAW;AAE9B,EAAA,MA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" + base64(salt[16] + iv[12] + ciphertext + tag[16])\n *\n * scrypt params: N=2^17, r=8, p=1 (~128 MB RAM per derivation).\n *\n * Node.js/Bun only - not available in browsers. Reachable only via the\n * '@elisym/sdk/node' subpath, which browser bundlers will not resolve.\n */\n\nimport { Buffer } from 'node:buffer';\nimport { createCipheriv, createDecipheriv, randomBytes, scryptSync } from 'node:crypto';\n\nconst PREFIX = 'encrypted:v1:';\nconst SALT_LENGTH = 16;\nconst IV_LENGTH = 12;\nconst TAG_LENGTH = 16;\nconst KEY_LENGTH = 32; // AES-256\n// v1: N=2^17 (OWASP minimum). v2 will use N=2^20 with format migration.\nconst SCRYPT_N = 2 ** 17;\nconst SCRYPT_R = 8;\nconst SCRYPT_P = 1;\nconst SCRYPT_MAXMEM = 128 * SCRYPT_N * SCRYPT_R * 2; // 2x the minimum required memory\n\n/** Check if a value is encrypted (has the encrypted:v1: prefix). */\nexport function isEncrypted(value: string): boolean {\n return value.startsWith(PREFIX);\n}\n\n/** Encrypt a plaintext secret with a passphrase. Returns \"encrypted:v1:base64...\". Node.js/Bun only. */\nexport function encryptSecret(plaintext: string, passphrase: string): string {\n if (!passphrase) {\n throw new Error('Passphrase must not be empty.');\n }\n\n const salt = randomBytes(SALT_LENGTH);\n const key = scryptSync(passphrase, salt, KEY_LENGTH, {\n N: SCRYPT_N,\n r: SCRYPT_R,\n p: SCRYPT_P,\n maxmem: SCRYPT_MAXMEM,\n });\n const iv = randomBytes(IV_LENGTH);\n\n const cipher = createCipheriv('aes-256-gcm', key, iv);\n const encrypted = Buffer.concat([cipher.update(plaintext, 'utf8'), cipher.final()]);\n const tag = cipher.getAuthTag();\n\n const payload = Buffer.concat([salt, iv, encrypted, tag]);\n return PREFIX + payload.toString('base64');\n}\n\n/** Decrypt an encrypted secret with a passphrase. Throws on wrong passphrase or corrupted data. Node.js/Bun only. */\nexport function decryptSecret(encrypted: string, passphrase: string): string {\n if (!isEncrypted(encrypted)) {\n throw new Error('Value is not encrypted (missing encrypted:v1: prefix).');\n }\n if (!passphrase) {\n throw new Error('Passphrase must not be empty.');\n }\n\n const payload = Buffer.from(encrypted.slice(PREFIX.length), 'base64');\n if (payload.length < SALT_LENGTH + IV_LENGTH + TAG_LENGTH) {\n throw new Error('Encrypted payload is too short.');\n }\n\n const salt = payload.subarray(0, SALT_LENGTH);\n const iv = payload.subarray(SALT_LENGTH, SALT_LENGTH + IV_LENGTH);\n const tag = payload.subarray(payload.length - TAG_LENGTH);\n const ciphertext = payload.subarray(SALT_LENGTH + IV_LENGTH, payload.length - TAG_LENGTH);\n\n const key = scryptSync(passphrase, salt, KEY_LENGTH, {\n N: SCRYPT_N,\n r: SCRYPT_R,\n p: SCRYPT_P,\n maxmem: SCRYPT_MAXMEM,\n });\n\n const decipher = createDecipheriv('aes-256-gcm', key, iv);\n decipher.setAuthTag(tag);\n\n try {\n const decrypted = Buffer.concat([decipher.update(ciphertext), decipher.final()]);\n return decrypted.toString('utf8');\n } catch {\n throw new Error('Decryption failed. Wrong passphrase or corrupted data.');\n }\n}\n","import type { Address } from '@solana/kit';\n\nexport const RELAYS = [\n 'wss://relay.damus.io',\n 'wss://nos.lol',\n 'wss://relay.nostr.band',\n 'wss://relay.primal.net',\n 'wss://relay.snort.social',\n];\n\nexport const KIND_APP_HANDLER = 31990;\nexport const KIND_LONG_FORM_ARTICLE = 30023;\nexport const KIND_JOB_REQUEST_BASE = 5000;\nexport const KIND_JOB_RESULT_BASE = 6000;\nexport const KIND_JOB_FEEDBACK = 7000;\nexport const DEFAULT_KIND_OFFSET = 100;\n\n/** Discovery tag attached to elisym agent policy events (kind 30023). */\nexport const POLICY_T_TAG = 'elisym-policy';\n/** d-tag prefix for policy events: full d-tag = `<prefix><type>` (e.g. `elisym-policy-tos`). */\nexport const POLICY_D_TAG_PREFIX = 'elisym-policy-';\n/** Validation regex for policy `type` slug. Lowercase ASCII + hyphen, 1-32 chars, no leading/trailing hyphen. */\nexport const POLICY_TYPE_REGEX = /^[a-z0-9](?:[a-z0-9-]{0,30}[a-z0-9])?$/;\n\n/** Default job request kind (5000 + 100). */\nexport const KIND_JOB_REQUEST = KIND_JOB_REQUEST_BASE + DEFAULT_KIND_OFFSET;\n/** Default job result kind (6000 + 100). */\nexport const KIND_JOB_RESULT = KIND_JOB_RESULT_BASE + DEFAULT_KIND_OFFSET;\n\n/** Compute a job request kind from an offset (5000 + offset). */\nexport function jobRequestKind(offset: number): number {\n if (!Number.isInteger(offset) || offset < 0 || offset >= 1000) {\n throw new Error(`Invalid kind offset: ${offset}. Must be integer 0-999.`);\n }\n return KIND_JOB_REQUEST_BASE + offset;\n}\n\n/** Compute a job result kind from an offset (6000 + offset). */\nexport function jobResultKind(offset: number): number {\n if (!Number.isInteger(offset) || offset < 0 || offset >= 1000) {\n throw new Error(`Invalid kind offset: ${offset}. Must be integer 0-999.`);\n }\n return KIND_JOB_RESULT_BASE + offset;\n}\n\n/** Ephemeral ping/pong kinds (not stored by relays, forwarded in real-time). */\nexport const KIND_PING = 20200;\nexport const KIND_PONG = 20201;\n\nexport const LAMPORTS_PER_SOL = 1_000_000_000;\n\n/**\n * Solana program ID for the elisym protocol config (devnet deployment).\n *\n * The Anchor program at this address is the source of truth for fee bps,\n * treasury address, and admin rotation state. Read via `getProtocolConfig`.\n */\nexport const PROTOCOL_PROGRAM_ID_DEVNET = 'BrX1CRkSgvcjxBvc2bgc3QqgWjinusofDmeP7ZVxvwrE' as Address;\n\n/**\n * Read-only marker pubkey attached as a non-signer account to every elisym\n * payment transaction. Lets indexers enumerate every elisym tx network-wide\n * via a single `getSignaturesForAddress(ELISYM_PROTOCOL_TAG)` call,\n * independent of fee size or recipient.\n *\n * The account does not need to exist on-chain; including its pubkey as an\n * extra read-only account in the provider transfer instruction is enough for\n * Solana's tx-by-account index to pick it up. The corresponding secret key\n * was generated and discarded - the tag never signs and never holds funds.\n */\nexport const ELISYM_PROTOCOL_TAG = 'ELiZksgwDt41LaeuPDLkUfWgFXhGgVayTMP7L5nTSEL8' as Address;\n\nexport type ProtocolCluster = 'devnet' | 'mainnet' | 'localnet';\n\n/**\n * Resolve the elisym-config program ID for a given Solana cluster.\n * Mainnet is intentionally unsupported until the program ships there.\n */\nexport function getProtocolProgramId(cluster: ProtocolCluster): Address {\n switch (cluster) {\n case 'devnet':\n case 'localnet':\n return PROTOCOL_PROGRAM_ID_DEVNET;\n case 'mainnet':\n throw new Error('Protocol program is not deployed on mainnet yet');\n }\n}\n\n/** Default values for timeouts, retries, and batch sizes. */\nexport const DEFAULTS = {\n SUBSCRIPTION_TIMEOUT_MS: 120_000,\n PING_TIMEOUT_MS: 3_000,\n PING_RETRIES: 2,\n PING_CACHE_TTL_MS: 30_000,\n PAYMENT_EXPIRY_SECS: 600,\n BATCH_SIZE: 250,\n QUERY_TIMEOUT_MS: 15_000,\n EOSE_TIMEOUT_MS: 3_000,\n VERIFY_RETRIES: 10,\n VERIFY_INTERVAL_MS: 3_000,\n VERIFY_BY_REF_RETRIES: 15,\n VERIFY_BY_REF_INTERVAL_MS: 2_000,\n RESULT_RETRY_COUNT: 3,\n RESULT_RETRY_BASE_MS: 1_000,\n QUERY_MAX_CONCURRENCY: 6,\n VERIFY_SIGNATURE_LIMIT: 25,\n // Default ceiling for a single iroh file transfer (seed/fetch). A tunable\n // default, not a protocol constant - the transfer is resumable and its own\n // budget, decoupled from the result-wait window.\n IROH_FETCH_TIMEOUT_MS: 300_000,\n} as const;\n\n/** Protocol limits for input validation. */\nexport const LIMITS = {\n MAX_INPUT_LENGTH: 100_000,\n // NIP-44 v2 hard cap on encrypted plaintext: the pad() length prefix is a u16,\n // so the plaintext can be at most 65_535 BYTES (not chars). Encrypting anything\n // larger throws `invalid plaintext size` inside nip44Encrypt. This is the binding\n // limit for TARGETED (encrypted) jobs - lower than every relay's NIP-11 cap.\n NIP44_MAX_PLAINTEXT_BYTES: 65_535,\n // Spill threshold for encrypted content: above this many UTF-8 bytes, callers\n // route the text through iroh out-of-band instead of inlining it. A non-spilled\n // job is encrypted RAW (no envelope - see marketplace.submitJobRequest), so a\n // 60_000-byte input is a 60_000-byte plaintext; the ~5.5KB gap under the hard cap\n // is plain slack, and NIP44_MAX_PLAINTEXT_BYTES is the SDK backstop.\n MAX_ENCRYPTED_INLINE_BYTES: 60_000,\n // Ceiling above which a text/* attachment is NOT materialized back into a string\n // (re-inlined into SkillInput.data) - the consumer gets a filePath / explicit\n // fetch instead. Also bounds the in-memory git-diff buffer (memory-DoS guard).\n MAX_REINLINE_TEXT_BYTES: 4_194_304, // 4 MiB\n // Hard safety cap on a single file transferred via iroh, enforced on the\n // actual streamed bytes (never the sender-declared `size`). A tunable default;\n // providers may lower it per deployment.\n MAX_FILE_SIZE: 1_073_741_824, // 1 GiB\n\n MAX_TIMEOUT_SECS: 600,\n // Upper bound for execution budgets (`max_execution_secs` / `execution_timeout_secs`).\n // Distinct from MAX_TIMEOUT_SECS (the result-wait cap): execution budgets may be\n // hours, so this exists only to keep `secs * 1000` within Node's setTimeout limit\n // (2_147_483_647 ms) - a larger value overflows and fires the timer immediately.\n MAX_EXECUTION_SECS: 2_147_483,\n MAX_CAPABILITIES: 20,\n MAX_DESCRIPTION_LENGTH: 500,\n MAX_AGENT_NAME_LENGTH: 64,\n MAX_CAPABILITY_LENGTH: 64,\n MAX_POLICY_CONTENT_LENGTH: 50_000,\n MAX_POLICIES_PER_AGENT: 12,\n MAX_POLICY_TYPE_LENGTH: 32,\n MAX_POLICY_TITLE_LENGTH: 120,\n MAX_POLICY_SUMMARY_LENGTH: 280,\n MAX_POLICY_VERSION_LENGTH: 32,\n} as const;\n\nconst UTF8_ENCODER = new TextEncoder();\n\n/**\n * UTF-8 byte length of a string. All size guards on encrypted content measure\n * BYTES, not `String.length` (UTF-16 code units): NIP-44's plaintext cap is a\n * byte cap, so a multibyte string under the char cap can still exceed it.\n */\nexport function utf8ByteLength(value: string): number {\n return UTF8_ENCODER.encode(value).length;\n}\n","/**\n * Write agent files: elisym.yaml, .secrets.json, .gitignore, and create agent dirs.\n */\n\nimport { randomBytes } from 'node:crypto';\nimport { mkdir, readFile, rename, writeFile } from 'node:fs/promises';\nimport { dirname, join } from 'node:path';\nimport YAML from 'yaml';\nimport { encryptSecret, isEncrypted } from '../primitives/encryption';\nimport { agentPaths, type AgentPaths } from './paths';\nimport { elisymRootFor, type AgentSource } from './resolver';\nimport { ElisymYamlSchema, SecretsSchema, type ElisymYaml, type Secrets } from './schema';\nimport { renderInitialYaml } from './template';\n\n/** Bare per-agent `.iroh/` store dir; ignored at any depth under `.elisym/`. */\nconst IROH_GITIGNORE_ENTRY = '.iroh/';\n\nconst GITIGNORE_CONTENT = [\n '# elisym private state - do not commit.',\n '.secrets.json',\n '.media-cache.json',\n '.jobs.json',\n '.jobs.json.corrupt.*',\n '.customer-history.json',\n '.contacts.json',\n IROH_GITIGNORE_ENTRY,\n '',\n].join('\\n');\n\n/**\n * Ensure the project-local `.elisym/.gitignore` ignores the iroh blob store.\n * Idempotent migration for agents created before `.iroh/` was added to the\n * default ignore list; a no-op when no `.gitignore` exists (e.g. home-global,\n * which relies on directory permissions instead). The iroh store holds job\n * payloads in cleartext, so it must never be committed.\n */\nexport async function ensureGitignoreHasIrohEntry(elisymRoot: string): Promise<void> {\n const gitignorePath = join(elisymRoot, '.gitignore');\n let current: string;\n try {\n current = await readFile(gitignorePath, 'utf-8');\n } catch {\n return;\n }\n const hasEntry = current.split('\\n').some((line) => line.trim() === IROH_GITIGNORE_ENTRY);\n if (hasEntry) {\n return;\n }\n const separator = current.length === 0 || current.endsWith('\\n') ? '' : '\\n';\n await writeFile(gitignorePath, `${current}${separator}${IROH_GITIGNORE_ENTRY}\\n`, {\n mode: 0o644,\n });\n}\n\nexport interface CreateAgentDirOptions {\n target: AgentSource;\n name: string;\n cwd: string;\n /**\n * For `target: 'project'`: if no .elisym/ dir exists above cwd,\n * where should we create one? Defaults to cwd.\n */\n projectRoot?: string;\n}\n\nexport interface CreatedAgentDir {\n dir: string;\n paths: AgentPaths;\n source: AgentSource;\n createdNewElisymRoot: boolean;\n}\n\n/**\n * Create (or reuse) the directory layout for a new agent. Idempotent: if the\n * agent directory already exists, returns its paths without overwriting.\n * Writes `.gitignore` in project-local .elisym/ on first creation.\n */\nexport async function createAgentDir(options: CreateAgentDirOptions): Promise<CreatedAgentDir> {\n const { target, name, cwd, projectRoot } = options;\n\n const existingRoot = elisymRootFor(target, cwd);\n let elisymRoot: string;\n let createdNewElisymRoot = false;\n\n if (existingRoot) {\n elisymRoot = existingRoot;\n } else if (target === 'project') {\n elisymRoot = join(projectRoot ?? cwd, '.elisym');\n createdNewElisymRoot = true;\n } else {\n throw new Error('homeElisymDir should always exist conceptually - this is unreachable');\n }\n\n const agentDir = join(elisymRoot, name);\n const mode = target === 'home' ? 0o700 : 0o755;\n await mkdir(agentDir, { recursive: true, mode });\n await mkdir(join(agentDir, 'skills'), { recursive: true, mode });\n\n if (target === 'project') {\n const gitignorePath = join(elisymRoot, '.gitignore');\n await writeFileIfMissing(gitignorePath, GITIGNORE_CONTENT, 0o644);\n }\n\n return {\n dir: agentDir,\n paths: agentPaths(agentDir),\n source: target,\n createdNewElisymRoot,\n };\n}\n\n/** Write elisym.yaml atomically. Validates via Zod before writing. */\nexport async function writeYaml(agentDir: string, yaml: ElisymYaml): Promise<void> {\n const validated = ElisymYamlSchema.parse(yaml);\n const body = YAML.stringify(validated);\n const target = agentPaths(agentDir).yaml;\n await writeFileAtomic(target, body, 0o644);\n}\n\n/**\n * Write a brand-new elisym.yaml with descriptive header comments and\n * commented-out examples for unset optional fields. Use only at agent\n * creation time (CLI `init`, MCP `create_agent`). Subsequent edits go\n * through `writeYaml`, which discards comments.\n */\nexport async function writeYamlInitial(agentDir: string, yaml: ElisymYaml): Promise<void> {\n const validated = ElisymYamlSchema.parse(yaml);\n const body = renderInitialYaml(validated);\n const target = agentPaths(agentDir).yaml;\n await writeFileAtomic(target, body, 0o644);\n}\n\n/**\n * Create a skills directory placeholder file with a commented-out SKILL.md\n * template covering every supported field, so operators have a reference\n * for what they can declare without having to read source. The file is\n * named `EXAMPLE.md` (not `SKILL.md`) and lives directly in `skills/`\n * (not in a subdirectory), so the skill loader skips it - it's reference\n * material, not an active skill. To turn it into a real skill: copy it\n * into `skills/<your-skill-name>/SKILL.md` and uncomment the lines you\n * need.\n *\n * Idempotent: written with `wx` flag so we never overwrite an operator's\n * edits on re-run of `init`.\n */\nexport async function writeExampleSkillTemplate(agentDir: string): Promise<void> {\n const target = join(agentDir, 'skills', 'EXAMPLE.md');\n await writeFileIfMissing(target, EXAMPLE_SKILL_TEMPLATE, 0o644);\n}\n\nconst EXAMPLE_SKILL_TEMPLATE = `# elisym skill template\n#\n# This is reference material, not an active skill. The agent runtime\n# only loads skills from \\`skills/<name>/SKILL.md\\` (one folder per\n# skill). To turn this template into a real skill:\n#\n# 1. mkdir skills/my-skill\n# 2. cp skills/EXAMPLE.md skills/my-skill/SKILL.md\n# 3. uncomment the fields you need and fill in real values\n# 4. delete this comment block from the new file\n#\n# Full reference: see packages/cli/SKILLS.md in the elisym monorepo.\n\n# ---\n# # Required fields ---------------------------------------------------\n#\n# # Skill name. Must be unique within the agent. Used as the d-tag for\n# # routing incoming jobs (NIP-89/NIP-90).\n# name: My Skill\n#\n# # One-line description shown to customers in discovery UIs. Keep it\n# # short and concrete - this is the \"elevator pitch\" for the skill.\n# description: Send a prompt, get back a poem about it.\n#\n# # Capability tags. Customers filter and discover skills by these.\n# # At least one entry required. Use lowercase kebab-case.\n# capabilities:\n# - poetry\n# - text-generation\n#\n# # Price the customer pays per job. Number or numeric string. Free\n# # skills (price: 0) are allowed only when the agent runtime is\n# # configured with \\`allowFreeSkills\\`.\n# price: 0.05\n#\n# # Asset the price is denominated in. Defaults to \"sol\" for back-compat\n# # but USDC is the canonical paid-skill currency for examples.\n# token: usdc\n# # Optional explicit mint (base58). Resolved automatically for known\n# # tokens, so usually omit this.\n# # mint: 4zMMC9srt5Ri5X14GAgXhaHii3GnPAEERYPJgZJDncDU\n#\n# # Execution mode. Defaults to \"llm\" if omitted.\n# # - llm: feed input to an LLM with the system prompt below.\n# # - static-file: return the contents of a fixed file (no input read).\n# # - static-script: spawn a script with no stdin (no input read).\n# # - dynamic-script: spawn a script and pipe the customer's input to stdin.\n# mode: llm\n#\n# # ---\n# # LLM configuration / dependency -----------------------------------\n# #\n# # For mode: 'llm', \\`provider\\` + \\`model\\` override the agent default\n# # for runtime LLM execution. \\`max_tokens\\` overrides the default cap.\n# #\n# # For script modes (static-script / dynamic-script / static-file):\n# # \\`provider\\` + \\`model\\` declare which LLM API key the script\n# # depends on. The agent registers the (provider, model) pair with\n# # the health monitor so it can:\n# # - probe the key at startup (refuse to start on invalid/billing-out)\n# # - reactively flip the pair to unhealthy if the script exits with\n# # SCRIPT_EXIT_BILLING_EXHAUSTED (= 42), refusing future jobs\n# # before payment until the key recovers\n# # - run a 5-min lazy recovery probe loop that flips the pair back\n# # to healthy as soon as the key works again\n# # \\`max_tokens\\` is rejected for script modes (the script controls\n# # its own token limits).\n# # provider: anthropic\n# # model: claude-haiku-4-5-20251001\n# # max_tokens: 4096\n#\n# # ---\n# # mode-specific fields -------------------------------------------\n#\n# # Required when mode === 'static-file'.\n# # output_file: ./output.txt\n#\n# # Required when mode === 'static-script' | 'dynamic-script'.\n# # script: ./scripts/run.sh\n# # script_args:\n# # - --flag\n# # - value\n# # script_timeout_ms: 60000\n#\n# # ---\n# # mode === 'llm' extras ------------------------------------------\n# #\n# # External tools the LLM can invoke during a job. Each tool is a\n# # named subprocess; the LLM decides whether/when to call it.\n# # tools:\n# # - name: lookup\n# # description: Look up a record by id.\n# # command:\n# # - ./tools/lookup.sh\n# # parameters:\n# # - name: id\n# # description: Record identifier (UUID).\n# # required: true\n#\n# # Cap on tool-use rounds (LLM <-> tools loop). Default 10.\n# # max_tool_rounds: 10\n#\n# # ---\n# # Per-skill rate limit (any mode) --------------------------------\n# # Snake-case in YAML, applied by the runtime regardless of mode.\n# # rate_limit:\n# # per_window_secs: 60\n# # max_per_window: 30\n#\n# # ---\n# # Per-skill execution budget (any mode) --------------------------\n# # Caps skill.execute (seconds). 0 = unlimited; omit to inherit the\n# # agent-level execution_timeout_secs (unlimited if that is unset too).\n# # max_execution_secs: 1800\n#\n# # ---\n# # Imagery ---------------------------------------------------------\n# # Either a local file path (uploaded on first start) or an absolute\n# # URL. Local paths must stay inside the skill directory.\n# # image_file: ./skill-icon.png\n# # image: https://example.com/icon.png\n# ---\n#\n# Markdown body below the frontmatter is the system prompt for\n# mode === 'llm'. For other modes it's ignored.\n#\n# You are a helpful assistant. Reply concisely.\n`;\n\n/**\n * Write .secrets.json atomically. If `passphrase` is given, encrypts all\n * plaintext secret fields (already-encrypted values are left as-is).\n * Generic over `llm_api_keys` so any registered provider's key is\n * encrypted without per-provider plumbing here.\n */\nexport async function writeSecrets(\n agentDir: string,\n secrets: Secrets,\n passphrase?: string,\n): Promise<void> {\n const validated = SecretsSchema.parse(secrets);\n let encryptedLlmKeys: Record<string, string> | undefined;\n if (validated.llm_api_keys) {\n encryptedLlmKeys = {};\n for (const [providerId, value] of Object.entries(validated.llm_api_keys)) {\n if (value) {\n encryptedLlmKeys[providerId] = maybeEncrypt(value, passphrase);\n }\n }\n if (Object.keys(encryptedLlmKeys).length === 0) {\n encryptedLlmKeys = undefined;\n }\n }\n const finalSecrets: Secrets = {\n nostr_secret_key: maybeEncrypt(validated.nostr_secret_key, passphrase),\n solana_secret_key: validated.solana_secret_key\n ? maybeEncrypt(validated.solana_secret_key, passphrase)\n : undefined,\n llm_api_keys: encryptedLlmKeys,\n };\n const body = JSON.stringify(finalSecrets, null, 2) + '\\n';\n const target = agentPaths(agentDir).secrets;\n await writeFileAtomic(target, body, 0o600);\n}\n\nfunction maybeEncrypt(value: string, passphrase: string | undefined): string {\n if (!passphrase) {\n return value;\n }\n if (isEncrypted(value)) {\n return value;\n }\n return encryptSecret(value, passphrase);\n}\n\n/** Atomic write: temp file + rename. Preserves mode. */\nexport async function writeFileAtomic(\n path: string,\n data: string | Buffer,\n mode: number,\n): Promise<void> {\n await mkdir(dirname(path), { recursive: true });\n const tmpPath = `${path}.tmp.${randomBytes(6).toString('hex')}`;\n await writeFile(tmpPath, data, { mode });\n try {\n await rename(tmpPath, path);\n } catch (e) {\n // Best-effort cleanup of temp file on rename failure.\n try {\n const { unlink } = await import('node:fs/promises');\n await unlink(tmpPath);\n } catch {\n /* ignore */\n }\n throw e;\n }\n}\n\nasync function writeFileIfMissing(path: string, data: string, mode: number): Promise<void> {\n try {\n await writeFile(path, data, { mode, flag: 'wx' });\n } catch (e: unknown) {\n // wx fails with EEXIST if file exists - that's fine.\n if (!isEexist(e)) {\n throw e;\n }\n }\n}\n\nfunction isEexist(e: unknown): boolean {\n return (\n typeof e === 'object' && e !== null && 'code' in e && (e as { code: string }).code === 'EEXIST'\n );\n}\n","/**\n * Zod schemas and types for `~/.elisym/config.yaml`.\n *\n * Split from `./global` so the schemas can be re-exported from the\n * browser-safe `@elisym/sdk` entry point without dragging in `node:fs/promises`\n * (which the loader/writer in `./global` needs).\n */\n\nimport { z } from 'zod';\n\nexport const SessionSpendLimitEntrySchema = z\n .object({\n chain: z.enum(['solana']),\n token: z\n .string()\n .min(1)\n .max(16)\n .regex(/^[a-z0-9]+$/, 'token must be lowercase alphanumeric'),\n mint: z.string().min(1).max(64).optional(),\n // Stored as a string to preserve the operator's exact decimal text (avoids\n // Number round-tripping to scientific notation). Legacy configs persisted a\n // number; accept both and normalize to a positive-decimal string.\n amount: z\n .union([z.string(), z.number()])\n .transform((value) => (typeof value === 'number' ? String(value) : value.trim()))\n .refine((value) => /^\\d+(?:\\.\\d+)?$/.test(value) && /[1-9]/.test(value), {\n message: 'amount must be a positive decimal (e.g. \"0.5\", \"1\")',\n }),\n })\n .strict();\n\nexport const GlobalConfigSchema = z\n .object({\n session_spend_limits: z.array(SessionSpendLimitEntrySchema).max(16).optional(),\n })\n .strict();\n\nexport type SessionSpendLimitEntry = z.infer<typeof SessionSpendLimitEntrySchema>;\nexport type GlobalConfig = z.infer<typeof GlobalConfigSchema>;\n","/**\n * Global (not per-agent) config stored at `~/.elisym/config.yaml`.\n *\n * Node.js/Bun only - reads and writes the filesystem. Browser code must not\n * import this module; import the schemas from `./global-schema` instead, or\n * the loader/writer from `@elisym/sdk/node`.\n */\n\nimport { readFile } from 'node:fs/promises';\nimport YAML from 'yaml';\nimport { writeFileAtomic } from '../agent-store/writer';\nimport { GlobalConfigSchema, type GlobalConfig } from './global-schema';\n\nexport {\n GlobalConfigSchema,\n SessionSpendLimitEntrySchema,\n type GlobalConfig,\n type SessionSpendLimitEntry,\n} from './global-schema';\n\nfunction isEnoent(e: unknown): boolean {\n return (\n typeof e === 'object' && e !== null && 'code' in e && (e as { code: string }).code === 'ENOENT'\n );\n}\n\n/**\n * Read and validate `~/.elisym/config.yaml`. Returns `{}` if missing. Throws\n * on malformed YAML or schema violations — the MCP server treats these as fatal\n * at startup rather than silently ignoring bad overrides.\n */\nexport async function loadGlobalConfig(path: string): Promise<GlobalConfig> {\n let raw: string;\n try {\n raw = await readFile(path, 'utf-8');\n } catch (e) {\n if (isEnoent(e)) {\n return {};\n }\n throw e;\n }\n if (raw.trim() === '') {\n return {};\n }\n const parsed: unknown = YAML.parse(raw);\n return GlobalConfigSchema.parse(parsed ?? {});\n}\n\n/** Write the config YAML atomically. Validates via Zod before writing. */\nexport async function writeGlobalConfig(path: string, config: GlobalConfig): Promise<void> {\n const validated = GlobalConfigSchema.parse(config);\n const body = YAML.stringify(validated);\n await writeFileAtomic(path, body, 0o644);\n}\n","/**\n * Node-only iroh blob transport: seed a file as a content-addressed blob and\n * fetch one by ticket, streaming to/from disk. Import from `@elisym/sdk/node`.\n *\n * `@number0/iroh` is an OPTIONAL native (napi) dependency, loaded via dynamic\n * `import()` only on first use, so the SDK installs and runs without it (file\n * transfer is simply unavailable). To stay decoupled from the optional addon's\n * type surface (and its `const enum`s), the binding is accessed through the\n * minimal local interface below; enum parameters are passed as their runtime\n * string values, which is what the napi layer expects.\n */\nimport { LIMITS, DEFAULTS } from '../constants';\n\n/** Streamed add-progress (subset). `found` carries the byte size; `allDone` the hash. */\ninterface IrohAddProgress {\n found?: { size: bigint };\n allDone?: { hash: string; format: string };\n}\n\n/** Streamed download-progress (subset). `found.size` is the BLAKE3-verified total. */\ninterface IrohDownloadProgress {\n found?: { size: bigint };\n progress?: { offset: bigint };\n allDone?: { bytesWritten: bigint };\n}\n\ninterface IrohTicket {\n hash: string;\n format: string;\n asDownloadOptions(): unknown;\n toString(): string;\n}\n\ninterface IrohBlobs {\n addFromPath(\n path: string,\n inPlace: boolean,\n tag: unknown,\n wrap: { wrap: boolean },\n cb: (err: Error | null, progress: IrohAddProgress) => void,\n ): Promise<void>;\n addBytes(bytes: number[]): Promise<{ hash: string; format: string; size: bigint }>;\n share(hash: string, blobFormat: string, addrInfoOptions: string): Promise<IrohTicket>;\n download(\n hash: string,\n opts: unknown,\n cb: (err: Error | null, progress: IrohDownloadProgress) => void,\n ): Promise<void>;\n export(hash: string, destination: string, format: string, mode: string): Promise<void>;\n readToBytes(hash: string): Promise<number[]>;\n size(hash: string): Promise<bigint>;\n deleteBlob(hash: string): Promise<void>;\n}\n\ninterface IrohNode {\n blobs: IrohBlobs;\n node: { shutdown(): Promise<void> };\n}\n\ninterface IrohModule {\n Iroh: { persistent(path: string): Promise<IrohNode> };\n SetTagOption: { auto(): unknown };\n BlobTicket: { fromString(ticket: string): IrohTicket };\n}\n\n/** Outcome of seeding a file: a shareable ticket plus the blob's byte size. */\nexport interface SeedResult {\n ticket: string;\n size: number;\n}\n\nexport interface FetchOptions {\n /** Hard cap on the BLAKE3-verified blob size; defaults to `LIMITS.MAX_FILE_SIZE`. */\n maxBytes?: number;\n /** Per-fetch timeout; defaults to `DEFAULTS.IROH_FETCH_TIMEOUT_MS`. */\n timeoutMs?: number;\n}\n\n/**\n * Node-to-node blob transport. Files move path-based (streamed to/from disk),\n * never buffered whole in memory.\n */\nexport interface IrohBlobTransport {\n /** Add a file to the local store and return a shareable ticket + its byte size. */\n seedPath(path: string): Promise<SeedResult>;\n /** Add an in-memory buffer to the local store (e.g. large inline text). */\n seedBytes(bytes: Uint8Array): Promise<SeedResult>;\n /** Download a blob by ticket and export it to `dest`, bounded by size + timeout. */\n fetchToPath(ticket: string, dest: string, options?: FetchOptions): Promise<void>;\n /**\n * Download a blob by ticket and return it as bytes, bounded by size + timeout.\n * The whole blob is held in memory, so callers MUST pass a tight `maxBytes`\n * (e.g. `LIMITS.MAX_REINLINE_TEXT_BYTES`) - the cap is enforced on the\n * BLAKE3-verified size BEFORE the blob is read into memory.\n */\n fetchToBytes(ticket: string, options?: FetchOptions): Promise<Uint8Array>;\n /** Re-share an already-stored blob to mint a fresh ticket (e.g. after a restart). */\n reShare(ticket: string): Promise<string>;\n /** Shut the node down, releasing the fs-store lock. Safe if the node was never created. */\n shutdown(): Promise<void>;\n}\n\nexport interface CreateIrohTransportOptions {\n /** Directory for the persistent fs-store (e.g. `<agent-dir>/.iroh/`). */\n storePath: string;\n}\n\nconst ADDR_INFO_RELAY_AND_ADDRESSES = 'RelayAndAddresses';\nconst EXPORT_FORMAT_BLOB = 'Blob';\nconst EXPORT_MODE_COPY = 'Copy';\n\n// Specifiers are passed through variables so bundlers (Vite/esbuild) leave the\n// dynamic import for the Node loader at runtime - we never want the native addon\n// bundled. The published `package.json` has a non-standard `main`: Node's CJS\n// loader falls back to `index.js`, but stricter loaders (e.g. vite-node under the\n// test runner) do not, so we fall back to the explicit `/index.js` subpath.\nconst IROH_MODULE_IDS = ['@number0/iroh', '@number0/iroh/index.js'];\n\nasync function loadIrohModule(): Promise<IrohModule> {\n let lastError: unknown;\n for (const moduleId of IROH_MODULE_IDS) {\n try {\n return (await import(moduleId)) as unknown as IrohModule;\n } catch (cause) {\n lastError = cause;\n }\n }\n throw new Error(\n 'iroh file transfer is unavailable: the optional @number0/iroh native addon is not installed.',\n { cause: lastError },\n );\n}\n\nfunction rejectAfter(\n timeoutMs: number,\n label: string,\n): { promise: Promise<never>; cancel: () => void } {\n let timer: ReturnType<typeof setTimeout>;\n const promise = new Promise<never>((_resolve, reject) => {\n timer = setTimeout(\n () => reject(new Error(`${label} timed out after ${timeoutMs}ms`)),\n timeoutMs,\n );\n });\n return { promise, cancel: () => clearTimeout(timer) };\n}\n\n/**\n * Create a lazily-initialized iroh transport bound to a persistent fs-store.\n * The node (and the native addon import) is created on first use and shared\n * single-flight across concurrent callers.\n */\nexport function createIrohTransport(options: CreateIrohTransportOptions): IrohBlobTransport {\n let nodePromise: Promise<{ module: IrohModule; node: IrohNode }> | null = null;\n\n const getNode = (): Promise<{ module: IrohModule; node: IrohNode }> => {\n if (!nodePromise) {\n const pending = (async () => {\n const module = await loadIrohModule();\n const node = await module.Iroh.persistent(options.storePath);\n return { module, node };\n })();\n nodePromise = pending;\n // Never cache a rejection: a failed node creation (e.g. another process is\n // briefly holding the fs-store lock) must not permanently disable the\n // transport. Clear it so the next call retries; concurrent in-flight callers\n // still share this single attempt.\n pending.catch(() => {\n if (nodePromise === pending) {\n nodePromise = null;\n }\n });\n }\n return nodePromise;\n };\n\n const seedPath = async (path: string): Promise<SeedResult> => {\n const { module, node } = await getNode();\n let size = 0;\n const outcome = await new Promise<{ hash: string; format: string }>((resolve, reject) => {\n node.blobs\n .addFromPath(path, false, module.SetTagOption.auto(), { wrap: false }, (err, progress) => {\n if (err !== null) {\n reject(err);\n return;\n }\n if (progress.found !== undefined) {\n size = Number(progress.found.size);\n }\n if (progress.allDone !== undefined) {\n resolve(progress.allDone);\n }\n })\n .catch(reject);\n });\n const ticket = await node.blobs.share(\n outcome.hash,\n outcome.format,\n ADDR_INFO_RELAY_AND_ADDRESSES,\n );\n return { ticket: ticket.toString(), size };\n };\n\n const seedBytes = async (bytes: Uint8Array): Promise<SeedResult> => {\n const { node } = await getNode();\n const outcome = await node.blobs.addBytes(Array.from(bytes));\n const ticket = await node.blobs.share(\n outcome.hash,\n outcome.format,\n ADDR_INFO_RELAY_AND_ADDRESSES,\n );\n return { ticket: ticket.toString(), size: Number(outcome.size) };\n };\n\n // Download a blob by ticket, enforcing the size cap on the BLAKE3-verified\n // total and a per-fetch timeout, deleting any (partial) blob on failure.\n // Returns the node + hash so the caller can export to disk or read to memory.\n const downloadBounded = async (\n ticketStr: string,\n fetchOptions: FetchOptions | undefined,\n ): Promise<{ node: IrohNode; hash: string }> => {\n const { module, node } = await getNode();\n const maxBytes = fetchOptions?.maxBytes ?? LIMITS.MAX_FILE_SIZE;\n const timeoutMs = fetchOptions?.timeoutMs ?? DEFAULTS.IROH_FETCH_TIMEOUT_MS;\n const ticket = module.BlobTicket.fromString(ticketStr);\n const hash = ticket.hash;\n\n const timeout = rejectAfter(timeoutMs, 'iroh fetch');\n try {\n await Promise.race([\n timeout.promise,\n new Promise<void>((resolve, reject) => {\n node.blobs\n .download(hash, ticket.asDownloadOptions(), (err, progress) => {\n if (err !== null) {\n reject(err);\n return;\n }\n // Enforce on the BLAKE3-verified size, never the descriptor's claim.\n if (progress.found !== undefined && Number(progress.found.size) > maxBytes) {\n reject(\n new Error(\n `file exceeds MAX_FILE_SIZE: ${progress.found.size} > ${maxBytes} bytes`,\n ),\n );\n return;\n }\n if (progress.progress !== undefined && Number(progress.progress.offset) > maxBytes) {\n reject(\n new Error(`file exceeds MAX_FILE_SIZE during transfer (> ${maxBytes} bytes)`),\n );\n return;\n }\n if (progress.allDone !== undefined) {\n resolve();\n }\n })\n .catch(reject);\n }),\n ]);\n } catch (error) {\n // Best-effort reclaim of any (partial) data for the rejected blob. The napi\n // binding exposes no mid-transfer cancel, so an oversized transfer may finish\n // in the background before this runs; the cap still prevents the caller from\n // exporting/using it, and this keeps the store from retaining it.\n await node.blobs.deleteBlob(hash).catch(() => {});\n throw error;\n } finally {\n timeout.cancel();\n }\n // Re-check the verified size against the cap. The progress-callback guard\n // above only fires while bytes transfer; a blob ALREADY resident in the local\n // store completes via `allDone` alone (no `found`/`progress`), so without this\n // an oversized resident blob would slip past the cap before `readToBytes`\n // pulls it into memory. `blobs.size` reports the BLAKE3-verified total.\n const verifiedSize = Number(await node.blobs.size(hash));\n if (verifiedSize > maxBytes) {\n await node.blobs.deleteBlob(hash).catch(() => {});\n throw new Error(`file exceeds MAX_FILE_SIZE: ${verifiedSize} > ${maxBytes} bytes`);\n }\n return { node, hash };\n };\n\n const fetchToPath = async (\n ticketStr: string,\n dest: string,\n fetchOptions?: FetchOptions,\n ): Promise<void> => {\n const { node, hash } = await downloadBounded(ticketStr, fetchOptions);\n await node.blobs.export(hash, dest, EXPORT_FORMAT_BLOB, EXPORT_MODE_COPY);\n };\n\n const fetchToBytes = async (\n ticketStr: string,\n fetchOptions?: FetchOptions,\n ): Promise<Uint8Array> => {\n const { node, hash } = await downloadBounded(ticketStr, fetchOptions);\n // The cap was enforced on the verified size during download, so reading the\n // whole blob into memory here is bounded by the caller's maxBytes.\n const bytes = await node.blobs.readToBytes(hash);\n return Uint8Array.from(bytes);\n };\n\n const reShare = async (ticketStr: string): Promise<string> => {\n const { module, node } = await getNode();\n const ticket = module.BlobTicket.fromString(ticketStr);\n const fresh = await node.blobs.share(ticket.hash, ticket.format, ADDR_INFO_RELAY_AND_ADDRESSES);\n return fresh.toString();\n };\n\n const shutdown = async (): Promise<void> => {\n if (!nodePromise) {\n return;\n }\n const pending = nodePromise;\n nodePromise = null;\n const loaded = await pending.catch(() => null);\n if (loaded) {\n await loaded.node.node.shutdown();\n }\n };\n\n return { seedPath, seedBytes, fetchToPath, fetchToBytes, reShare, shutdown };\n}\n"]}
package/dist/skills.cjs CHANGED
@@ -4,6 +4,7 @@ var child_process = require('child_process');
4
4
  var string_decoder = require('string_decoder');
5
5
  var promises = require('fs/promises');
6
6
  var path = require('path');
7
+ var os = require('os');
7
8
  var fs = require('fs');
8
9
  var YAML = require('yaml');
9
10
  var Decimal = require('decimal.js-light');
@@ -63,6 +64,14 @@ function runScript(cmd, args, opts) {
63
64
  }
64
65
  });
65
66
  }
67
+ var SECRET_ENV_VARS = ["ANTHROPIC_API_KEY", "OPENAI_API_KEY"];
68
+ function scopedToolEnv() {
69
+ const env = { ...process.env };
70
+ for (const key of SECRET_ENV_VARS) {
71
+ delete env[key];
72
+ }
73
+ return env;
74
+ }
66
75
  var ScriptSkill = class {
67
76
  name;
68
77
  description;
@@ -184,13 +193,21 @@ var ScriptSkill = class {
184
193
  if (value === void 0) {
185
194
  continue;
186
195
  }
196
+ const stringValue = String(value);
197
+ if (stringValue.startsWith("-")) {
198
+ return `Error: tool "${toolDef.name}" argument "${param.name}" must not begin with "-".`;
199
+ }
187
200
  if (param.required && index === 0) {
188
- args.push(String(value));
201
+ args.push(stringValue);
189
202
  } else {
190
- args.push(`--${param.name}`, String(value));
203
+ args.push(`--${param.name}`, stringValue);
191
204
  }
192
205
  }
193
- const result = await runScript(cmd, args, { cwd: this.skillDir, signal });
206
+ const result = await runScript(cmd, args, {
207
+ cwd: this.skillDir,
208
+ signal,
209
+ env: scopedToolEnv()
210
+ });
194
211
  if (result.spawnError) {
195
212
  return `Error: ${result.spawnError.message}`;
196
213
  }
@@ -253,6 +270,16 @@ var ScriptBillingExhaustedError = class extends Error {
253
270
  this.stderr = stderr;
254
271
  }
255
272
  };
273
+ var ScriptExecutionError = class extends Error {
274
+ exitCode;
275
+ detail;
276
+ constructor(exitCode, detail, summary) {
277
+ super(summary ?? `script failed (exit ${exitCode ?? "unknown"})`);
278
+ this.name = "ScriptExecutionError";
279
+ this.exitCode = exitCode;
280
+ this.detail = detail;
281
+ }
282
+ };
256
283
 
257
284
  // src/skills/staticScriptSkill.ts
258
285
  var StaticScriptSkill = class {
@@ -291,19 +318,23 @@ var StaticScriptSkill = class {
291
318
  env: this.scriptEnv
292
319
  });
293
320
  if (result.spawnError) {
294
- throw new Error(`script spawn failed: ${result.spawnError.message}`);
321
+ throw new ScriptExecutionError(
322
+ null,
323
+ result.spawnError.message,
324
+ "script could not be started"
325
+ );
295
326
  }
296
327
  if (result.code === SCRIPT_EXIT_BILLING_EXHAUSTED) {
297
328
  throw new ScriptBillingExhaustedError(result.code, result.stdout, result.stderr);
298
329
  }
299
330
  if (result.code !== 0) {
300
331
  const detail = result.stderr.trim() || result.stdout.trim() || "(no output)";
301
- throw new Error(`script failed (exit ${result.code}): ${detail}`);
332
+ throw new ScriptExecutionError(result.code, detail);
302
333
  }
303
334
  const output = result.stdout.trim();
304
335
  if (output === "") {
305
336
  const detail = result.stderr.trim() || "(no stderr)";
306
- throw new Error(`script exited 0 but produced empty output: ${detail}`);
337
+ throw new ScriptExecutionError(result.code, detail, "script produced empty output");
307
338
  }
308
339
  return { data: output };
309
340
  }
@@ -322,6 +353,7 @@ var DynamicScriptSkill = class {
322
353
  scriptArgs;
323
354
  scriptTimeoutMs;
324
355
  scriptEnv;
356
+ outputMime;
325
357
  constructor(params) {
326
358
  this.name = params.name;
327
359
  this.description = params.description;
@@ -335,31 +367,65 @@ var DynamicScriptSkill = class {
335
367
  this.scriptArgs = params.scriptArgs;
336
368
  this.scriptTimeoutMs = params.scriptTimeoutMs;
337
369
  this.scriptEnv = params.scriptEnv;
370
+ this.outputMime = params.outputMime;
338
371
  }
339
372
  async execute(input, ctx) {
340
- const result = await runScript(this.scriptPath, this.scriptArgs, {
341
- cwd: path.dirname(this.scriptPath),
342
- stdin: input.data,
343
- signal: ctx.signal,
344
- timeoutMs: this.scriptTimeoutMs,
345
- env: this.scriptEnv
346
- });
347
- if (result.spawnError) {
348
- throw new Error(`script spawn failed: ${result.spawnError.message}`);
373
+ const outDir = await promises.mkdtemp(path.join(os.tmpdir(), "elisym-skill-out-"));
374
+ const outputFile = path.join(outDir, "output");
375
+ const env = {
376
+ ...this.scriptEnv ?? process.env,
377
+ ELISYM_OUTPUT_FILE: outputFile
378
+ };
379
+ if (input.filePath !== void 0) {
380
+ env.ELISYM_INPUT_FILE = input.filePath;
349
381
  }
350
- if (result.code === SCRIPT_EXIT_BILLING_EXHAUSTED) {
351
- throw new ScriptBillingExhaustedError(result.code, result.stdout, result.stderr);
352
- }
353
- if (result.code !== 0) {
354
- const detail = result.stderr.trim() || result.stdout.trim() || "(no output)";
355
- throw new Error(`script failed (exit ${result.code}): ${detail}`);
356
- }
357
- const output = result.stdout.trim();
358
- if (output === "") {
359
- const detail = result.stderr.trim() || "(no stderr)";
360
- throw new Error(`script exited 0 but produced empty output: ${detail}`);
382
+ let keepOutDir = false;
383
+ try {
384
+ const result = await runScript(this.scriptPath, this.scriptArgs, {
385
+ cwd: path.dirname(this.scriptPath),
386
+ stdin: input.data,
387
+ signal: ctx.signal,
388
+ timeoutMs: this.scriptTimeoutMs,
389
+ env
390
+ });
391
+ if (result.spawnError) {
392
+ throw new ScriptExecutionError(
393
+ null,
394
+ result.spawnError.message,
395
+ "script could not be started"
396
+ );
397
+ }
398
+ if (result.code === SCRIPT_EXIT_BILLING_EXHAUSTED) {
399
+ throw new ScriptBillingExhaustedError(result.code, result.stdout, result.stderr);
400
+ }
401
+ if (result.code !== 0) {
402
+ const detail = result.stderr.trim() || result.stdout.trim() || "(no output)";
403
+ throw new ScriptExecutionError(result.code, detail);
404
+ }
405
+ const outputStat = await promises.stat(outputFile).catch(() => null);
406
+ if (outputStat !== null && outputStat.isFile() && outputStat.size > 0) {
407
+ keepOutDir = true;
408
+ return {
409
+ data: result.stdout.trim(),
410
+ filePath: outputFile,
411
+ outputMime: this.outputMime ?? "application/octet-stream",
412
+ cleanup: async () => {
413
+ await promises.rm(outDir, { recursive: true, force: true });
414
+ }
415
+ };
416
+ }
417
+ const output = result.stdout.trim();
418
+ if (output === "") {
419
+ const detail = result.stderr.trim() || "(no stderr)";
420
+ throw new ScriptExecutionError(result.code, detail, "script produced empty output");
421
+ }
422
+ return { data: output };
423
+ } finally {
424
+ if (!keepOutDir) {
425
+ await promises.rm(outDir, { recursive: true, force: true }).catch(() => {
426
+ });
427
+ }
361
428
  }
362
- return { data: output };
363
429
  }
364
430
  };
365
431
  function resolveInsidePath(rootDir, value) {
@@ -371,13 +437,13 @@ function resolveInsidePath(rootDir, value) {
371
437
  }
372
438
  return candidate;
373
439
  }
374
- var LAMPORTS_PER_SOL = 1e9;
375
440
  var LIMITS = {
376
441
  // Upper bound for execution budgets (`max_execution_secs` / `execution_timeout_secs`).
377
442
  // Distinct from MAX_TIMEOUT_SECS (the result-wait cap): execution budgets may be
378
443
  // hours, so this exists only to keep `secs * 1000` within Node's setTimeout limit
379
444
  // (2_147_483_647 ms) - a larger value overflows and fires the timer immediately.
380
445
  MAX_EXECUTION_SECS: 2147483};
446
+ new TextEncoder();
381
447
  var NATIVE_SOL = {
382
448
  chain: "solana",
383
449
  token: "sol",
@@ -454,11 +520,15 @@ var VALID_MODES = [
454
520
  "dynamic-script"
455
521
  ];
456
522
  function solToLamports(sol) {
457
- const asNumber = typeof sol === "string" ? Number(sol) : sol;
458
- if (!Number.isFinite(asNumber) || asNumber < 0) {
523
+ const asString = (typeof sol === "string" ? sol : String(sol)).trim();
524
+ if (/^0+(?:\.0+)?$/.test(asString)) {
525
+ return 0n;
526
+ }
527
+ try {
528
+ return parseAssetAmount(NATIVE_SOL, asString);
529
+ } catch {
459
530
  throw new Error(`Invalid SOL amount: ${sol}`);
460
531
  }
461
- return BigInt(Math.round(asNumber * LAMPORTS_PER_SOL));
462
532
  }
463
533
  function resolveSkillAsset(skillName, token, mint) {
464
534
  if (token === void 0 || token === null) {
@@ -671,6 +741,34 @@ function validateScriptTimeoutMs(skillName, raw) {
671
741
  }
672
742
  return raw;
673
743
  }
744
+ function validateOutputMime(skillName, raw) {
745
+ if (raw === void 0 || raw === null) {
746
+ return void 0;
747
+ }
748
+ if (typeof raw !== "string" || raw.length === 0) {
749
+ throw new Error(
750
+ `SKILL.md "${skillName}": "output_mime" must be a non-empty string (e.g. "image/png")`
751
+ );
752
+ }
753
+ if (raw.length > 255) {
754
+ throw new Error(`SKILL.md "${skillName}": "output_mime" too long (max 255 chars)`);
755
+ }
756
+ return raw;
757
+ }
758
+ function validateInputMime(skillName, raw) {
759
+ if (raw === void 0 || raw === null) {
760
+ return void 0;
761
+ }
762
+ if (typeof raw !== "string" || raw.length === 0) {
763
+ throw new Error(
764
+ `SKILL.md "${skillName}": "input_mime" must be a non-empty string (e.g. "image/png" or "*")`
765
+ );
766
+ }
767
+ if (raw.length > 255) {
768
+ throw new Error(`SKILL.md "${skillName}": "input_mime" too long (max 255 chars)`);
769
+ }
770
+ return raw;
771
+ }
674
772
  function validateMaxExecutionSecs(skillName, raw) {
675
773
  if (raw === void 0 || raw === null) {
676
774
  return void 0;
@@ -722,7 +820,7 @@ function validateSkillFrontmatter(frontmatter, systemPrompt, options = {}) {
722
820
  }
723
821
  const priceString = typeof priceRaw === "number" ? String(priceRaw) : priceRaw;
724
822
  if (asset === NATIVE_SOL) {
725
- priceSubunits = solToLamports(priceRaw);
823
+ priceSubunits = solToLamports(priceString);
726
824
  } else {
727
825
  try {
728
826
  priceSubunits = parseAssetAmount(asset, priceString);
@@ -771,6 +869,8 @@ function validateSkillFrontmatter(frontmatter, systemPrompt, options = {}) {
771
869
  let script;
772
870
  let scriptArgs = [];
773
871
  let scriptTimeoutMs;
872
+ let outputMime;
873
+ let inputMime;
774
874
  if (mode === "static-file") {
775
875
  if (typeof frontmatter.output_file !== "string" || frontmatter.output_file.length === 0) {
776
876
  throw new Error(
@@ -782,6 +882,16 @@ function validateSkillFrontmatter(frontmatter, systemPrompt, options = {}) {
782
882
  `SKILL.md "${frontmatter.name}": "script" is not valid in mode 'static-file'`
783
883
  );
784
884
  }
885
+ if (frontmatter.output_mime !== void 0) {
886
+ throw new Error(
887
+ `SKILL.md "${frontmatter.name}": "output_mime" is only valid in mode 'dynamic-script'`
888
+ );
889
+ }
890
+ if (frontmatter.input_mime !== void 0) {
891
+ throw new Error(
892
+ `SKILL.md "${frontmatter.name}": "input_mime" is only valid in mode 'dynamic-script'`
893
+ );
894
+ }
785
895
  outputFile = frontmatter.output_file;
786
896
  } else if (mode === "static-script" || mode === "dynamic-script") {
787
897
  if (typeof frontmatter.script !== "string" || frontmatter.script.length === 0) {
@@ -795,6 +905,21 @@ function validateSkillFrontmatter(frontmatter, systemPrompt, options = {}) {
795
905
  script = frontmatter.script;
796
906
  scriptArgs = validateScriptArgs(frontmatter.name, frontmatter.script_args);
797
907
  scriptTimeoutMs = validateScriptTimeoutMs(frontmatter.name, frontmatter.script_timeout_ms);
908
+ if (mode === "dynamic-script") {
909
+ outputMime = validateOutputMime(frontmatter.name, frontmatter.output_mime);
910
+ inputMime = validateInputMime(frontmatter.name, frontmatter.input_mime);
911
+ } else {
912
+ if (frontmatter.output_mime !== void 0) {
913
+ throw new Error(
914
+ `SKILL.md "${frontmatter.name}": "output_mime" is only valid in mode 'dynamic-script'`
915
+ );
916
+ }
917
+ if (frontmatter.input_mime !== void 0) {
918
+ throw new Error(
919
+ `SKILL.md "${frontmatter.name}": "input_mime" is only valid in mode 'dynamic-script'`
920
+ );
921
+ }
922
+ }
798
923
  } else {
799
924
  if (frontmatter.output_file !== void 0) {
800
925
  throw new Error(
@@ -816,6 +941,16 @@ function validateSkillFrontmatter(frontmatter, systemPrompt, options = {}) {
816
941
  `SKILL.md "${frontmatter.name}": "script_timeout_ms" is only valid in script modes`
817
942
  );
818
943
  }
944
+ if (frontmatter.output_mime !== void 0) {
945
+ throw new Error(
946
+ `SKILL.md "${frontmatter.name}": "output_mime" is only valid in mode 'dynamic-script'`
947
+ );
948
+ }
949
+ if (frontmatter.input_mime !== void 0) {
950
+ throw new Error(
951
+ `SKILL.md "${frontmatter.name}": "input_mime" is only valid in mode 'dynamic-script'`
952
+ );
953
+ }
819
954
  }
820
955
  const image = typeof frontmatter.image === "string" ? frontmatter.image : void 0;
821
956
  const imageFile = typeof frontmatter.image_file === "string" ? frontmatter.image_file : void 0;
@@ -842,11 +977,21 @@ function validateSkillFrontmatter(frontmatter, systemPrompt, options = {}) {
842
977
  script,
843
978
  scriptArgs,
844
979
  scriptTimeoutMs,
980
+ outputMime,
981
+ inputMime,
845
982
  rateLimit,
846
983
  executionTimeoutSecs
847
984
  };
848
985
  }
849
986
  function buildSkillFromParsed(parsed, skillDir, logger) {
987
+ let imageFile = parsed.imageFile;
988
+ if (imageFile !== void 0 && resolveInsidePath(skillDir, imageFile) === null) {
989
+ logger.warn?.(
990
+ { skill: parsed.name, imageFile },
991
+ 'SKILL.md "image_file" escapes the skill directory; ignoring it'
992
+ );
993
+ imageFile = void 0;
994
+ }
850
995
  switch (parsed.mode) {
851
996
  case "llm":
852
997
  return new ScriptSkill({
@@ -861,7 +1006,7 @@ function buildSkillFromParsed(parsed, skillDir, logger) {
861
1006
  maxToolRounds: parsed.maxToolRounds,
862
1007
  llmOverride: parsed.llmOverride,
863
1008
  image: parsed.image,
864
- imageFile: parsed.imageFile,
1009
+ imageFile,
865
1010
  logger
866
1011
  });
867
1012
  case "static-file": {
@@ -884,7 +1029,7 @@ function buildSkillFromParsed(parsed, skillDir, logger) {
884
1029
  asset: parsed.asset,
885
1030
  outputFilePath,
886
1031
  image: parsed.image,
887
- imageFile: parsed.imageFile,
1032
+ imageFile,
888
1033
  llmOverride: parsed.llmOverride
889
1034
  });
890
1035
  }
@@ -899,8 +1044,7 @@ function buildSkillFromParsed(parsed, skillDir, logger) {
899
1044
  if (!scriptPath) {
900
1045
  throw new Error(`SKILL.md "${parsed.name}": "script" must stay inside the skill directory`);
901
1046
  }
902
- const Ctor = parsed.mode === "static-script" ? StaticScriptSkill : DynamicScriptSkill;
903
- return new Ctor({
1047
+ const scriptParams = {
904
1048
  name: parsed.name,
905
1049
  description: parsed.description,
906
1050
  capabilities: parsed.capabilities,
@@ -910,9 +1054,10 @@ function buildSkillFromParsed(parsed, skillDir, logger) {
910
1054
  scriptArgs: parsed.scriptArgs,
911
1055
  scriptTimeoutMs: parsed.scriptTimeoutMs ?? DEFAULT_SCRIPT_TIMEOUT_MS,
912
1056
  image: parsed.image,
913
- imageFile: parsed.imageFile,
1057
+ imageFile,
914
1058
  llmOverride: parsed.llmOverride
915
- });
1059
+ };
1060
+ return parsed.mode === "dynamic-script" ? new DynamicScriptSkill({ ...scriptParams, outputMime: parsed.outputMime }) : new StaticScriptSkill(scriptParams);
916
1061
  }
917
1062
  }
918
1063
  }