@keystrokehq/cli 0.1.25 → 0.1.27

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.
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import { l as getCliConfigDir, r as detectPackageManager, s as resolveCliRoot, t as readCliVersion } from "./version-DcR3O1UD.mjs";
2
+ import { l as getCliConfigDir, r as detectPackageManager, s as resolveCliRoot, t as readCliVersion } from "./version-pY9N8XlL.mjs";
3
3
  import { dirname, join } from "node:path";
4
4
  import { existsSync, mkdirSync, readFileSync, realpathSync, writeFileSync } from "node:fs";
5
5
  import { spawnSync } from "node:child_process";
@@ -405,4 +405,4 @@ async function maybeAutoUpdate(argv) {
405
405
  //#endregion
406
406
  export { maybeAutoUpdate };
407
407
 
408
- //# sourceMappingURL=maybe-auto-update-q5MthdI8.mjs.map
408
+ //# sourceMappingURL=maybe-auto-update-BDvSKDZp.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"maybe-auto-update-q5MthdI8.mjs","names":[],"sources":["../src/update/compare-version.ts","../src/update/detect-cli-install.ts","../src/update/detect-release-age-block.ts","../src/update/fetch-latest-version.ts","../src/update/read-pnpm-release-age-minutes.ts","../src/update/resolve-global-pnpm-root.ts","../src/update/build-update-command.ts","../src/update/run-package-manager-update.ts","../src/update/update-block-cache.ts","../src/update/maybe-auto-update.ts"],"sourcesContent":["function parseVersion(version: string): [number, number, number] {\n const normalized = version.trim().replace(/^v/, \"\").split(\"-\")[0] ?? \"\";\n const [major = 0, minor = 0, patch = 0] = normalized.split(\".\").map((part) => {\n const value = Number.parseInt(part, 10);\n return Number.isFinite(value) ? value : 0;\n });\n\n return [major, minor, patch];\n}\n\nexport function isNewerVersion(latest: string, current: string): boolean {\n const [latestMajor, latestMinor, latestPatch] = parseVersion(latest);\n const [currentMajor, currentMinor, currentPatch] = parseVersion(current);\n\n if (latestMajor !== currentMajor) {\n return latestMajor > currentMajor;\n }\n\n if (latestMinor !== currentMinor) {\n return latestMinor > currentMinor;\n }\n\n return latestPatch > currentPatch;\n}\n","import { existsSync, realpathSync } from \"node:fs\";\nimport { spawnSync } from \"node:child_process\";\nimport { dirname, join } from \"node:path\";\n\nimport { detectPackageManager, type PackageManager } from \"../init/package-manager\";\n\nexport type CliInstallKind = \"global\" | \"local\";\n\nexport type CliInstallInfo = {\n kind: CliInstallKind;\n packageManager: PackageManager;\n packageRoot: string;\n projectRoot?: string;\n};\n\nfunction realpathSafe(path: string): string {\n try {\n return realpathSync(path);\n } catch {\n return path;\n }\n}\n\nfunction detectManagerFromLockfile(dir: string): PackageManager | undefined {\n if (existsSync(join(dir, \"pnpm-lock.yaml\"))) {\n return \"pnpm\";\n }\n\n if (existsSync(join(dir, \"bun.lockb\")) || existsSync(join(dir, \"bun.lock\"))) {\n return \"bun\";\n }\n\n if (existsSync(join(dir, \"yarn.lock\"))) {\n return \"yarn\";\n }\n\n if (existsSync(join(dir, \"package-lock.json\"))) {\n return \"npm\";\n }\n\n return undefined;\n}\n\nfunction findLocalProjectRoot(packageRoot: string): string | undefined {\n const normalizedRoot = realpathSafe(packageRoot);\n let dir = dirname(packageRoot);\n\n while (dir !== dirname(dir)) {\n const installedCliPath = join(dir, \"node_modules\", \"@keystrokehq\", \"cli\");\n if (\n existsSync(join(dir, \"package.json\")) &&\n realpathSafe(installedCliPath) === normalizedRoot\n ) {\n return dir;\n }\n\n dir = dirname(dir);\n }\n\n return undefined;\n}\n\nfunction globalRootForManager(manager: PackageManager): string | undefined {\n const commands: Record<PackageManager, { command: string; args: string[] }> = {\n pnpm: { command: \"pnpm\", args: [\"root\", \"-g\"] },\n npm: { command: \"npm\", args: [\"root\", \"-g\"] },\n yarn: { command: \"yarn\", args: [\"global\", \"dir\"] },\n bun: { command: \"bun\", args: [\"pm\", \"bin\"] },\n };\n\n const { command, args } = commands[manager];\n const result = spawnSync(command, args, { encoding: \"utf8\" });\n\n if (result.status !== 0) {\n return undefined;\n }\n\n const root = result.stdout.trim();\n return root ? realpathSafe(root) : undefined;\n}\n\nfunction detectGlobalManager(packageRoot: string): PackageManager {\n const normalizedRoot = realpathSafe(packageRoot);\n\n if (normalizedRoot.includes(`${join(\"\", \".pnpm\")}`)) {\n return \"pnpm\";\n }\n\n for (const manager of [\"pnpm\", \"npm\", \"yarn\", \"bun\"] as const) {\n const globalRoot = globalRootForManager(manager);\n if (globalRoot && normalizedRoot.startsWith(globalRoot)) {\n return manager;\n }\n }\n\n if (process.env.PNPM_HOME) {\n return \"pnpm\";\n }\n\n return detectPackageManager();\n}\n\nexport function detectCliInstall(packageRoot: string): CliInstallInfo | undefined {\n const normalizedRoot = realpathSafe(packageRoot);\n const projectRoot = findLocalProjectRoot(normalizedRoot);\n\n if (projectRoot) {\n const packageManager = detectManagerFromLockfile(projectRoot) ?? detectPackageManager();\n\n return {\n kind: \"local\",\n packageManager,\n packageRoot: normalizedRoot,\n projectRoot,\n };\n }\n\n return {\n kind: \"global\",\n packageManager: detectGlobalManager(normalizedRoot),\n packageRoot: normalizedRoot,\n };\n}\n","const RELEASE_AGE_PATTERNS = [\n /minimumReleaseAge/i,\n /minimum-release-age/i,\n /ERR_PNPM_NO_MATURE_MATCHING_VERSION/,\n /ERR_PNPM_MINIMUM_RELEASE_AGE/,\n /does not meet the minimumReleaseAge constraint/,\n];\n\nexport function isReleaseAgeBlock(output: string): boolean {\n return RELEASE_AGE_PATTERNS.some((pattern) => pattern.test(output));\n}\n\nexport function formatReleaseAgeBlockMessage(options: {\n currentVersion: string;\n availableVersion: string;\n retryAfter?: Date;\n}): string {\n const retry =\n options.retryAfter !== undefined ? ` Retry after ${options.retryAfter.toLocaleString()}.` : \"\";\n\n return (\n `@keystrokehq/cli ${options.availableVersion} is available but blocked by your ` +\n `minimum-release-age setting. You're on ${options.currentVersion}.${retry} ` +\n `Add @keystrokehq/cli to minimumReleaseAgeExclude to install immediately.`\n );\n}\n","const REGISTRY_URL = \"https://registry.npmjs.org/@keystrokehq%2Fcli\";\nconst REQUEST_TIMEOUT_MS = 3_000;\n\ntype RegistryPackage = {\n \"dist-tags\"?: {\n latest?: string;\n };\n time?: Record<string, string>;\n};\n\nexport type CliRegistryRelease = {\n version: string;\n publishedAt?: string;\n};\n\nexport async function fetchLatestCliRelease(): Promise<CliRegistryRelease | undefined> {\n const controller = new AbortController();\n const timeout = setTimeout(() => controller.abort(), REQUEST_TIMEOUT_MS);\n\n try {\n const response = await fetch(REGISTRY_URL, {\n signal: controller.signal,\n headers: {\n Accept: \"application/json\",\n },\n });\n\n if (!response.ok) {\n return undefined;\n }\n\n const payload = (await response.json()) as RegistryPackage;\n const version = payload[\"dist-tags\"]?.latest?.trim();\n if (!version) {\n return undefined;\n }\n\n return {\n version,\n publishedAt: payload.time?.[version],\n };\n } catch {\n return undefined;\n } finally {\n clearTimeout(timeout);\n }\n}\n\nexport async function fetchLatestCliVersion(): Promise<string | undefined> {\n const release = await fetchLatestCliRelease();\n return release?.version;\n}\n","import { spawnSync } from \"node:child_process\";\n\nexport function readPnpmMinimumReleaseAgeMinutes(): number | undefined {\n const result = spawnSync(\"pnpm\", [\"config\", \"get\", \"minimum-release-age\"], {\n encoding: \"utf8\",\n });\n\n if (result.status !== 0) {\n return undefined;\n }\n\n const value = result.stdout.trim();\n if (!value || value === \"undefined\" || value === \"0\") {\n return undefined;\n }\n\n const minutes = Number.parseInt(value, 10);\n return Number.isFinite(minutes) && minutes > 0 ? minutes : undefined;\n}\n\nexport function computeReleaseAgeRetryAfter(\n publishedAt: string | undefined,\n minimumReleaseAgeMinutes: number | undefined,\n): Date | undefined {\n if (!publishedAt || !minimumReleaseAgeMinutes) {\n return undefined;\n }\n\n const publishedMs = Date.parse(publishedAt);\n if (!Number.isFinite(publishedMs)) {\n return undefined;\n }\n\n return new Date(publishedMs + minimumReleaseAgeMinutes * 60_000);\n}\n","/** pnpm global installs live in `<pnpm-home>/global/<major>/`. */\nexport function resolveGlobalPnpmRoot(packageRoot: string): string | undefined {\n const normalized = packageRoot.replace(/\\\\/g, \"/\");\n const match = normalized.match(/^(.*\\/global\\/\\d+)\\//);\n return match?.[1];\n}\n","import type { CliInstallInfo } from \"./detect-cli-install\";\nimport { resolveGlobalPnpmRoot } from \"./resolve-global-pnpm-root\";\n\nconst PACKAGE_NAME = \"@keystrokehq/cli@latest\";\n\nexport function buildUpdateCommand(install: CliInstallInfo): {\n command: string;\n args: string[];\n cwd?: string;\n} {\n const { kind, packageManager } = install;\n\n if (kind === \"global\") {\n switch (packageManager) {\n case \"pnpm\":\n return {\n command: \"pnpm\",\n args: [\"add\", \"-g\", PACKAGE_NAME],\n cwd: resolveGlobalPnpmRoot(install.packageRoot),\n };\n case \"yarn\":\n return { command: \"yarn\", args: [\"global\", \"add\", PACKAGE_NAME] };\n case \"bun\":\n return { command: \"bun\", args: [\"add\", \"-g\", PACKAGE_NAME] };\n case \"npm\":\n default:\n return { command: \"npm\", args: [\"install\", \"-g\", PACKAGE_NAME] };\n }\n }\n\n const cwd = install.projectRoot;\n switch (packageManager) {\n case \"pnpm\":\n return { command: \"pnpm\", args: [\"add\", \"-D\", PACKAGE_NAME], cwd };\n case \"yarn\":\n return { command: \"yarn\", args: [\"add\", \"-D\", PACKAGE_NAME], cwd };\n case \"bun\":\n return { command: \"bun\", args: [\"add\", \"-D\", PACKAGE_NAME], cwd };\n case \"npm\":\n default:\n return { command: \"npm\", args: [\"install\", \"-D\", PACKAGE_NAME], cwd };\n }\n}\n","import { spawnSync } from \"node:child_process\";\n\nimport { buildUpdateCommand } from \"./build-update-command\";\nimport type { CliInstallInfo } from \"./detect-cli-install\";\n\nexport function updateSpawnEnv(): NodeJS.ProcessEnv {\n const env = { ...process.env };\n const pnpmHome = env.PNPM_HOME;\n\n if (!pnpmHome) {\n return env;\n }\n\n const pathKey = process.platform === \"win32\" ? \"Path\" : \"PATH\";\n const path = env[pathKey] ?? \"\";\n const segments = path.split(process.platform === \"win32\" ? \";\" : \":\");\n const binDir = `${pnpmHome}/bin`;\n const prefix = [binDir, pnpmHome].filter((dir) => !segments.includes(dir));\n\n if (prefix.length > 0) {\n env[pathKey] = [...prefix, path].filter(Boolean).join(process.platform === \"win32\" ? \";\" : \":\");\n }\n\n return env;\n}\n\nexport type PackageManagerRunResult = {\n ok: boolean;\n output: string;\n};\n\nfunction runPackageManager(command: string, args: string[], cwd?: string): PackageManagerRunResult {\n const result = spawnSync(command, args, {\n cwd,\n encoding: \"utf8\",\n env: updateSpawnEnv(),\n });\n\n const output = `${result.stdout ?? \"\"}${result.stderr ?? \"\"}`;\n\n return {\n ok: result.status === 0,\n output,\n };\n}\n\nfunction migratePnpmGlobal(cwd: string): boolean {\n const result = spawnSync(\"pnpm\", [\"install\"], {\n cwd,\n encoding: \"utf8\",\n env: {\n ...updateSpawnEnv(),\n CI: \"true\",\n },\n });\n\n return result.status === 0;\n}\n\nexport function runPackageManagerUpdate(install: CliInstallInfo): PackageManagerRunResult {\n const { command, args, cwd } = buildUpdateCommand(install);\n const firstAttempt = runPackageManager(command, args, cwd);\n\n if (firstAttempt.ok) {\n return firstAttempt;\n }\n\n if (install.kind === \"global\" && install.packageManager === \"pnpm\" && cwd) {\n if (migratePnpmGlobal(cwd)) {\n return runPackageManager(command, args, cwd);\n }\n }\n\n return firstAttempt;\n}\n","import { existsSync, mkdirSync, readFileSync, writeFileSync } from \"node:fs\";\nimport { join } from \"node:path\";\n\nimport { getCliConfigDir } from \"../config\";\n\nexport type UpdateBlockCache = {\n registryLatest?: string;\n blockedUntil?: string;\n lastFailedAt?: string;\n};\n\nconst CACHE_FILE = \"update-check.json\";\nconst GENERIC_RETRY_MS = 24 * 60 * 60 * 1000;\n\nfunction cachePath(configDir = getCliConfigDir()): string {\n return join(configDir, CACHE_FILE);\n}\n\nexport function readUpdateBlockCache(configDir?: string): UpdateBlockCache {\n const path = cachePath(configDir);\n if (!existsSync(path)) {\n return {};\n }\n\n try {\n return JSON.parse(readFileSync(path, \"utf8\")) as UpdateBlockCache;\n } catch {\n return {};\n }\n}\n\nexport function writeUpdateBlockCache(cache: UpdateBlockCache, configDir?: string): void {\n const dir = configDir ?? getCliConfigDir();\n mkdirSync(dir, { recursive: true });\n writeFileSync(cachePath(dir), `${JSON.stringify(cache, null, 2)}\\n`, \"utf8\");\n}\n\nexport function shouldSkipCachedUpdate(\n cache: UpdateBlockCache,\n registryLatest: string,\n now = Date.now(),\n): boolean {\n if (cache.registryLatest !== registryLatest) {\n return false;\n }\n\n if (cache.blockedUntil) {\n const blockedUntilMs = Date.parse(cache.blockedUntil);\n if (Number.isFinite(blockedUntilMs) && blockedUntilMs > now) {\n return true;\n }\n }\n\n if (cache.lastFailedAt) {\n const lastFailedMs = Date.parse(cache.lastFailedAt);\n if (Number.isFinite(lastFailedMs) && now - lastFailedMs < GENERIC_RETRY_MS) {\n return true;\n }\n }\n\n return false;\n}\n\nexport function clearUpdateBlockCache(configDir?: string): void {\n writeUpdateBlockCache({}, configDir);\n}\n\nexport function recordReleaseAgeBlock(options: {\n registryLatest: string;\n retryAfter?: Date;\n configDir?: string;\n}): void {\n writeUpdateBlockCache(\n {\n registryLatest: options.registryLatest,\n blockedUntil: options.retryAfter?.toISOString(),\n },\n options.configDir,\n );\n}\n\nexport function recordGenericUpdateFailure(registryLatest: string, configDir?: string): void {\n writeUpdateBlockCache(\n {\n registryLatest,\n lastFailedAt: new Date().toISOString(),\n },\n configDir,\n );\n}\n","import { spawnSync } from \"node:child_process\";\n\nimport { resolveCliRoot } from \"../project/resolve-cli-root\";\nimport { readCliVersion } from \"../version\";\nimport { isNewerVersion } from \"./compare-version\";\nimport { detectCliInstall } from \"./detect-cli-install\";\nimport { formatReleaseAgeBlockMessage, isReleaseAgeBlock } from \"./detect-release-age-block\";\nimport { fetchLatestCliRelease } from \"./fetch-latest-version\";\nimport {\n computeReleaseAgeRetryAfter,\n readPnpmMinimumReleaseAgeMinutes,\n} from \"./read-pnpm-release-age-minutes\";\nimport { runPackageManagerUpdate } from \"./run-package-manager-update\";\nimport {\n clearUpdateBlockCache,\n readUpdateBlockCache,\n recordGenericUpdateFailure,\n recordReleaseAgeBlock,\n shouldSkipCachedUpdate,\n} from \"./update-block-cache\";\n\nfunction shouldSkipAutoUpdate(argv: string[]): boolean {\n if (\n process.env.KEYSTROKE_DEV ||\n process.env.KEYSTROKE_SKIP_UPDATE ||\n process.env.KEYSTROKE_UPDATING\n ) {\n return true;\n }\n\n if (process.env.CI === \"true\" || process.env.CI === \"1\") {\n return true;\n }\n\n const args = argv.slice(2);\n if (args.length === 0) {\n return false;\n }\n\n return args.every(\n (arg) =>\n arg === \"-V\" ||\n arg === \"--version\" ||\n arg === \"-h\" ||\n arg === \"--help\" ||\n arg.startsWith(\"-V\"),\n );\n}\n\nfunction reexecCli(argv: string[]): never {\n const result = spawnSync(process.execPath, argv.slice(1), {\n stdio: \"inherit\",\n env: {\n ...process.env,\n KEYSTROKE_UPDATING: \"1\",\n },\n });\n\n process.exit(result.status ?? 1);\n}\n\nfunction releaseAgeRetryAfter(\n install: NonNullable<ReturnType<typeof detectCliInstall>>,\n publishedAt: string | undefined,\n): Date | undefined {\n if (install.packageManager !== \"pnpm\") {\n return undefined;\n }\n\n return computeReleaseAgeRetryAfter(publishedAt, readPnpmMinimumReleaseAgeMinutes());\n}\n\nexport async function maybeAutoUpdate(argv: string[]): Promise<void> {\n if (shouldSkipAutoUpdate(argv)) {\n return;\n }\n\n const install = detectCliInstall(resolveCliRoot(import.meta.url));\n if (!install || (install.kind === \"local\" && !install.projectRoot)) {\n return;\n }\n\n const currentVersion = readCliVersion();\n const release = await fetchLatestCliRelease();\n\n if (!release || !isNewerVersion(release.version, currentVersion)) {\n clearUpdateBlockCache();\n return;\n }\n\n const cache = readUpdateBlockCache();\n if (shouldSkipCachedUpdate(cache, release.version)) {\n return;\n }\n\n process.stderr.write(\n `Updating @keystrokehq/cli ${currentVersion} -> ${release.version} via ${install.packageManager}...\\n`,\n );\n\n const result = runPackageManagerUpdate(install);\n const installedVersion = readCliVersion();\n\n if (isNewerVersion(installedVersion, currentVersion)) {\n clearUpdateBlockCache();\n process.stderr.write(`Updated @keystrokehq/cli ${currentVersion} -> ${installedVersion}.\\n`);\n reexecCli(argv);\n }\n\n if (result.ok) {\n clearUpdateBlockCache();\n return;\n }\n\n if (isReleaseAgeBlock(result.output)) {\n const retryAfter = releaseAgeRetryAfter(install, release.publishedAt);\n recordReleaseAgeBlock({\n registryLatest: release.version,\n retryAfter,\n });\n process.stderr.write(\n `${formatReleaseAgeBlockMessage({\n currentVersion,\n availableVersion: release.version,\n retryAfter,\n })}\\n`,\n );\n return;\n }\n\n recordGenericUpdateFailure(release.version);\n process.stderr.write(\"Auto-update failed; continuing with the current version.\\n\");\n}\n"],"mappings":";;;;;;AAAA,SAAS,aAAa,SAA2C;CAE/D,MAAM,CAAC,QAAQ,GAAG,QAAQ,GAAG,QAAQ,MADlB,QAAQ,KAAK,EAAE,QAAQ,MAAM,EAAE,EAAE,MAAM,GAAG,EAAE,MAAM,IAChB,MAAM,GAAG,EAAE,KAAK,SAAS;EAC5E,MAAM,QAAQ,OAAO,SAAS,MAAM,EAAE;EACtC,OAAO,OAAO,SAAS,KAAK,IAAI,QAAQ;CAC1C,CAAC;CAED,OAAO;EAAC;EAAO;EAAO;CAAK;AAC7B;AAEA,SAAgB,eAAe,QAAgB,SAA0B;CACvE,MAAM,CAAC,aAAa,aAAa,eAAe,aAAa,MAAM;CACnE,MAAM,CAAC,cAAc,cAAc,gBAAgB,aAAa,OAAO;CAEvE,IAAI,gBAAgB,cAClB,OAAO,cAAc;CAGvB,IAAI,gBAAgB,cAClB,OAAO,cAAc;CAGvB,OAAO,cAAc;AACvB;;;ACRA,SAAS,aAAa,MAAsB;CAC1C,IAAI;EACF,OAAO,aAAa,IAAI;CAC1B,QAAQ;EACN,OAAO;CACT;AACF;AAEA,SAAS,0BAA0B,KAAyC;CAC1E,IAAI,WAAW,KAAK,KAAK,gBAAgB,CAAC,GACxC,OAAO;CAGT,IAAI,WAAW,KAAK,KAAK,WAAW,CAAC,KAAK,WAAW,KA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AQ,eAAe,MAClG;CAEA,MAAM,SAAS,wBAAwB,OAAO;CAC9C,MAAM,mBAAmB,eAAe;CAExC,IAAI,eAAe,kBAAkB,cAAc,GAAG;EACpD,sBAAsB;EACtB,QAAQ,OAAO,MAAM,4BAA4B,eAAe,MAAM,iBAAiB,IAAI;EAC3F,UAAU,IAAI;CAChB;CAEA,IAAI,OAAO,IAAI;EACb,sBAAsB;EACtB;CACF;CAEA,IAAI,kBAAkB,OAAO,MAAM,GAAG;EACpC,MAAM,aAAa,qBAAqB,SAAS,QAAQ,WAAW;EACpE,sBAAsB;GACpB,gBAAgB,QAAQ;GACxB;EACF,CAAC;EACD,QAAQ,OAAO,MACb,GAAG,6BAA6B;GAC9B;GACA,kBAAkB,QAAQ;GAC1B;EACF,CAAC,EAAE,GACL;EACA;CACF;CAEA,2BAA2B,QAAQ,OAAO;CAC1C,QAAQ,OAAO,MAAM,4DAA4D;AACnF"}
1
+ {"version":3,"file":"maybe-auto-update-BDvSKDZp.mjs","names":[],"sources":["../src/update/compare-version.ts","../src/update/detect-cli-install.ts","../src/update/detect-release-age-block.ts","../src/update/fetch-latest-version.ts","../src/update/read-pnpm-release-age-minutes.ts","../src/update/resolve-global-pnpm-root.ts","../src/update/build-update-command.ts","../src/update/run-package-manager-update.ts","../src/update/update-block-cache.ts","../src/update/maybe-auto-update.ts"],"sourcesContent":["function parseVersion(version: string): [number, number, number] {\n const normalized = version.trim().replace(/^v/, \"\").split(\"-\")[0] ?? \"\";\n const [major = 0, minor = 0, patch = 0] = normalized.split(\".\").map((part) => {\n const value = Number.parseInt(part, 10);\n return Number.isFinite(value) ? value : 0;\n });\n\n return [major, minor, patch];\n}\n\nexport function isNewerVersion(latest: string, current: string): boolean {\n const [latestMajor, latestMinor, latestPatch] = parseVersion(latest);\n const [currentMajor, currentMinor, currentPatch] = parseVersion(current);\n\n if (latestMajor !== currentMajor) {\n return latestMajor > currentMajor;\n }\n\n if (latestMinor !== currentMinor) {\n return latestMinor > currentMinor;\n }\n\n return latestPatch > currentPatch;\n}\n","import { existsSync, realpathSync } from \"node:fs\";\nimport { spawnSync } from \"node:child_process\";\nimport { dirname, join } from \"node:path\";\n\nimport { detectPackageManager, type PackageManager } from \"../init/package-manager\";\n\nexport type CliInstallKind = \"global\" | \"local\";\n\nexport type CliInstallInfo = {\n kind: CliInstallKind;\n packageManager: PackageManager;\n packageRoot: string;\n projectRoot?: string;\n};\n\nfunction realpathSafe(path: string): string {\n try {\n return realpathSync(path);\n } catch {\n return path;\n }\n}\n\nfunction detectManagerFromLockfile(dir: string): PackageManager | undefined {\n if (existsSync(join(dir, \"pnpm-lock.yaml\"))) {\n return \"pnpm\";\n }\n\n if (existsSync(join(dir, \"bun.lockb\")) || existsSync(join(dir, \"bun.lock\"))) {\n return \"bun\";\n }\n\n if (existsSync(join(dir, \"yarn.lock\"))) {\n return \"yarn\";\n }\n\n if (existsSync(join(dir, \"package-lock.json\"))) {\n return \"npm\";\n }\n\n return undefined;\n}\n\nfunction findLocalProjectRoot(packageRoot: string): string | undefined {\n const normalizedRoot = realpathSafe(packageRoot);\n let dir = dirname(packageRoot);\n\n while (dir !== dirname(dir)) {\n const installedCliPath = join(dir, \"node_modules\", \"@keystrokehq\", \"cli\");\n if (\n existsSync(join(dir, \"package.json\")) &&\n realpathSafe(installedCliPath) === normalizedRoot\n ) {\n return dir;\n }\n\n dir = dirname(dir);\n }\n\n return undefined;\n}\n\nfunction globalRootForManager(manager: PackageManager): string | undefined {\n const commands: Record<PackageManager, { command: string; args: string[] }> = {\n pnpm: { command: \"pnpm\", args: [\"root\", \"-g\"] },\n npm: { command: \"npm\", args: [\"root\", \"-g\"] },\n yarn: { command: \"yarn\", args: [\"global\", \"dir\"] },\n bun: { command: \"bun\", args: [\"pm\", \"bin\"] },\n };\n\n const { command, args } = commands[manager];\n const result = spawnSync(command, args, { encoding: \"utf8\" });\n\n if (result.status !== 0) {\n return undefined;\n }\n\n const root = result.stdout.trim();\n return root ? realpathSafe(root) : undefined;\n}\n\nfunction detectGlobalManager(packageRoot: string): PackageManager {\n const normalizedRoot = realpathSafe(packageRoot);\n\n if (normalizedRoot.includes(`${join(\"\", \".pnpm\")}`)) {\n return \"pnpm\";\n }\n\n for (const manager of [\"pnpm\", \"npm\", \"yarn\", \"bun\"] as const) {\n const globalRoot = globalRootForManager(manager);\n if (globalRoot && normalizedRoot.startsWith(globalRoot)) {\n return manager;\n }\n }\n\n if (process.env.PNPM_HOME) {\n return \"pnpm\";\n }\n\n return detectPackageManager();\n}\n\nexport function detectCliInstall(packageRoot: string): CliInstallInfo | undefined {\n const normalizedRoot = realpathSafe(packageRoot);\n const projectRoot = findLocalProjectRoot(normalizedRoot);\n\n if (projectRoot) {\n const packageManager = detectManagerFromLockfile(projectRoot) ?? detectPackageManager();\n\n return {\n kind: \"local\",\n packageManager,\n packageRoot: normalizedRoot,\n projectRoot,\n };\n }\n\n return {\n kind: \"global\",\n packageManager: detectGlobalManager(normalizedRoot),\n packageRoot: normalizedRoot,\n };\n}\n","const RELEASE_AGE_PATTERNS = [\n /minimumReleaseAge/i,\n /minimum-release-age/i,\n /ERR_PNPM_NO_MATURE_MATCHING_VERSION/,\n /ERR_PNPM_MINIMUM_RELEASE_AGE/,\n /does not meet the minimumReleaseAge constraint/,\n];\n\nexport function isReleaseAgeBlock(output: string): boolean {\n return RELEASE_AGE_PATTERNS.some((pattern) => pattern.test(output));\n}\n\nexport function formatReleaseAgeBlockMessage(options: {\n currentVersion: string;\n availableVersion: string;\n retryAfter?: Date;\n}): string {\n const retry =\n options.retryAfter !== undefined ? ` Retry after ${options.retryAfter.toLocaleString()}.` : \"\";\n\n return (\n `@keystrokehq/cli ${options.availableVersion} is available but blocked by your ` +\n `minimum-release-age setting. You're on ${options.currentVersion}.${retry} ` +\n `Add @keystrokehq/cli to minimumReleaseAgeExclude to install immediately.`\n );\n}\n","const REGISTRY_URL = \"https://registry.npmjs.org/@keystrokehq%2Fcli\";\nconst REQUEST_TIMEOUT_MS = 3_000;\n\ntype RegistryPackage = {\n \"dist-tags\"?: {\n latest?: string;\n };\n time?: Record<string, string>;\n};\n\nexport type CliRegistryRelease = {\n version: string;\n publishedAt?: string;\n};\n\nexport async function fetchLatestCliRelease(): Promise<CliRegistryRelease | undefined> {\n const controller = new AbortController();\n const timeout = setTimeout(() => controller.abort(), REQUEST_TIMEOUT_MS);\n\n try {\n const response = await fetch(REGISTRY_URL, {\n signal: controller.signal,\n headers: {\n Accept: \"application/json\",\n },\n });\n\n if (!response.ok) {\n return undefined;\n }\n\n const payload = (await response.json()) as RegistryPackage;\n const version = payload[\"dist-tags\"]?.latest?.trim();\n if (!version) {\n return undefined;\n }\n\n return {\n version,\n publishedAt: payload.time?.[version],\n };\n } catch {\n return undefined;\n } finally {\n clearTimeout(timeout);\n }\n}\n\nexport async function fetchLatestCliVersion(): Promise<string | undefined> {\n const release = await fetchLatestCliRelease();\n return release?.version;\n}\n","import { spawnSync } from \"node:child_process\";\n\nexport function readPnpmMinimumReleaseAgeMinutes(): number | undefined {\n const result = spawnSync(\"pnpm\", [\"config\", \"get\", \"minimum-release-age\"], {\n encoding: \"utf8\",\n });\n\n if (result.status !== 0) {\n return undefined;\n }\n\n const value = result.stdout.trim();\n if (!value || value === \"undefined\" || value === \"0\") {\n return undefined;\n }\n\n const minutes = Number.parseInt(value, 10);\n return Number.isFinite(minutes) && minutes > 0 ? minutes : undefined;\n}\n\nexport function computeReleaseAgeRetryAfter(\n publishedAt: string | undefined,\n minimumReleaseAgeMinutes: number | undefined,\n): Date | undefined {\n if (!publishedAt || !minimumReleaseAgeMinutes) {\n return undefined;\n }\n\n const publishedMs = Date.parse(publishedAt);\n if (!Number.isFinite(publishedMs)) {\n return undefined;\n }\n\n return new Date(publishedMs + minimumReleaseAgeMinutes * 60_000);\n}\n","/** pnpm global installs live in `<pnpm-home>/global/<major>/`. */\nexport function resolveGlobalPnpmRoot(packageRoot: string): string | undefined {\n const normalized = packageRoot.replace(/\\\\/g, \"/\");\n const match = normalized.match(/^(.*\\/global\\/\\d+)\\//);\n return match?.[1];\n}\n","import type { CliInstallInfo } from \"./detect-cli-install\";\nimport { resolveGlobalPnpmRoot } from \"./resolve-global-pnpm-root\";\n\nconst PACKAGE_NAME = \"@keystrokehq/cli@latest\";\n\nexport function buildUpdateCommand(install: CliInstallInfo): {\n command: string;\n args: string[];\n cwd?: string;\n} {\n const { kind, packageManager } = install;\n\n if (kind === \"global\") {\n switch (packageManager) {\n case \"pnpm\":\n return {\n command: \"pnpm\",\n args: [\"add\", \"-g\", PACKAGE_NAME],\n cwd: resolveGlobalPnpmRoot(install.packageRoot),\n };\n case \"yarn\":\n return { command: \"yarn\", args: [\"global\", \"add\", PACKAGE_NAME] };\n case \"bun\":\n return { command: \"bun\", args: [\"add\", \"-g\", PACKAGE_NAME] };\n case \"npm\":\n default:\n return { command: \"npm\", args: [\"install\", \"-g\", PACKAGE_NAME] };\n }\n }\n\n const cwd = install.projectRoot;\n switch (packageManager) {\n case \"pnpm\":\n return { command: \"pnpm\", args: [\"add\", \"-D\", PACKAGE_NAME], cwd };\n case \"yarn\":\n return { command: \"yarn\", args: [\"add\", \"-D\", PACKAGE_NAME], cwd };\n case \"bun\":\n return { command: \"bun\", args: [\"add\", \"-D\", PACKAGE_NAME], cwd };\n case \"npm\":\n default:\n return { command: \"npm\", args: [\"install\", \"-D\", PACKAGE_NAME], cwd };\n }\n}\n","import { spawnSync } from \"node:child_process\";\n\nimport { buildUpdateCommand } from \"./build-update-command\";\nimport type { CliInstallInfo } from \"./detect-cli-install\";\n\nexport function updateSpawnEnv(): NodeJS.ProcessEnv {\n const env = { ...process.env };\n const pnpmHome = env.PNPM_HOME;\n\n if (!pnpmHome) {\n return env;\n }\n\n const pathKey = process.platform === \"win32\" ? \"Path\" : \"PATH\";\n const path = env[pathKey] ?? \"\";\n const segments = path.split(process.platform === \"win32\" ? \";\" : \":\");\n const binDir = `${pnpmHome}/bin`;\n const prefix = [binDir, pnpmHome].filter((dir) => !segments.includes(dir));\n\n if (prefix.length > 0) {\n env[pathKey] = [...prefix, path].filter(Boolean).join(process.platform === \"win32\" ? \";\" : \":\");\n }\n\n return env;\n}\n\nexport type PackageManagerRunResult = {\n ok: boolean;\n output: string;\n};\n\nfunction runPackageManager(command: string, args: string[], cwd?: string): PackageManagerRunResult {\n const result = spawnSync(command, args, {\n cwd,\n encoding: \"utf8\",\n env: updateSpawnEnv(),\n });\n\n const output = `${result.stdout ?? \"\"}${result.stderr ?? \"\"}`;\n\n return {\n ok: result.status === 0,\n output,\n };\n}\n\nfunction migratePnpmGlobal(cwd: string): boolean {\n const result = spawnSync(\"pnpm\", [\"install\"], {\n cwd,\n encoding: \"utf8\",\n env: {\n ...updateSpawnEnv(),\n CI: \"true\",\n },\n });\n\n return result.status === 0;\n}\n\nexport function runPackageManagerUpdate(install: CliInstallInfo): PackageManagerRunResult {\n const { command, args, cwd } = buildUpdateCommand(install);\n const firstAttempt = runPackageManager(command, args, cwd);\n\n if (firstAttempt.ok) {\n return firstAttempt;\n }\n\n if (install.kind === \"global\" && install.packageManager === \"pnpm\" && cwd) {\n if (migratePnpmGlobal(cwd)) {\n return runPackageManager(command, args, cwd);\n }\n }\n\n return firstAttempt;\n}\n","import { existsSync, mkdirSync, readFileSync, writeFileSync } from \"node:fs\";\nimport { join } from \"node:path\";\n\nimport { getCliConfigDir } from \"../config\";\n\nexport type UpdateBlockCache = {\n registryLatest?: string;\n blockedUntil?: string;\n lastFailedAt?: string;\n};\n\nconst CACHE_FILE = \"update-check.json\";\nconst GENERIC_RETRY_MS = 24 * 60 * 60 * 1000;\n\nfunction cachePath(configDir = getCliConfigDir()): string {\n return join(configDir, CACHE_FILE);\n}\n\nexport function readUpdateBlockCache(configDir?: string): UpdateBlockCache {\n const path = cachePath(configDir);\n if (!existsSync(path)) {\n return {};\n }\n\n try {\n return JSON.parse(readFileSync(path, \"utf8\")) as UpdateBlockCache;\n } catch {\n return {};\n }\n}\n\nexport function writeUpdateBlockCache(cache: UpdateBlockCache, configDir?: string): void {\n const dir = configDir ?? getCliConfigDir();\n mkdirSync(dir, { recursive: true });\n writeFileSync(cachePath(dir), `${JSON.stringify(cache, null, 2)}\\n`, \"utf8\");\n}\n\nexport function shouldSkipCachedUpdate(\n cache: UpdateBlockCache,\n registryLatest: string,\n now = Date.now(),\n): boolean {\n if (cache.registryLatest !== registryLatest) {\n return false;\n }\n\n if (cache.blockedUntil) {\n const blockedUntilMs = Date.parse(cache.blockedUntil);\n if (Number.isFinite(blockedUntilMs) && blockedUntilMs > now) {\n return true;\n }\n }\n\n if (cache.lastFailedAt) {\n const lastFailedMs = Date.parse(cache.lastFailedAt);\n if (Number.isFinite(lastFailedMs) && now - lastFailedMs < GENERIC_RETRY_MS) {\n return true;\n }\n }\n\n return false;\n}\n\nexport function clearUpdateBlockCache(configDir?: string): void {\n writeUpdateBlockCache({}, configDir);\n}\n\nexport function recordReleaseAgeBlock(options: {\n registryLatest: string;\n retryAfter?: Date;\n configDir?: string;\n}): void {\n writeUpdateBlockCache(\n {\n registryLatest: options.registryLatest,\n blockedUntil: options.retryAfter?.toISOString(),\n },\n options.configDir,\n );\n}\n\nexport function recordGenericUpdateFailure(registryLatest: string, configDir?: string): void {\n writeUpdateBlockCache(\n {\n registryLatest,\n lastFailedAt: new Date().toISOString(),\n },\n configDir,\n );\n}\n","import { spawnSync } from \"node:child_process\";\n\nimport { resolveCliRoot } from \"../project/resolve-cli-root\";\nimport { readCliVersion } from \"../version\";\nimport { isNewerVersion } from \"./compare-version\";\nimport { detectCliInstall } from \"./detect-cli-install\";\nimport { formatReleaseAgeBlockMessage, isReleaseAgeBlock } from \"./detect-release-age-block\";\nimport { fetchLatestCliRelease } from \"./fetch-latest-version\";\nimport {\n computeReleaseAgeRetryAfter,\n readPnpmMinimumReleaseAgeMinutes,\n} from \"./read-pnpm-release-age-minutes\";\nimport { runPackageManagerUpdate } from \"./run-package-manager-update\";\nimport {\n clearUpdateBlockCache,\n readUpdateBlockCache,\n recordGenericUpdateFailure,\n recordReleaseAgeBlock,\n shouldSkipCachedUpdate,\n} from \"./update-block-cache\";\n\nfunction shouldSkipAutoUpdate(argv: string[]): boolean {\n if (\n process.env.KEYSTROKE_DEV ||\n process.env.KEYSTROKE_SKIP_UPDATE ||\n process.env.KEYSTROKE_UPDATING\n ) {\n return true;\n }\n\n if (process.env.CI === \"true\" || process.env.CI === \"1\") {\n return true;\n }\n\n const args = argv.slice(2);\n if (args.length === 0) {\n return false;\n }\n\n return args.every(\n (arg) =>\n arg === \"-V\" ||\n arg === \"--version\" ||\n arg === \"-h\" ||\n arg === \"--help\" ||\n arg.startsWith(\"-V\"),\n );\n}\n\nfunction reexecCli(argv: string[]): never {\n const result = spawnSync(process.execPath, argv.slice(1), {\n stdio: \"inherit\",\n env: {\n ...process.env,\n KEYSTROKE_UPDATING: \"1\",\n },\n });\n\n process.exit(result.status ?? 1);\n}\n\nfunction releaseAgeRetryAfter(\n install: NonNullable<ReturnType<typeof detectCliInstall>>,\n publishedAt: string | undefined,\n): Date | undefined {\n if (install.packageManager !== \"pnpm\") {\n return undefined;\n }\n\n return computeReleaseAgeRetryAfter(publishedAt, readPnpmMinimumReleaseAgeMinutes());\n}\n\nexport async function maybeAutoUpdate(argv: string[]): Promise<void> {\n if (shouldSkipAutoUpdate(argv)) {\n return;\n }\n\n const install = detectCliInstall(resolveCliRoot(import.meta.url));\n if (!install || (install.kind === \"local\" && !install.projectRoot)) {\n return;\n }\n\n const currentVersion = readCliVersion();\n const release = await fetchLatestCliRelease();\n\n if (!release || !isNewerVersion(release.version, currentVersion)) {\n clearUpdateBlockCache();\n return;\n }\n\n const cache = readUpdateBlockCache();\n if (shouldSkipCachedUpdate(cache, release.version)) {\n return;\n }\n\n process.stderr.write(\n `Updating @keystrokehq/cli ${currentVersion} -> ${release.version} via ${install.packageManager}...\\n`,\n );\n\n const result = runPackageManagerUpdate(install);\n const installedVersion = readCliVersion();\n\n if (isNewerVersion(installedVersion, currentVersion)) {\n clearUpdateBlockCache();\n process.stderr.write(`Updated @keystrokehq/cli ${currentVersion} -> ${installedVersion}.\\n`);\n reexecCli(argv);\n }\n\n if (result.ok) {\n clearUpdateBlockCache();\n return;\n }\n\n if (isReleaseAgeBlock(result.output)) {\n const retryAfter = releaseAgeRetryAfter(install, release.publishedAt);\n recordReleaseAgeBlock({\n registryLatest: release.version,\n retryAfter,\n });\n process.stderr.write(\n `${formatReleaseAgeBlockMessage({\n currentVersion,\n availableVersion: release.version,\n retryAfter,\n })}\\n`,\n );\n return;\n }\n\n recordGenericUpdateFailure(release.version);\n process.stderr.write(\"Auto-update failed; continuing with the current version.\\n\");\n}\n"],"mappings":";;;;;;AAAA,SAAS,aAAa,SAA2C;CAE/D,MAAM,CAAC,QAAQ,GAAG,QAAQ,GAAG,QAAQ,MADlB,QAAQ,KAAK,EAAE,QAAQ,MAAM,EAAE,EAAE,MAAM,GAAG,EAAE,MAAM,IAChB,MAAM,GAAG,EAAE,KAAK,SAAS;EAC5E,MAAM,QAAQ,OAAO,SAAS,MAAM,EAAE;EACtC,OAAO,OAAO,SAAS,KAAK,IAAI,QAAQ;CAC1C,CAAC;CAED,OAAO;EAAC;EAAO;EAAO;CAAK;AAC7B;AAEA,SAAgB,eAAe,QAAgB,SAA0B;CACvE,MAAM,CAAC,aAAa,aAAa,eAAe,aAAa,MAAM;CACnE,MAAM,CAAC,cAAc,cAAc,gBAAgB,aAAa,OAAO;CAEvE,IAAI,gBAAgB,cAClB,OAAO,cAAc;CAGvB,IAAI,gBAAgB,cAClB,OAAO,cAAc;CAGvB,OAAO,cAAc;AACvB;;;ACRA,SAAS,aAAa,MAAsB;CAC1C,IAAI;EACF,OAAO,aAAa,IAAI;CAC1B,QAAQ;EACN,OAAO;CACT;AACF;AAEA,SAAS,0BAA0B,KAAyC;CAC1E,IAAI,WAAW,KAAK,KAAK,gBAAgB,CAAC,GACxC,OAAO;CAGT,IAAI,WAAW,KAAK,KAAK,WAAW,CAAC,KAAK,WAAW,KAAK,KAAK,UAAU,CAAC,GACxE,O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SAAS,wBAAwB,OAAO;CAC9C,MAAM,mBAAmB,eAAe;CAExC,IAAI,eAAe,kBAAkB,cAAc,GAAG;EACpD,sBAAsB;EACtB,QAAQ,OAAO,MAAM,4BAA4B,eAAe,MAAM,iBAAiB,IAAI;EAC3F,UAAU,IAAI;CAChB;CAEA,IAAI,OAAO,IAAI;EACb,sBAAsB;EACtB;CACF;CAEA,IAAI,kBAAkB,OAAO,MAAM,GAAG;EACpC,MAAM,aAAa,qBAAqB,SAAS,QAAQ,WAAW;EACpE,sBAAsB;GACpB,gBAAgB,QAAQ;GACxB;EACF,CAAC;EACD,QAAQ,OAAO,MACb,GAAG,6BAA6B;GAC9B;GACA,kBAAkB,QAAQ;GAC1B;EACF,CAAC,EAAE,GACL;EACA;CACF;CAEA,2BAA2B,QAAQ,OAAO;CAC1C,QAAQ,OAAO,MAAM,4DAA4D;AACnF"}
@@ -6,7 +6,7 @@ You are editing a **keystroke project** in a remote workspace via MCP. Author un
6
6
 
7
7
  Use MCP tools to work on the project: `read_file`, `write_file`, `edit_file`, `list_files`, `delete_file`, `exec_command`, and `deploy_project`. Look up authoring guidance, APIs, and examples with `search_docs` and `query_docs` (see docs below) before editing files.
8
8
 
9
- The **keystroke platform** is the hosted control plane. After you change code, run `deploy_project` to build and upload; that activates the cloud runtime. A project is a single live runtime — a deploy replaces what's running on that project (there's no separate dev and prod within one project), so use filtered deploys and `@keystroke ignore` to iterate quickly.
9
+ The **keystroke platform** is the hosted control plane and the shared web workspace where your user works — viewing workflows on a canvas, chatting with agents, inspecting runs, and managing credentials. After you change code, run `deploy_project` to build and upload; that activates the cloud runtime. A project is a single live runtime — a deploy replaces what's running on that project (there's no separate dev and prod within one project), so use filtered deploys and `@keystroke ignore` to iterate quickly.
10
10
 
11
11
  ## What you build
12
12
 
@@ -1,148 +1,267 @@
1
1
  # keystroke
2
2
 
3
- This codebase is a Keystroke project.
3
+ This codebase is a Keystroke project. Keystroke is a code-first AI automation platform. You build AI agents, workflows, triggers, and actions in TypeScript under `src/`, deploy them to a managed cloud runtime, then run and inspect what's deployed.
4
4
 
5
- > Keystroke is a code-first AI automation platform. With it, anyone can build specialized AI agents and workflow automations in TypeScript, then deploy them to a managed cloud platform where they run.
5
+ You are the user's AI automation engineer, the coding agent that builds and maintains this project. Read `src/` first (existing agents, workflows, actions, and triggers). Read the docs before making decisions (see [Documentation](#documentation)).
6
6
 
7
- - **Build agents and workflows:** Build agents and workflows with an open TypeScript framework. Run tests, connect integrations, and maintain what you build over time.
8
- - **Connect to thousands of integrations:** Keystroke has over 1,000 built-in integrations (Slack, Google, Linear, and hundreds more). It is also extremely easy to quickly build a connection for any HTTP API (including private internal APIs) or MCP server.
9
- - **Deploy what you build:** The Keystroke platform gives teams a managed workspace to run what they build. Deploy agents and workflows from your project. Then, view workflows on an interactive canvas, chat with agents in a chat interface, inspect runs, manage credentials, and collaborate from a shared web platform.
7
+ ## Match the user's level
10
8
 
11
- ## Keystroke projects
9
+ Your user may or may not be technical. Keystroke users range from staff engineers to Zapier-caliber automation builders. You are the medium through which they build.
12
10
 
13
- In Keystroke, everything you build belongs to a project. A project is a shared space for building and running your agents, workflows, triggers, and actions. Think of a project as the unit you build, deploy, give credentials to, invite teammates to, and inspect run history for.
11
+ - **Mirror their voice.** Only get as technical as the user does. Match their vocabulary.
12
+ - **Narrate in outcomes, not plumbing.** Default to "I'll set this to run every morning and message you a summary", not "deploying the cron trigger to the runtime." Don't surface internal concepts (build artifacts, event logs, correlation IDs, filtered deploys) unless the user has to make a decision about one.
13
+ - **Don't hand them the work.** They build *through* you — don't tell them to run commands, edit files, or paste code unless they've shown they want to. Do it yourself, do it quickly, and report the result.
14
+ - **Simplify the talk, never the work.** Speaking plainly doesn't lower the bar — follow every invariant in this guide regardless of how the user communicates.
15
+ - **If the end-state isn't clear, just ask.** It's okay to clarify how the thing you're building should be built, which integrations to use, etc.
14
16
 
15
- Keystroke projects use two related ideas:
17
+ ## Local codebase vs platform project
16
18
 
17
- - **Local codebase**: a local directory (this codebase) with `keystroke.config.ts` and `src/` (`keystroke init` scaffolds this). Run it locally with `keystroke start` / `keystroke dev`; no platform project required.
18
- - **Platform project**: an org-owned cloud record: a deploy target plus a hosted runtime (its own keystroke server, URL, managed credentials). Projects are inactive until their first deploy.
19
+ Keystroke separates *where you write code* from *where it runs*:
19
20
 
20
- `keystroke deploy --project <id>` links your local codebase to your platform project: it uploads the built local codebase and activates that platform project's server. After the first deploy the project is saved as your active target (in `~/.keystroke`), so later commands — including subsequent deploys — can drop `--project`. Deployed agents and workflows instantly run there with no additional configuration; the web workspace is where organization members can manage their projects, deployments, logs, credentials, etc.
21
+ | | What it is | Lives |
22
+ | --- | --- | --- |
23
+ | **Local codebase** | This directory — `keystroke.config.ts` + `src/`. Source of truth. | Your machine / Git |
24
+ | **Platform project** | Org-owned cloud runtime (its own server, URL, credentials, run history). Inactive until first deploy. | Keystroke cloud |
21
25
 
22
- ## How this codebase fits in
26
+ `keystroke deploy` builds `src/`, uploads it, and promotes it as the project's single live runtime. A deploy replaces what's running — there is no separate dev and prod within one project.
23
27
 
24
- This is the local codebase that defines your agents, workflows, triggers, actions, skills, context files, etc.
28
+ ### The web platform
25
29
 
26
- Projects are scaffolded with an opinionated folder structure (like Next.js for building AI systems):
30
+ Once deployed, your user works in the **web platform** — a shared workspace where they view workflows on an interactive canvas, use agents in a chat interface, inspect runs and traces, manage credentials, and collaborate with teammates. Most users spend far more time here than in code, so frame what you build around what they'll see and do there, not the CLI plumbing.
31
+
32
+ ### Project layout
33
+
34
+ Keystroke discovers everything under `src/` by convention.
27
35
 
28
36
  ```
29
37
  my-app/
30
- keystroke.config.ts # project configuration
38
+ keystroke.config.ts # project configuration
31
39
  src/
32
- agents/ # LLM agents
33
- actions/ # reusable units of work
34
- workflows/ # multi-step automations
35
- triggers/ # schedules, webhooks, app events
36
- skills/ # project skills for agents
37
- files/ # context for attaching to agents
38
- AGENTS.md # this guide
40
+ agents/ # LLM agents
41
+ actions/ # reusable leaf units of work
42
+ workflows/ # multi-step automations
43
+ triggers/ # schedules, webhooks, app events
44
+ skills/ # runtime playbooks for agents
45
+ files/ # context files attached to agents
46
+ AGENTS.md # this guide
39
47
  ```
40
48
 
41
- Keystroke discovers everything under `src/` by convention. Add a file that exports an agent, workflow, trigger, etc, and it becomes part of the project. Because the project is code, agents (Cursor, Claude Code, Codex, etc) can read it, change it, run tests, and maintain it over time.
42
-
43
- Each primitive imports from `@keystrokehq/keystroke/<piece>` (`/action`, `/agent`, `/workflow`, `/trigger`, `/app`); integrations are their own `@keystrokehq/<slug>` packages. The example files in `src/` show the exact imports.
49
+ Each primitive imports from `@keystrokehq/keystroke/<piece>` (`/agent`, `/action`, `/workflow`, `/trigger`, `/sandbox`). Integrations are `@keystrokehq/<slug>` packages.
44
50
 
45
- ## How you work
51
+ ## The deploy-first loop
46
52
 
47
- ### Build, deploy, test
53
+ Keystroke is deploy-first: build, ship, then run and inspect what's live. Deploy often.
48
54
 
49
- You build in `src/`, deploy to your project on the platform, then run and inspect what's deployed with the CLI. The loop is: edit → `keystroke deploy` run/inspect/test repeat. You should deploy often.
55
+ 1. **Auth once** `keystroke auth login` (token is stored and reused).
56
+ 2. **Edit** primitives under `src/`.
57
+ 3. **Deploy** — `keystroke deploy` (full) or `keystroke deploy --filter agents/support` (one module).
58
+ 4. **Run** — `keystroke workflow run <slug> --input '{...}'` / `keystroke agent prompt <slug> --message "..."`.
59
+ 5. **Inspect** — read the real run/trace before claiming done (see [Audit & debug](#audit--debug)).
60
+ 6. Repeat.
50
61
 
51
62
  ```bash
52
- keystroke auth status # show the current user and active organization
53
- keystroke auth login # once; token is automatically stored and reused
54
- keystroke project list # your projects on the platform
55
- keystroke deploy --project <id> # build + ship src/ to the platform
56
- keystroke workflow run greeting --input '{"name":"Ada"}' # test and run a workflow
57
- keystroke agent prompt hello --message "Hi" # test and chat with an agent
63
+ keystroke auth status # current user + org
64
+ keystroke project list # your platform projects
65
+ keystroke deploy # build + ship src/ (first deploy must be full)
66
+ keystroke workflow run greeting --input '{"name":"Ada"}' # run a workflow
67
+ keystroke agent prompt hello --message "Hi" # prompt an agent
68
+ ```
69
+
70
+ New project: `keystroke init my-app --yes`, then deploy. Join an existing cloud project: `keystroke pull --project <slug>`.
71
+
72
+ ## Choosing a primitive
73
+
74
+ | Build a… | When |
75
+ | --- | --- |
76
+ | **Agent** | The path isn't fixed — needs judgment, tool use, language, or multi-turn context. Or when a user is explicitly asking you to build an agent (e.g. AI data analyst for use in Slack, support agent, etc) |
77
+ | **Workflow** | You know the order of steps and want durability and predictability. |
78
+ | **Action** | A single reusable capability (an API call, a computation) used by workflows or agents. |
79
+ | **Trigger** | Something should start a workflow/agent automatically — schedule, webhook, or poll. |
80
+
81
+ Generally, prefer a workflow (or a plain action / LLM step) unless the path genuinely varies at runtime. Reach for an agent only when the user is clearly asking you to build one or when the work needs judgment, tool selection, or multi-turn context — not just because it's easier to wire up. Primitives compose: workflows orchestrate actions and prompt agents; agents call actions, subagents, and workflows as tools.
82
+
83
+ ## Building blocks
84
+
85
+ ### Agent — `defineAgent`
86
+
87
+ Required: `slug`, `systemPrompt`, `model`. Everything else is optional.
88
+
89
+ ```ts
90
+ import { defineAgent } from "@keystrokehq/keystroke/agent";
91
+
92
+ export default defineAgent({
93
+ slug: "support",
94
+ systemPrompt: "You are a helpful support assistant. Answer concisely.",
95
+ model: "anthropic/claude-sonnet-4.6",
96
+ });
97
+ ```
98
+
99
+ - **Model** — exact catalog id in `vendor/model-id` format from https://keystroke.ai/models.md. Do **not** kebab-case the version (`anthropic/claude-sonnet-4.6` is valid; `...-4-6` fails at deploy).
100
+ - **Tools** — attach actions, subagents, workflows, and MCP tools directly in `tools: [...]`. Do **not** hand-roll a `defineTool` + `executeWorkflow()` wrapper. A subagent's tool name is its `slug` and takes a `message`.
101
+ - **Built in**: isolated `/workspace` with file + `bash` tools, session + persistent memory (`memory: false` to disable), `web_search`/`web_fetch` when configured, self-scheduling tools.
102
+ - **Credentials** are declared on actions, not agents — the agent gets them by calling those actions as tools.
103
+ - **Sandbox** — default in-process bash covers most needs. For real CLIs/isolation: `sandbox: defineSandbox({ mode: "vm" })` (`mode` lives on `defineSandbox`, not as a top-level agent field).
104
+
105
+ ### Workflow — `defineWorkflow`
106
+
107
+ Global `slug`, typed Zod `input`/`output`, a normal `async` `run`.
108
+
109
+ ```ts
110
+ import { defineWorkflow } from "@keystrokehq/keystroke/workflow";
111
+ import { z } from "zod";
112
+
113
+ export default defineWorkflow({
114
+ slug: "signup-pipeline",
115
+ input: z.object({ name: z.string(), email: z.string().email() }),
116
+ output: z.object({ brief: z.string() }),
117
+ async run(input) {
118
+ const { brief } = await researchSignup.run(input);
119
+ await postBrief.run({ text: brief });
120
+ return { brief };
121
+ },
122
+ });
123
+ ```
124
+
125
+ | Step | Syntax |
126
+ | --- | --- |
127
+ | Action | `await action.run(input)` |
128
+ | Agent | `await agent.prompt({ message })` |
129
+ | One-shot LLM | `await promptLlm(prompt, { model, outputSchema? })` |
130
+ | Sub-workflow | `await otherWorkflow.run(input)` — never pass `ctx` |
131
+ | Durable sleep | `await ctx.sleep("1h")` |
132
+ | Durable wait | `await ctx.hook<T>()` |
133
+
134
+ `ctx` is the second `run` argument (`async run(input, ctx)`) — add it only when a step needs `ctx.sleep`/`ctx.hook`.
135
+
136
+ Use `promptLlm(...)` (import from `@keystrokehq/keystroke/workflow`) for one-shot generation/classification. Use `agent.prompt(...)` when the step needs tools, memory, or multi-turn reasoning.
137
+
138
+ **Durability** — completed steps replay on retry: keep side effects inside steps; make steps idempotent; keep control flow deterministic (no `Date.now()` / randomness); pin `.stepId()` when the step set can change. `ctx.sleep`/`ctx.hook` work from triggers/CLI/HTTP but not when a workflow is inline as an agent tool.
139
+
140
+ ### Action — `defineAction`
141
+
142
+ Leaf unit — **never calls another action** (yours or an integration's). Enforced at runtime and by lint.
143
+
144
+ ```ts
145
+ import { defineAction } from "@keystrokehq/keystroke/action";
146
+ import { z } from "zod";
147
+
148
+ export const triage = defineAction({
149
+ slug: "triage",
150
+ input: z.object({ message: z.string() }),
151
+ output: z.object({ priority: z.enum(["low", "normal", "high", "urgent"]) }),
152
+ run: async (input) => ({ priority: /urgent/i.test(input.message) ? "urgent" : "normal" }),
153
+ });
58
154
  ```
59
155
 
60
- After a deploy, runtime commands (`workflow`, `agent`, `trigger`, `app`, `connect`) operate on that project automatically no target to manage.
156
+ Compose in workflows. Attach integration actions directly as workflow steps or agent tools never wrap in a custom action. An action *may* call an agent (`await agent.prompt(...)`).
157
+
158
+ ### Trigger — source + `.attach()`
61
159
 
62
- A project is a single live runtime. A deploy replaces what's running on that project — there's no separate dev and prod within one project. You can use `--filter` deploys and `@keystroke ignore` to iterate quickly.
160
+ Exactly three sources: `defineCronSource`, `defineWebhookSource`, `definePollSource`. Default-export the attached result.
63
161
 
64
- To create a new project: `keystroke init my-app --yes`, then deploy.
162
+ ```ts
163
+ import { defineWebhookSource } from "@keystrokehq/keystroke/trigger";
164
+ import { z } from "zod";
165
+ import workflow from "../workflows/signup-pipeline";
65
166
 
66
- Look things up cheapest-first: `keystroke <command> --help` for the authoritative flags and usage of any command (local, always current); `keystroke docs search`/`query` for documentation and examples; and `keystroke docs query "cat /cli.mdx"` for the full CLI reference.
167
+ export default defineWebhookSource({
168
+ slug: "signup",
169
+ endpoint: "signup",
170
+ request: z.object({ name: z.string(), email: z.string().email() }),
171
+ }).attach({ workflow });
172
+ ```
67
173
 
68
- ### Building agents
174
+ | Source | Use when |
175
+ | --- | --- |
176
+ | **Schedule** (`defineCronSource`) | Time alone starts the run (cron is UTC in prod). Passes `{}` — workflow `input` must accept an empty object. |
177
+ | **Webhook** (`defineWebhookSource`) | Another system pushes events. Best option when available. |
178
+ | **Poll** (`definePollSource`) | Keystroke must pull/check an external system on a schedule. |
69
179
 
70
- Agents are useful when a task needs judgment, language understanding, tool use, or multi-turn context.
180
+ Filters live on the source; `transform` lives on the workflow attachment. Agents use `.attach({ agent, prompt })` (not `transform`). Attachment id: `{sourceSlug}:{targetSlug}`.
71
181
 
72
- | Capability | How it works |
73
- | -------------------- | --------------------------------------------------- |
74
- | **Instructions** | `systemPrompt` tells the model how to behave |
75
- | **Models** | `model` uses `vendor/model-id`, with optional `thinkingLevel` |
76
- | **File system** | Each session gets a `/workspace` with a built-in file system and bash (code execution) tools |
77
- | **Web search** | Built-in `web_search` and `web_fetch` tools when a web provider is configured |
78
- | **Tools** | Attach custom tools, MCP tools, subagents, and workflows as tools |
79
- | **Skills and files** | Attach skills from `src/skills/` and context files from `src/files/` |
80
- | **Memory** | Sessions and persistent memory are enabled by default unless disabled |
81
- | **Sandbox** | A built-in sandbox environment for using CLIs and more advanced code execution |
82
- | **Self-scheduling** | Built-in tools let an agent schedule its own future or recurring runs (ephemeral triggers) |
182
+ ## Integrations & credentials
83
183
 
84
- **Workflow steps.** Workflows orchestrate actions, agent prompts, LLM calls (`promptLlm`), and other workflows as steps. Reuse a workflow by importing it and calling `await otherWorkflow.run(input)` a first-class durable step (validated IO, checkpointed, runs inline in the same run; never thread `ctx`). Import a workflow into an agent's `tools` / call over HTTP when you want it as its own tracked run.
184
+ Keystroke has 1,000+ built-in integrations, and it's easy to build a custom one for any HTTP API or MCP server (including private/internal).
85
185
 
86
- **Agent tools.** Agents can use actions, subagents, workflows, and MCP tools as tools import them directly into `tools`.
186
+ Discover apps and actions with the CLI the docs integration index is **not** reliable for discovery:
87
187
 
88
- ### Building workflows
188
+ ```bash
189
+ keystroke app list # all registered apps
190
+ keystroke app search <query> # find an app + slug in the full catalog
191
+ keystroke app actions <slug> --search <q> # actions an app exposes
192
+ keystroke app action <action-slug> # input/output schema for one action
193
+ keystroke connect <slug> # connect an app credential (opens web OAuth/api key flow for the user)
194
+ keystroke credentials list # stored credential instances
195
+ keystroke credentials set <key> --set apiKey=@env:MY_KEY # static API key
196
+ ```
89
197
 
90
- Workflows are useful when you know the order of work: call an action, prompt an agent, branch on the result, wait for approval, then continue.
198
+ `keystroke deploy` **never uploads `.env`** connect cloud credentials with `keystroke connect` / `keystroke credentials set`. Missing a built-in? Use `defineCredential` + an action, `defineApp`, or `defineMcp`. See `/learn/credentials/custom-integrations`.
91
199
 
92
- | Capability | How it works |
93
- | -------------------------- | --------------------------------------------------------------------------------------------- |
94
- | **Typed input and output** | Zod schemas validate the payload going in and the result coming out |
95
- | **Action steps** | Call any [action](/learn/actions/overview) with `.run()`, your own or one from an integration |
96
- | **Agent steps** | Prompt an [agent](/learn/agents/overview) with `.prompt()` when a step needs judgment |
97
- | **LLM steps** | Use `promptLlm()` for a one-shot model call without defining a full agent |
98
- | **Durability** | Completed steps are recorded and replayed, so retries resume instead of restarting |
99
- | **Durable waits** | `ctx.sleep()` and `ctx.hook()` suspend a run for a delay or until it is resumed externally |
200
+ ## Skills & files
100
201
 
101
- ### Common failures
202
+ - **Skills** (`src/skills/<name>/SKILL.md`) — runtime playbooks that teach an agent *how* to do a task. Attach with `skills: ["<name>"]`.
203
+ - **Files** (`src/files/<set>/`) — static context an agent can access. Attach with `sandbox: defineSandbox({ files: true })` (set folder matches the agent `slug`).
102
204
 
103
- - **Research real APIs before mirroring them** — building actions for custom integrations is very common; web search and fetch the actual reference & explore relevant docs, don't guess endpoints or payload shapes.
104
- - **Run before you claim you are finished** — deploy what you build, run it in the cloud, and read the real output before activating live triggers or claiming you are finished building something. Chat with agents to ensure they behave correctly. Run workflows to ensure they behave correctly.
105
- - **Cover obvious edge cases** and write simple tests as needed (null field, empty array, a step that throws).
106
- - **Connected apps aren't in `.env`** — `keystroke deploy` never uploads `.env`; connect apps (aka, integrations) for your project with `keystroke connect <slug>`.
107
- - **Filtered deploys** — determine if you should do a full vs filtered deploy, or use WIP ignore directives.
108
- - **Actions are leaf units** - An action never calls another action (including integration actions like `slackSendMessage`). You can compose actions in a workflow, or attach an integration action directly as a workflow step or agent tool. Action can call agents, allowing you to create "subagent tools" or "agent steps".
205
+ Both materialize into the agent's `/workspace/agent/...` environment before each prompt.
109
206
 
110
- ### Audit & debug (CLI)
207
+ ## Deploy targets & scope
111
208
 
112
- Use the CLI to inspect your deployed project.
209
+ - **Target**: after the first deploy, CLI commands target the **cloud** project automatically.
210
+ - **Full vs filtered**: first deploy must be full. Use `keystroke deploy --filter agents/support` to patch one module — filter keys are exact paths (`agents/support`, `workflows/morning-check`), no globs. Changing `keystroke.config.ts` or shared skills/files/integrations needs a full deploy.
211
+ - **WIP**: `// @keystroke ignore` skips a file everywhere; `// @keystroke ignore:deploy` keeps it local but out of deploys. A shipped module cannot import an ignored one.
212
+
213
+ ## Audit & debug
214
+
215
+ Inspect deployed runs with `--include` to see full traces:
113
216
 
114
217
  ```bash
115
- # Workflows
116
- keystroke workflow list # list deployed workflows
117
- keystroke workflow runs list <workflow-slug> # recent runs for a workflow
118
- keystroke workflow runs get <workflow-slug> <run-id> --include steps,trace # one run in full: input, each step, execution trace
119
-
120
- # Agents
121
- keystroke agent list # list deployed agents
122
- keystroke agent sessions list <agent-slug> # recent sessions for an agent
123
- keystroke agent sessions get <agent-slug> <session-id> --include messages,trace # one session in full: messages, execution trace
124
-
125
- # Triggers (attachment id is <trigger-slug>:<workflow-slug>)
126
- keystroke trigger list # list deployed triggers
127
- keystroke trigger url <trigger-slug> # print a trigger's webhook URL
128
- keystroke trigger runs list <trigger-slug>:<workflow-slug> # recent runs for a trigger→workflow attachment
129
- keystroke trigger runs get <trigger-slug>:<workflow-slug> <run-id> --include workflows,trace # one run in full: workflows fired, execution trace
218
+ keystroke workflow runs list <workflow-slug>
219
+ keystroke workflow runs get <workflow-slug> <run-id> --include steps,trace
220
+
221
+ keystroke agent sessions list <agent-slug>
222
+ keystroke agent sessions get <agent-slug> <session-id> --include messages,trace
223
+
224
+ keystroke trigger list
225
+ keystroke trigger url <trigger-slug> # webhook URL (+ ?token= on platform)
226
+ keystroke trigger runs get <trigger-slug>:<workflow-slug> <run-id> --include workflows,trace
227
+ keystroke trigger attachment disable <trigger-slug> <trigger-slug>:<workflow-slug> # pause without redeploy (takes both the trigger slug and the attachment id)
228
+
229
+ keystroke history list --kind workflow --status failed
130
230
  ```
131
231
 
132
- Read `src/` first; existing agents, workflows, actions, and triggers are your best map of how this project works.
232
+ Invoke/inspect commands print JSON to stdout (exit 0 on success, 1 on failure) pipe to `jq`. Lifecycle commands (`init`/`dev`/`deploy`) print human status.
233
+
234
+ ## Before you claim you're done
235
+
236
+ - [ ] Deployed the change and read the real run output/trace — not just "it should work".
237
+ - [ ] Prompted agents / ran workflows with realistic input and verified behavior.
238
+ - [ ] Researched real APIs before mirroring them in custom integration actions — no guessed endpoints or payloads.
239
+ - [ ] Covered obvious edge cases (null field, empty array, a step that throws) with a simple test where warranted.
240
+ - [ ] Connected any new apps with `keystroke connect` (not `.env`).
241
+ - [ ] Tested manually before deploying attached cron/polling triggers, or used `trigger attachment disable` to pause until ready.
242
+
243
+ ## Common gotchas
244
+
245
+ 1. **Action calling an action** — throws at runtime and fails lint. Compose in a workflow, or attach the integration action directly.
246
+ 2. **Bad model id** — must be exact `vendor/model-id` from the catalog; don't kebab the version. Fails at deploy, not typecheck.
247
+ 3. **LLM structured output: use `.nullish()`, not `.optional()`** — models emit `"field": null` for "not applicable" values, and Zod `.optional()` rejects `null` (the step fails). Use `.nullish()` (or `.nullable()`) for any optional field in an `outputSchema`.
248
+ 4. **Silent fallbacks hide real failures** — for live config (Sheets, DBs, credentials), don't `catch` and quietly substitute fallback/empty data in production paths. A run that "completes" with empty inputs looks like success in the trace but is a silent failure. Throw when required config is missing or empty, and validate response shape, not just status.
249
+ 5. **Side effects outside steps** — they re-run on every replay. Keep them inside `.run()` / `.prompt()`.
250
+ 6. **Schedule input** — a cron trigger passes `{}`; give the workflow `input: z.object({})`.
133
251
 
134
252
  ## Documentation
135
253
 
136
- **You should regularly and thoroughly read the documentation** when working with the CLI, building agents/workflows/triggers/actions/etc, and debugging. Bias heavily toward quickly reading documentation before making decisions or changes, and prefer what the docs say over your prior knowledge.
254
+ Read the docs regularly and prefer them over prior knowledge. Bias **heavily** toward searching and reading documentation before making any decisions or changes. The documentation contains much more important context than this `AGENTS.md` guide.
137
255
 
138
- Documentation is directly available via the CLI (no auth required). Use these CLI commands to search, query, and read the Keystroke documentation:
256
+ All documentation is available via the CLI (no auth), cheapest-first:
139
257
 
140
- - **`keystroke docs search "<query>"`**best for broad or conceptual lookups when you don't know the path (e.g. `keystroke docs search "webhook trigger"`). Returns matching pages with titles and paths; read one by passing its path to `query`.
141
- - **`keystroke docs query "<command>"`**exact keyword/regex search, structure exploration, and reading pages by path with a shell-style command (`cat`, `rg`, `ls`, `tree`, `head`). Append `.mdx` to a doc path to read it: `keystroke docs query "cat /quickstart.mdx"`, `keystroke docs query "rg -il trigger /"`, `keystroke docs query "tree / -L 2"`.
258
+ - `keystroke <command> --help` authoritative, always-current flags for any command.
259
+ - `keystroke docs search "<query>"`find pages by topic when you don't know the path.
260
+ - `keystroke docs query "<cmd>"` — read/search pages with `cat`/`rg`/`ls`/`tree`/`head` (e.g. `keystroke docs query "cat /learn/agents/build-agents.mdx"`).
142
261
 
143
- Each `query` is stateless — the working dir resets to `/`, so use absolute paths or chain with `&&` and output is capped (~30KB). Prefer a targeted `rg -C 3 "term" /path.mdx` or `head -n 120 /path.mdx` over `cat` on large pages, and batch several files into one read (`head -n 80 /a.mdx /b.mdx`).
262
+ `query` is stateless (working dir resets to `/`; use absolute paths or chain with `&&`) and output is capped (~30KB) prefer targeted `rg -C 3` / `head` over `cat` on large pages.
144
263
 
145
- Below is a sample of common documentation pages. You can read a page with `keystroke docs query "cat <path>.mdx"`.
264
+ Below is a sample of some of the most common documentation pages.
146
265
 
147
266
  | Doc path | Read when |
148
267
  | -------- | --------- |
@@ -162,7 +281,6 @@ Below is a sample of common documentation pages. You can read a page with `keyst
162
281
  | `/learn/actions/workflow-steps` | Wiring actions into workflows |
163
282
  | `/learn/actions/agent-tools` | Exposing actions as agent tools |
164
283
  | `/learn/triggers/overview` | Choosing a trigger type |
165
- | `/learn/triggers/app-events` | App-event triggers |
166
284
  | `/learn/triggers/webhooks` | Webhook triggers |
167
285
  | `/learn/triggers/schedules` | Cron / scheduled triggers |
168
286
  | `/learn/triggers/polling` | Polling triggers |
@@ -170,24 +288,7 @@ Below is a sample of common documentation pages. You can read a page with `keyst
170
288
  | `/learn/credentials/connect-credentials` | `keystroke connect`, OAuth, project credentials |
171
289
  | `/learn/credentials/use-credentials` | Using connected apps in code |
172
290
  | `/learn/credentials/custom-integrations` | Building a custom HTTP / MCP / GraphQL integration |
173
- | `/learn/skills/overview` | `src/skills/` playbooks for agents (runtime, not this guide) |
291
+ | `/learn/skills/overview` | `src/skills/` skills for agents (runtime, not this guide) |
174
292
  | `/learn/skills/create-skills` | Authoring an agent skill |
175
293
  | `/learn/files/overview` | `src/files/` workspace context |
176
- | `/learn/logs/overview` | Reading run history, debugging deployed runs |
177
-
178
- ## Integrations and secrets
179
-
180
- For searching native integrations use the CLI, not docs. The docs contain an index of integrations, but the documentation integration index is not reliable. To discover apps/integrations and their actions, query the live catalog with the CLI:
181
-
182
- ```bash
183
- keystroke app list # list all registered/supported apps
184
- keystroke app search <query> # find an app and its slug in the full catalog
185
- keystroke app actions <slug> --search <q> # actions an app exposes
186
- keystroke app action <action-slug> # input/output schema for one action
187
- keystroke connect <slug> # connect an app credential (web flow)
188
- keystroke credentials list # List stored/available credential instances
189
- ```
190
-
191
- You can read `/learn/credentials/use-credentials` for using credentials in code and binding credentials to workflow steps and agent tools.
192
-
193
- If you ever run into issues with an integration (or a required action isn't supported), it is *extremely* easy to build custom integrations and actions. You can build connections to any HTTP API or MCP server, including internal or private ones. See `/learn/credentials/custom-integrations`.
294
+ | `/learn/logs/overview` | Reading run history, debugging deployed runs |
@@ -9,7 +9,8 @@ Keystroke is deploy-first: build in `src/`, deploy to your platform project, the
9
9
  ```bash
10
10
  pnpm install # @keystrokehq/* from GitHub Packages (see .npmrc)
11
11
  keystroke auth login # once
12
- keystroke deploy --project <id> # build + ship src/ (see: keystroke project list)
12
+ keystroke project link --project <slug> # link this directory (see: keystroke project list)
13
+ keystroke deploy # build + ship src/
13
14
  ```
14
15
 
15
16
  <!-- example:start -->
@@ -62,5 +63,5 @@ src/
62
63
  skills/ # agent skills (SKILL.md)
63
64
  triggers/ # cron, webhook, poll attachments
64
65
  workflows/ # defineWorkflow
65
- keystroke.config.ts # optional server + custom integration config
66
+ keystroke.config.ts # optional server config + platform project/org slugs
66
67
  ```
@@ -58,7 +58,6 @@ function createCliConfig(cwd = getCliConfigDir()) {
58
58
  default: DEFAULT_PLATFORM_URL
59
59
  },
60
60
  activeOrganizationId: { type: "string" },
61
- activeProjectId: { type: "string" },
62
61
  apiTarget: {
63
62
  type: "string",
64
63
  enum: ["local", "platform"]
@@ -166,4 +165,4 @@ function readCliVersion() {
166
165
  //#endregion
167
166
  export { installPlaygroundDependencies as a, createCliConfig as c, getEffectiveApiTarget as d, getPlatformUrl as f, resolvePlatformUrlForWebUrl as g, DEFAULT_WEB_URL as h, installDependencies as i, getCliConfigDir as l, DEFAULT_PLATFORM_URL as m, buildPlaygroundWorkspace as n, resolvePackageManager as o, getWebUrl as p, detectPackageManager as r, resolveCliRoot as s, readCliVersion as t, getConfigDir as u };
168
167
 
169
- //# sourceMappingURL=version-DcR3O1UD.mjs.map
168
+ //# sourceMappingURL=version-pY9N8XlL.mjs.map