1
0

gen-third-party-notices.ts 35 KB

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