gen-third-party-notices.ts 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769
  1. /**
  2. * Generate `THIRD_PARTY_NOTICES.md` from the workspace manifests: every
  3. * external dependency named by a workspace `package.json`, the vendored-package
  4. * manifest in `vendor/README.md`, the Python `pyproject.toml` files, and the
  5. * pnpm patch list. License and repository metadata come from the installed
  6. * store, so the tree must be installed. `--check` verifies the committed
  7. * artifact. Tier policy and ownership live in
  8. * `.agents/notes/implemented/process/2026-07-30-generated-third-party-notices.md`.
  9. */
  10. import { existsSync, globSync, readdirSync, readFileSync, writeFileSync } from 'node:fs'
  11. import { resolve } from 'node:path'
  12. import * as yaml from 'js-yaml'
  13. import { parse as parseToml, type TomlTableWithoutBigInt, type TomlValueWithoutBigInt } from 'smol-toml'
  14. import parseSpdx from 'spdx-expression-parse'
  15. const root = resolve(import.meta.dirname, '..')
  16. const OUT = 'THIRD_PARTY_NOTICES.md'
  17. /** Dependency-declaration kinds a consumer resolves at runtime. */
  18. const RUNTIME_KINDS = ['dependencies', 'optionalDependencies'] as const
  19. /** All manifest sections that name an external package this file must disclose. */
  20. const ALL_KINDS = ['dependencies', 'devDependencies', 'optionalDependencies', 'peerDependencies'] as const
  21. /**
  22. * Workspace areas that never reach a user: repository tooling and gates (the
  23. * root manifest), test infrastructure, the documentation site, and the native
  24. * launcher's build workspace. A runtime
  25. * declaration by anything outside these areas is a disclosure-relevant
  26. * runtime dependency because any plugin package can be mounted from a user's
  27. * `cordis.yml`.
  28. */
  29. const DEV_ONLY_AREAS = [
  30. 'package.json',
  31. 'packages/test-support/',
  32. 'packages/test-support/client-runtime/',
  33. 'website/',
  34. 'native/',
  35. ] as const
  36. /** First-party public native packages: reachable at runtime but not third-party. */
  37. const FIRST_PARTY = new Set([
  38. '@deepseek-ai/node-addon-landlock-run',
  39. '@deepseek-ai/node-addon-landlock-run-linux-arm64',
  40. '@deepseek-ai/node-addon-landlock-run-linux-x64',
  41. ])
  42. /** Official SDK identity covered by the project's narrow owner authorization. */
  43. export const CLAUDE_AGENT_SDK_PACKAGE = '@anthropic-ai/claude-agent-sdk'
  44. const CLAUDE_PLATFORM_PACKAGE_PREFIX = `${CLAUDE_AGENT_SDK_PACKAGE}-`
  45. const CLAUDE_PLATFORM_DECLARED_LICENSE = 'SEE LICENSE IN LICENSE.md'
  46. /**
  47. * Whether a non-permissive runtime declaration has an identity-scoped owner
  48. * authorization. This does not reclassify its terms as permissive.
  49. * @param name - exact npm package identity.
  50. * @returns true only for the official Claude Agent SDK package.
  51. */
  52. export function isOwnerAuthorizedRuntime(name: string): boolean {
  53. return name === CLAUDE_AGENT_SDK_PACKAGE
  54. }
  55. /**
  56. * Metadata overrides where the installed manifest is wrong or unreachable.
  57. * Each entry documents why the store cannot answer.
  58. */
  59. const OVERRIDES: Record<string, { license?: string; repo?: string }> = {
  60. // Rust workspaces publishing npm bins without `license` in package.json.
  61. 'oxlint': { license: 'MIT', repo: 'https://github.com/oxc-project/oxc' },
  62. 'oxlint-tsgolint': { license: 'MIT', repo: 'https://github.com/oxc-project/tsgolint' },
  63. // `license: SEE LICENSE IN LICENSE`: the servers repo is mid MIT→Apache-2.0
  64. // relicensing, so the effective terms are per-contribution.
  65. '@modelcontextprotocol/server-everything': { license: 'MIT / Apache-2.0', repo: 'https://github.com/modelcontextprotocol/servers' },
  66. '@modelcontextprotocol/server-filesystem': { license: 'MIT / Apache-2.0', repo: 'https://github.com/modelcontextprotocol/servers' },
  67. // No repository field in the published manifest.
  68. 'node-addon-require-builtin': { repo: 'https://www.npmjs.com/package/node-addon-require-builtin' },
  69. }
  70. /**
  71. * Python dependencies are few and named directly in `pyproject.toml` files
  72. * without installed metadata to harvest, so license/repo are recorded here and
  73. * the generator fails when a manifest names a package this map misses.
  74. */
  75. const PYTHON_METADATA: Record<string, { license: string; repo: string; role: string }> = {
  76. pydantic: { license: 'MIT', repo: 'https://github.com/pydantic/pydantic', role: 'runtime dependency of `deepseek-harness-sdk`' },
  77. hatchling: { license: 'MIT', repo: 'https://github.com/pypa/hatch', role: 'build backend' },
  78. pytest: { license: 'MIT', repo: 'https://github.com/pytest-dev/pytest', role: 'test-only' },
  79. }
  80. type PythonMetadata = typeof PYTHON_METADATA
  81. /** Tools fetched by scripts at build time, keyed by the pin the script owns. */
  82. const BUILD_TIME_TOOLS = [
  83. {
  84. name: '@yao-pkg/pkg',
  85. license: 'MIT',
  86. repo: 'https://github.com/yao-pkg/pkg',
  87. role: 'invoked by `scripts/build-exe-for-python-sdk.ts` to assemble the single-file SDK runtime executable',
  88. pinSource: 'scripts/build-exe-for-python-sdk.ts',
  89. },
  90. ]
  91. /** The `package.json` fields this generator reads. */
  92. export interface Manifest {
  93. name?: string
  94. version?: string
  95. private?: boolean
  96. license?: string
  97. dependencies?: Record<string, string>
  98. devDependencies?: Record<string, string>
  99. optionalDependencies?: Record<string, string>
  100. peerDependencies?: Record<string, string>
  101. }
  102. /** One disclosed external npm dependency. */
  103. interface ExternalDep {
  104. name: string
  105. license: string
  106. repo: string
  107. /** True when some shipped workspace consumer reaches it through runtime dependency edges. */
  108. runtime: boolean
  109. }
  110. /** Read and parse a workspace-relative `package.json`. */
  111. function readManifest(rel: string): Manifest {
  112. return JSON.parse(readFileSync(resolve(root, rel), 'utf8')) as Manifest
  113. }
  114. /**
  115. * Manifest globs, derived from the workspace declarations rather than listed
  116. * here, so a new member area (`tools/*`) is read the day it is declared.
  117. * @returns one glob per manifest-bearing location, repository-relative.
  118. */
  119. export function manifestPatterns(rootMembers: readonly string[]): string[] {
  120. return [
  121. 'package.json',
  122. ...rootMembers.map(member => `${member}/package.json`),
  123. ]
  124. }
  125. /** The `packages:` member globs declared by one pnpm workspace file. */
  126. function workspaceMembers(rel: string): string[] {
  127. const declared = (yaml.load(readFileSync(resolve(root, rel), 'utf8')) as { packages?: unknown }).packages
  128. if (!Array.isArray(declared) || declared.length === 0) {
  129. throw new Error(`gen-third-party-notices: ${rel} declares no workspace members; the manifest set cannot be derived.`)
  130. }
  131. return declared.map(member => String(member))
  132. }
  133. /**
  134. * Every workspace manifest, keyed by repository-relative path, plus the set of
  135. * workspace package names. Paths are normalized to `/` at ingestion: Node's
  136. * `fs.globSync` returns OS-native separators, and the area matching in
  137. * `tierExternalDeps` compares `/`-suffixed prefixes, so Windows backslashes
  138. * would silently push dev-area manifests into the runtime tier.
  139. */
  140. function loadWorkspaceManifests(): { manifests: Map<string, Manifest>; names: Set<string> } {
  141. const patterns = manifestPatterns(workspaceMembers('pnpm-workspace.yaml'))
  142. const manifests = new Map<string, Manifest>()
  143. const names = new Set<string>()
  144. for (const pattern of patterns) {
  145. for (const path of globSync(pattern, { cwd: root })) {
  146. const normalized = path.replaceAll('\\', '/')
  147. const manifest = readManifest(normalized)
  148. manifests.set(normalized, manifest)
  149. if (manifest.name !== undefined) names.add(manifest.name)
  150. }
  151. }
  152. if (manifests.size < 100) throw new Error(`gen-third-party-notices: only ${manifests.size} workspace manifests found; the glob set is stale.`)
  153. return { manifests, names }
  154. }
  155. type VirtualManifest = Manifest & {
  156. claudeCodeVersion?: string
  157. license?: string
  158. repository?: string | { url?: string }
  159. homepage?: string
  160. }
  161. /** One platform payload declared by the official Claude Agent SDK. */
  162. export interface ClaudePlatformPayload {
  163. readonly name: string
  164. readonly version: string
  165. }
  166. /** Current SDK and CLI distribution facts derived from the installed SDK manifest. */
  167. export interface ClaudeDistribution {
  168. readonly sdkVersion: string
  169. readonly claudeCodeVersion: string
  170. readonly payloads: ClaudePlatformPayload[]
  171. }
  172. function requiredManifestString(
  173. value: string | undefined,
  174. field: string,
  175. ): string {
  176. if (value === undefined || value.length === 0) {
  177. throw new Error(`gen-third-party-notices: ${CLAUDE_AGENT_SDK_PACKAGE} has no ${field}.`)
  178. }
  179. return value
  180. }
  181. /**
  182. * Derive the official platform payload set without a version or platform
  183. * allowlist. Only identities in the SDK's own package namespace are covered.
  184. * @param manifest - installed official SDK manifest.
  185. * @returns current SDK, CLI, and optional platform payload facts.
  186. */
  187. export function claudeDistributionFromManifest(
  188. manifest: VirtualManifest,
  189. ): ClaudeDistribution {
  190. if (manifest.name !== CLAUDE_AGENT_SDK_PACKAGE) {
  191. throw new Error(
  192. `gen-third-party-notices: expected ${CLAUDE_AGENT_SDK_PACKAGE} manifest, got ${JSON.stringify(manifest.name)}.`,
  193. )
  194. }
  195. const sdkVersion = requiredManifestString(manifest.version, 'version')
  196. const claudeCodeVersion = requiredManifestString(
  197. manifest.claudeCodeVersion,
  198. 'claudeCodeVersion',
  199. )
  200. const entries = Object.entries(manifest.optionalDependencies ?? {})
  201. if (entries.length === 0) {
  202. throw new Error(
  203. `gen-third-party-notices: ${CLAUDE_AGENT_SDK_PACKAGE} declares no optional platform payloads.`,
  204. )
  205. }
  206. const payloads = entries.map(([name, version]) => {
  207. if (!name.startsWith(CLAUDE_PLATFORM_PACKAGE_PREFIX)) {
  208. throw new Error(
  209. `gen-third-party-notices: ${CLAUDE_AGENT_SDK_PACKAGE} optional dependency ${name} is outside its authorized platform-payload identity.`,
  210. )
  211. }
  212. return {
  213. name,
  214. version: requiredManifestString(version, `${name} optional dependency version`),
  215. }
  216. }).sort((left, right) => left.name.localeCompare(right.name))
  217. return { sdkVersion, claudeCodeVersion, payloads }
  218. }
  219. /**
  220. * Resolve one package's manifest inside a pnpm virtual store. The prefix scan
  221. * matches ordinary `@scope+name@version` directory names; pnpm 11 truncates
  222. * long names (a peer-suffixed name past the length limit becomes
  223. * `<prefix>_<hash>`), so a content scan falls back over the whole store when
  224. * the prefix misses.
  225. *
  226. * @param virtual - the `.pnpm` virtual store directory to scan.
  227. * @param name - the external package name, exactly as `node_modules` spells it.
  228. * @returns the parsed manifest, or `undefined` when neither the prefix match
  229. * nor the content scan finds the package's `package.json`.
  230. */
  231. export function virtualManifest(virtual: string, name: string): VirtualManifest | undefined {
  232. const prefix = `${name.replace('/', '+')}@`
  233. const entry = readdirSync(virtual).find(dir => dir.startsWith(prefix))
  234. if (entry !== undefined) {
  235. return JSON.parse(readFileSync(resolve(virtual, entry, 'node_modules', name, 'package.json'), 'utf8')) as VirtualManifest
  236. }
  237. for (const dir of readdirSync(virtual)) {
  238. const candidate = resolve(virtual, dir, 'node_modules', name, 'package.json')
  239. if (existsSync(candidate)) {
  240. return JSON.parse(readFileSync(candidate, 'utf8')) as VirtualManifest
  241. }
  242. }
  243. return undefined
  244. }
  245. /** Resolve one installed external package manifest from either pnpm store. */
  246. function installedManifest(name: string): VirtualManifest | undefined {
  247. let manifest: (Manifest & { license?: string; repository?: string | { url?: string }; homepage?: string }) | undefined
  248. // Workspace-local link farms can expose a dependency that is not linked at
  249. // the repository root; both are backed by the root workspace's lockfile.
  250. for (const store of ['node_modules', 'native/landlock-run/node_modules']) {
  251. const direct = resolve(root, store, name, 'package.json')
  252. if (existsSync(direct)) {
  253. manifest = JSON.parse(readFileSync(direct, 'utf8')) as typeof manifest
  254. break
  255. }
  256. const virtual = resolve(root, store, '.pnpm')
  257. if (!existsSync(virtual)) continue
  258. manifest = virtualManifest(virtual, name)
  259. if (manifest !== undefined) break
  260. }
  261. return manifest
  262. }
  263. /** License and repository URL for an installed external package, from the pnpm store. */
  264. function installedMetadata(name: string): { license: string; repo: string } {
  265. const override = OVERRIDES[name]
  266. const manifest = installedManifest(name)
  267. const license = override?.license ?? manifest?.license
  268. const rawRepo = typeof manifest?.repository === 'string' ? manifest.repository : manifest?.repository?.url ?? manifest?.homepage
  269. const repo = override?.repo ?? normalizeRepo(rawRepo)
  270. if (license === undefined || repo === undefined) {
  271. throw new Error(`gen-third-party-notices: cannot resolve ${license === undefined ? 'license' : 'repository'} for ${name}; run \`pnpm install\`, or add an OVERRIDES entry.`)
  272. }
  273. return { license, repo }
  274. }
  275. function collectClaudeDistribution(): ClaudeDistribution {
  276. const manifest = installedManifest(CLAUDE_AGENT_SDK_PACKAGE)
  277. if (manifest === undefined) {
  278. throw new Error(
  279. `gen-third-party-notices: cannot resolve ${CLAUDE_AGENT_SDK_PACKAGE}; run \`pnpm install\`.`,
  280. )
  281. }
  282. const distribution = claudeDistributionFromManifest(manifest)
  283. let installedPayloads = 0
  284. for (const payload of distribution.payloads) {
  285. const installed = installedManifest(payload.name)
  286. if (installed === undefined) continue
  287. installedPayloads += 1
  288. if (
  289. installed.name !== payload.name
  290. || installed.version !== payload.version
  291. || installed.license !== CLAUDE_PLATFORM_DECLARED_LICENSE
  292. ) {
  293. throw new Error(
  294. `gen-third-party-notices: installed ${payload.name} does not match its SDK-declared version and ${CLAUDE_PLATFORM_DECLARED_LICENSE} license field.`,
  295. )
  296. }
  297. }
  298. if (installedPayloads === 0) {
  299. throw new Error(
  300. 'gen-third-party-notices: no SDK-declared Claude platform payload is installed; install optional dependencies before regenerating.',
  301. )
  302. }
  303. return distribution
  304. }
  305. /** Normalize a manifest repository/homepage value to a browsable https URL. */
  306. function normalizeRepo(raw: string | undefined): string | undefined {
  307. if (raw === undefined || raw === '') return undefined
  308. let url = raw
  309. .replace(/^git\+ssh:\/\/git@/, 'https://')
  310. .replace(/^git\+/, '')
  311. .replace(/^git:\/\//, 'https://')
  312. .replace(/^github:/, 'https://github.com/')
  313. .replace(/\.git$/, '')
  314. if (!url.startsWith('http')) url = `https://github.com/${url}`
  315. return url
  316. }
  317. /**
  318. * External npm dependencies, tiered by which workspace area declares them at
  319. * runtime: a package is runtime when any manifest outside `DEV_ONLY_AREAS`
  320. * names it in `dependencies`/`optionalDependencies`. A package declared only
  321. * by tooling, test infrastructure, the website, or the demo leaves — whatever
  322. * the declaring section is called — is development-only.
  323. */
  324. function collectNpmDeps(): ExternalDep[] {
  325. const { manifests, names } = loadWorkspaceManifests()
  326. return [...tierExternalDeps(manifests, names)]
  327. .filter(([name]) => !FIRST_PARTY.has(name))
  328. .sort(([a], [b]) => a.localeCompare(b))
  329. .map(([name, runtime]) => ({ name, ...installedMetadata(name), runtime }))
  330. }
  331. /**
  332. * Tier every external dependency the workspace declares.
  333. * @param manifests - workspace manifests keyed by repository-relative path.
  334. * @param names - every workspace package name, which never counts as external.
  335. * @returns each external package mapped to whether it is a runtime dependency.
  336. */
  337. export function tierExternalDeps(manifests: Map<string, Manifest>, names: Set<string>): Map<string, boolean> {
  338. const tiers = new Map<string, boolean>()
  339. // `tsx` is runtime by fiat: the root source-run scripts execute through its ESM hook.
  340. tiers.set('tsx', true)
  341. for (const [path, manifest] of manifests) {
  342. const devOnly = DEV_ONLY_AREAS.some(area => (area.endsWith('/') ? path.startsWith(area) : path === area))
  343. for (const kind of ALL_KINDS) {
  344. for (const [dep, range] of Object.entries(manifest[kind] ?? {})) {
  345. if (names.has(dep) || range.startsWith('workspace:')) continue
  346. const runtime = !devOnly && (RUNTIME_KINDS as readonly string[]).includes(kind)
  347. tiers.set(dep, (tiers.get(dep) ?? false) || runtime)
  348. }
  349. }
  350. }
  351. return tiers
  352. }
  353. /** A vendored package row parsed out of the `vendor/README.md` manifest table. */
  354. export interface VendoredRow {
  355. npmName: string
  356. /** The name this package carries upstream; MIT attribution names the fork's origin, not our scope. */
  357. upstreamName: string
  358. upstream: string
  359. }
  360. /**
  361. * Parse the vendored-package manifest table out of `vendor/README.md`.
  362. * @param text - the complete `vendor/README.md` contents.
  363. * @returns one row per manifest-table entry, in table order.
  364. */
  365. export function parseVendoredRows(text: string): VendoredRow[] {
  366. const rows: VendoredRow[] = []
  367. for (const line of text.split('\n')) {
  368. const match = new RegExp(String.raw`^\| \x60\S+\/\x60 \| \x60([^\x60]+)\x60 \| \x60([^\x60]+)\x60 \| \S+ \| `
  369. + String.raw`(https:\/\/\S+?)(?: \([^)]*\))? \| \x60[0-9a-f]+\x60 \|$`).exec(line)
  370. if (match === null) continue
  371. const [, npmName, upstreamName, upstream] = match
  372. if (npmName === undefined || upstreamName === undefined || upstream === undefined) continue
  373. rows.push({ npmName, upstreamName, upstream })
  374. }
  375. return rows
  376. }
  377. /**
  378. * Parse the vendored manifest table and confirm it accounts for every vendored
  379. * directory. The `vendor/` tree — not the table — is the set that must be
  380. * disclosed, so a row that stops matching the table format is a hard error
  381. * rather than a package that quietly vanishes from the notices.
  382. */
  383. function collectVendored(): VendoredRow[] {
  384. const rows = parseVendoredRows(readFileSync(resolve(root, 'vendor/README.md'), 'utf8'))
  385. const onDisk = new Map<string, string>()
  386. for (const entry of readdirSync(resolve(root, 'vendor'), { withFileTypes: true })) {
  387. if (!entry.isDirectory()) continue
  388. const manifest = readManifest(`vendor/${entry.name}/package.json`)
  389. if (manifest.name !== undefined) onDisk.set(manifest.name, entry.name)
  390. }
  391. const parsed = new Set(rows.map(row => row.npmName))
  392. const missing = [...onDisk.keys()].filter(name => !parsed.has(name))
  393. if (missing.length > 0) {
  394. throw new Error(`gen-third-party-notices: vendor/README.md has no manifest-table row for ${missing.join(', ')}; its table format changed or the sync is incomplete.`)
  395. }
  396. for (const row of rows) {
  397. const dir = onDisk.get(row.npmName)
  398. if (dir === undefined) throw new Error(`gen-third-party-notices: vendored package ${row.npmName} from vendor/README.md has no vendor/ directory.`)
  399. const license = readManifest(`vendor/${dir}/package.json`).license
  400. if (license !== 'MIT') {
  401. throw new Error(`gen-third-party-notices: vendored ${row.npmName} declares license ${JSON.stringify(license)}; the vendored section assumes MIT throughout.`)
  402. }
  403. }
  404. return rows
  405. }
  406. /** Whether a parsed TOML value is a table rather than an array or scalar. */
  407. function isTomlTable(value: TomlValueWithoutBigInt | undefined): value is TomlTableWithoutBigInt {
  408. return value !== undefined && typeof value === 'object' && !Array.isArray(value)
  409. }
  410. /** Parse one PEP 508 requirement string into its distribution name. */
  411. function parsePythonRequirement(requirement: string): string {
  412. const name = /^\s*([a-zA-Z][a-zA-Z0-9._-]*)\s*(?:\[[^\]]*\])?\s*(?:[<>=!~;@].*)?$/.exec(requirement)?.[1]
  413. if (name === undefined) {
  414. throw new Error(`gen-third-party-notices: cannot read a distribution name from the requirement ${JSON.stringify(requirement)}.`)
  415. }
  416. return name
  417. }
  418. /** Add the string requirements from one parsed TOML array. */
  419. function collectPythonRequirementArray(
  420. names: string[],
  421. value: TomlValueWithoutBigInt | undefined,
  422. location: string,
  423. allowGroupIncludes = false,
  424. ): void {
  425. if (value === undefined) return
  426. if (!Array.isArray(value)) {
  427. throw new Error(`gen-third-party-notices: ${location} must be an array.`)
  428. }
  429. for (const item of value) {
  430. if (typeof item === 'string') {
  431. names.push(parsePythonRequirement(item))
  432. continue
  433. }
  434. if (allowGroupIncludes && isTomlTable(item) && typeof item['include-group'] === 'string' && Object.keys(item).length === 1) {
  435. continue
  436. }
  437. throw new Error(`gen-third-party-notices: ${location} contains an unsupported requirement entry.`)
  438. }
  439. }
  440. /** Read an optional TOML table and reject a present non-table value. */
  441. function optionalTomlTable(value: TomlValueWithoutBigInt | undefined, location: string): TomlTableWithoutBigInt | undefined {
  442. if (value === undefined || isTomlTable(value)) return value
  443. throw new Error(`gen-third-party-notices: ${location} must be a table.`)
  444. }
  445. /**
  446. * Parse a `pyproject.toml` project identity and every requirement it declares:
  447. * `requires` under
  448. * `[build-system]`, `dependencies` under `[project]`, and every key under
  449. * `[project.optional-dependencies]` and `[dependency-groups]`. A TOML parser
  450. * owns comments, quoted keys, escapes, and array boundaries; unsupported
  451. * requirement forms fail instead of disappearing from the notices.
  452. * @param text - the complete `pyproject.toml` contents.
  453. * @returns the local project name and declared requirement names.
  454. */
  455. function parsePyproject(text: string): { projectName?: string; requirements: string[] } {
  456. const names: string[] = []
  457. const document = parseToml(text, { integersAsBigInt: false })
  458. const buildSystem = optionalTomlTable(document['build-system'], '[build-system]')
  459. const project = optionalTomlTable(document.project, '[project]')
  460. const projectName = project?.name
  461. if (projectName !== undefined && typeof projectName !== 'string') {
  462. throw new Error('gen-third-party-notices: [project].name must be a string.')
  463. }
  464. collectPythonRequirementArray(names, buildSystem?.requires, '[build-system].requires')
  465. collectPythonRequirementArray(names, project?.dependencies, '[project].dependencies')
  466. const optional = optionalTomlTable(project?.['optional-dependencies'], '[project.optional-dependencies]')
  467. for (const [group, requirements] of Object.entries(optional ?? {})) {
  468. collectPythonRequirementArray(names, requirements, `[project.optional-dependencies].${group}`)
  469. }
  470. const groups = optionalTomlTable(document['dependency-groups'], '[dependency-groups]')
  471. for (const [group, requirements] of Object.entries(groups ?? {})) {
  472. collectPythonRequirementArray(names, requirements, `[dependency-groups].${group}`, true)
  473. }
  474. return projectName === undefined
  475. ? { requirements: names }
  476. : { projectName, requirements: names }
  477. }
  478. /**
  479. * Read every requirement name declared by one `pyproject.toml`.
  480. * @param text - the complete `pyproject.toml` contents.
  481. * @returns each declared requirement's distribution name, in file order.
  482. */
  483. export function parsePyprojectRequirements(text: string): string[] {
  484. return parsePyproject(text).requirements
  485. }
  486. /** Normalize a Python distribution name according to the packaging name rule. */
  487. function normalizePythonDistributionName(name: string): string {
  488. return name.toLowerCase().replace(/[-_.]+/g, '-')
  489. }
  490. /**
  491. * Resolve external Python dependencies after excluding local project names.
  492. * @param pyprojects - complete local `pyproject.toml` contents.
  493. * @param metadata - disclosure metadata for every external dependency.
  494. * @returns disclosed dependencies in normalized name order.
  495. */
  496. export function collectPythonDependencies(
  497. pyprojects: string[],
  498. metadata: PythonMetadata = PYTHON_METADATA,
  499. ): { name: string; license: string; repo: string; role: string }[] {
  500. const parsed = pyprojects.map(parsePyproject)
  501. const firstParty = new Set(parsed.flatMap(({ projectName }) => (
  502. projectName === undefined ? [] : [normalizePythonDistributionName(projectName)]
  503. )))
  504. const found = new Set(parsed
  505. .flatMap(({ requirements }) => requirements.map(normalizePythonDistributionName))
  506. .filter(name => !firstParty.has(name)))
  507. return [...found].sort((a, b) => a.localeCompare(b)).map((name) => {
  508. const entry = metadata[name]
  509. if (entry === undefined) throw new Error(`gen-third-party-notices: python dependency ${name} is missing from PYTHON_METADATA.`)
  510. return { name, ...entry }
  511. })
  512. }
  513. /** Direct Python dependencies named by the `pyproject.toml` manifests under `python/`. */
  514. function collectPython(): { name: string; license: string; repo: string; role: string }[] {
  515. const manifests = globSync('python/*/pyproject.toml', { cwd: root })
  516. if (manifests.length === 0) throw new Error('gen-third-party-notices: no python/*/pyproject.toml found; the Python tree moved.')
  517. return collectPythonDependencies(manifests.map(path => readFileSync(resolve(root, path), 'utf8')))
  518. }
  519. /** pnpm-patched external packages, from `pnpm-workspace.yaml`. */
  520. function collectPatched(): { spec: string; patch: string }[] {
  521. const workspace = yaml.load(readFileSync(resolve(root, 'pnpm-workspace.yaml'), 'utf8')) as { patchedDependencies?: Record<string, string> }
  522. return Object.entries(workspace.patchedDependencies ?? {}).map(([spec, patch]) => ({ spec, patch }))
  523. }
  524. /** Verify each build-time tool pin still appears in its owning script. */
  525. function verifyBuildTimePins(): void {
  526. for (const tool of BUILD_TIME_TOOLS) {
  527. const text = readFileSync(resolve(root, tool.pinSource), 'utf8')
  528. if (!text.includes(tool.name)) {
  529. throw new Error(`gen-third-party-notices: ${tool.pinSource} no longer references ${tool.name}; update BUILD_TIME_TOOLS.`)
  530. }
  531. }
  532. }
  533. /** SPDX identifiers this project may ship without further review. */
  534. const PERMISSIVE_LICENSES = new Set(['MIT', 'ISC', 'BSD-2-Clause', 'BSD-3-Clause', 'Apache-2.0', '0BSD', 'Unlicense', 'CC0-1.0', 'BlueOak-1.0.0', 'Python-2.0'])
  535. /** Evaluate a parsed SPDX expression under the repository's license policy. */
  536. function isPermissiveSpdx(expression: ReturnType<typeof parseSpdx>): boolean {
  537. if ('conjunction' in expression) {
  538. return expression.conjunction === 'and'
  539. ? isPermissiveSpdx(expression.left) && isPermissiveSpdx(expression.right)
  540. : isPermissiveSpdx(expression.left) || isPermissiveSpdx(expression.right)
  541. }
  542. return expression.plus !== true
  543. && expression.exception === undefined
  544. && PERMISSIVE_LICENSES.has(expression.license)
  545. }
  546. /**
  547. * Whether an SPDX expression grants terms this project may ship under.
  548. * `OR` needs one permissive alternative, because the consumer chooses; `AND`
  549. * needs all of them, because every obligation applies. Anything that is not a
  550. * recognized permissive identifier — copyleft, an exception clause, or a
  551. * license this list has never seen — evaluates to false, so an unfamiliar
  552. * expression fails closed rather than passing on a partial match.
  553. * @param license - the SPDX expression from the package manifest.
  554. * @returns true when the expression's obligations are all permissive.
  555. */
  556. export function isPermissive(license: string): boolean {
  557. // Some npm manifests use a slash for a choice despite SPDX requiring `OR`.
  558. const normalized = license.replace(/\s*\/\s*/g, ' OR ').trim()
  559. try {
  560. return isPermissiveSpdx(parseSpdx(normalized))
  561. } catch {
  562. return false
  563. }
  564. }
  565. /**
  566. * Render the sentence that isolates non-permissive development tooling, or
  567. * nothing at all when every development dependency is permissive.
  568. * @param deps - development dependencies whose license is not permissive.
  569. * @returns the paragraph to place after the development table.
  570. */
  571. function renderNonPermissiveNote(deps: ExternalDep[]): string {
  572. if (deps.length === 0) return ''
  573. const named = deps.map(dep => `\`${dep.name}\` (${dep.license})`)
  574. const subject = named.length === 1 ? named[0] : `${named.slice(0, -1).join(', ')} and ${named.at(-1)}`
  575. return `\n${subject} ${named.length === 1 ? 'runs' : 'run'} only as development tooling; their code is not linked into or distributed with any DeepSeek Harness artifact.\n`
  576. }
  577. /** Render one npm dependency table. */
  578. function renderNpmTable(deps: ExternalDep[]): string {
  579. const lines = ['| Package | License |', '| --- | --- |']
  580. for (const dep of deps) lines.push(`| [\`${dep.name}\`](${dep.repo}) | ${dep.license} |`)
  581. return lines.join('\n')
  582. }
  583. function renderClaudeDistribution(
  584. distribution: ClaudeDistribution | undefined,
  585. ): string {
  586. if (distribution === undefined) return ''
  587. const rows = distribution.payloads.map(payload =>
  588. `| [\`${payload.name}\`](https://www.npmjs.com/package/${payload.name}) | ${payload.version} | ${CLAUDE_PLATFORM_DECLARED_LICENSE} |`,
  589. )
  590. return `
  591. ## Official Claude Code platform payloads
  592. The project owner authorizes distribution of every version of the official \`${CLAUDE_AGENT_SDK_PACKAGE}\` package and the official Claude Code CLI/platform payloads that each version declares through \`optionalDependencies\`. This identity-scoped authorization does not classify their declared terms as permissive and does not cover any unrelated runtime package; version, declared-license, and payload-set changes still require the ordinary dependency, lockfile, compatibility, terms, and notices review.
  593. The installed SDK ${distribution.sdkVersion} declares the following optional platform packages. Each carries the official Claude Code ${distribution.claudeCodeVersion} executable; the package identities and versions come from the SDK manifest, while the declared license field is verified against the platform payload installed for the current host.
  594. | Optional platform package | Version | Declared license |
  595. | --- | --- | --- |
  596. ${rows.join('\n')}
  597. `
  598. }
  599. /**
  600. * Render the complete notices document.
  601. * @returns the exact bytes `THIRD_PARTY_NOTICES.md` must hold.
  602. */
  603. export function render(): string {
  604. verifyBuildTimePins()
  605. const npm = collectNpmDeps()
  606. const runtimeDeps = npm.filter(dep => dep.runtime)
  607. const devDeps = npm.filter(dep => !dep.runtime)
  608. const vendored = collectVendored()
  609. const python = collectPython()
  610. const patched = collectPatched()
  611. const claudeDistribution = runtimeDeps.some(
  612. dep => dep.name === CLAUDE_AGENT_SDK_PACKAGE,
  613. )
  614. ? collectClaudeDistribution()
  615. : undefined
  616. const nonPermissiveDev = devDeps.filter(dep => !isPermissive(dep.license))
  617. // A copyleft license reaching a shipped surface is a distribution decision,
  618. // not a rendering detail; the notices cannot quietly absorb it.
  619. const nonPermissiveRuntime = runtimeDeps.filter(dep =>
  620. !isPermissive(dep.license)
  621. && !isOwnerAuthorizedRuntime(dep.name),
  622. )
  623. if (nonPermissiveRuntime.length > 0) {
  624. throw new Error(`gen-third-party-notices: runtime ${nonPermissiveRuntime.map(dep => `${dep.name} (${dep.license})`).join(', ')} is not a permissive license; review the distribution terms and record the decision before regenerating.`)
  625. }
  626. const patchedLines = patched.map(({ spec, patch }) => `- \`${spec}\` — [\`${patch}\`](${patch})`)
  627. return `<!-- Generated by scripts/gen-third-party-notices.ts — do not edit by hand.
  628. Run \`pnpm run gen-third-party-notices\` to regenerate. -->
  629. # Third-Party Notices
  630. DeepSeek Harness is licensed under [MIT](LICENSE). It depends on the third-party software listed below. Each project remains under its own license; nothing in this file changes those terms.
  631. This file lists **direct** dependencies declared by the workspace and the explicitly disclosed official Claude Code platform payload closure. It is generated from the workspace manifests by \`scripts/gen-third-party-notices.ts\`: a pre-commit hook regenerates it whenever a staged file changes one of its inputs, and \`scripts/gen-third-party-notices.spec.ts\` asserts in the test lane that the committed bytes match. Deleting a manifest runs no hook, so that case is caught by the assertion instead. Run \`pnpm run verify-third-party-notices\` for the standalone check.
  632. The complete npm transitive closure, including the Landlock launcher workspace, is recorded with exact pinned versions in [\`pnpm-lock.yaml\`](pnpm-lock.yaml) — inspect it with \`pnpm licenses list\`. The Python closure is recorded separately in [\`python/sdk/uv.lock\`](python/sdk/uv.lock).
  633. ## Vendored source (\`vendor/\`)
  634. The Cordis framework and its foundation libraries are source-vendored into this repository rather than consumed from npm, and republished under the \`@deepseek-ai\` scope. All are MIT-licensed; each directory preserves its upstream \`LICENSE\` file. Exact upstream commits and local modifications are recorded in [\`vendor/README.md\`](vendor/README.md).
  635. | Package | Upstream name | Upstream | License |
  636. | --- | --- | --- | --- |
  637. ${vendored.map(row => `| \`${row.npmName}\` | \`${row.upstreamName}\` | [${row.upstream.replace('https://', '')}](${row.upstream}) | MIT |`).join('\n')}
  638. ## Runtime npm dependencies
  639. External packages that a workspace package resolves at runtime. The tier covers every plugin a user can mount from \`cordis.yml\` — not only what the \`dsh\` CLI, Web UI, and Python SDK runtime load by default.
  640. ${renderNpmTable(runtimeDeps)}
  641. pnpm applies local patches to the following packages at install time, so shipped artifacts carry modified copies; each patch file is the complete record of the modification:
  642. ${patchedLines.join('\n')}
  643. ${renderClaudeDistribution(claudeDistribution)}
  644. ## Development-only npm dependencies
  645. External packages **directly declared** only by repository tooling, test infrastructure, the documentation site, the demo leaves, or the native launcher's build workspace. No shipped surface names them itself. A package here may still be pulled in transitively by a runtime dependency — \`pnpm-lock.yaml\` is the authority on the full closure — so this tier records who declares a package, not what a build ultimately bundles.
  646. ${renderNpmTable(devDeps)}
  647. ${renderNonPermissiveNote(nonPermissiveDev)}
  648. ## Python SDK dependencies (\`python/\`)
  649. Direct dependencies of the \`pyproject.toml\` manifests, plus \`uv\` as the development workflow tool.
  650. | Package | License | Role |
  651. | --- | --- | --- |
  652. ${python.map(dep => `| [\`${dep.name}\`](${dep.repo}) | ${dep.license} | ${dep.role} |`).join('\n')}
  653. | [\`uv\`](https://github.com/astral-sh/uv) | MIT / Apache-2.0 | development workflow tool |
  654. ## Fetched at build time
  655. | Package | License | Role |
  656. | --- | --- | --- |
  657. ${BUILD_TIME_TOOLS.map(tool => `| [\`${tool.name}\`](${tool.repo}) | ${tool.license} | ${tool.role} |`).join('\n')}
  658. ## First-party native packages
  659. \`@deepseek-ai/node-addon-landlock-run\` (and its platform packages) is built and released from this repository under BSD 3-Clause. It is listed here for completeness; it is first-party, not third-party.
  660. `
  661. }
  662. /** CLI entry: default writes the notices, `--check` fails if the committed copy
  663. * is stale. Guarded behind an entry-point check so importing this module for
  664. * tests neither regenerates the committed file nor calls process.exit. */
  665. function main(): void {
  666. const content = render()
  667. if (process.argv.includes('--check')) {
  668. let committed: string | null = null
  669. try {
  670. committed = readFileSync(resolve(root, OUT), 'utf8')
  671. } catch {
  672. // Only ENOENT (not yet generated) is expected; a present-but-unreadable
  673. // file is not a state this repo produces, and the remedy is the same.
  674. committed = null
  675. }
  676. if (committed === content) {
  677. console.log(`gen-third-party-notices: ${OUT} is up to date.`)
  678. process.exit(0)
  679. }
  680. console.error(`gen-third-party-notices: ${OUT} is stale. Run \`pnpm run gen-third-party-notices\` and commit ${OUT}.`)
  681. process.exit(1)
  682. }
  683. writeFileSync(resolve(root, OUT), content)
  684. console.log(`gen-third-party-notices: wrote ${OUT}.`)
  685. }
  686. if (process.argv[1] !== undefined && import.meta.filename === resolve(process.argv[1])) {
  687. main()
  688. }