gen-third-party-notices.ts 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803
  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 { dirname, 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. * @param expectedVersion - exact version required when the store retains more than one.
  229. * @returns the parsed manifest, or `undefined` when neither the prefix match
  230. * nor the content scan finds the requested package version.
  231. */
  232. export function virtualManifest(
  233. virtual: string,
  234. name: string,
  235. expectedVersion?: string,
  236. ): VirtualManifest | undefined {
  237. const prefix = `${name.replace('/', '+')}@`
  238. const entries = readdirSync(virtual)
  239. for (const entry of entries.filter(dir => dir.startsWith(prefix))) {
  240. const manifest = JSON.parse(readFileSync(resolve(virtual, entry, 'node_modules', name, 'package.json'), 'utf8')) as VirtualManifest
  241. if (expectedVersion === undefined || manifest.version === expectedVersion) return manifest
  242. }
  243. for (const dir of entries) {
  244. const candidate = resolve(virtual, dir, 'node_modules', name, 'package.json')
  245. if (existsSync(candidate)) {
  246. const manifest = JSON.parse(readFileSync(candidate, 'utf8')) as VirtualManifest
  247. if (expectedVersion === undefined || manifest.version === expectedVersion) return manifest
  248. }
  249. }
  250. return undefined
  251. }
  252. const workspaceLinkedManifestCache = new Map<string, VirtualManifest | undefined>()
  253. /**
  254. * Resolve the package version selected for a declaring workspace instead of an
  255. * unrelated historical version that still occupies the shared virtual store.
  256. * @param name - external package identity.
  257. * @returns the first current workspace link for that package, when installed.
  258. */
  259. function workspaceLinkedManifest(name: string): VirtualManifest | undefined {
  260. if (workspaceLinkedManifestCache.has(name)) return workspaceLinkedManifestCache.get(name)
  261. for (const [path, manifest] of loadWorkspaceManifests().manifests) {
  262. if (!ALL_KINDS.some(kind => name in (manifest[kind] ?? {}))) continue
  263. const linked = resolve(root, dirname(path), 'node_modules', name, 'package.json')
  264. if (!existsSync(linked)) continue
  265. const found = JSON.parse(readFileSync(linked, 'utf8')) as VirtualManifest
  266. workspaceLinkedManifestCache.set(name, found)
  267. return found
  268. }
  269. workspaceLinkedManifestCache.set(name, undefined)
  270. return undefined
  271. }
  272. /** Resolve one installed external package manifest from either pnpm store. */
  273. function installedManifest(name: string, expectedVersion?: string): VirtualManifest | undefined {
  274. const linked = workspaceLinkedManifest(name)
  275. if (linked !== undefined && (expectedVersion === undefined || linked.version === expectedVersion)) return linked
  276. let manifest: (Manifest & { license?: string; repository?: string | { url?: string }; homepage?: string }) | undefined
  277. // Workspace-local link farms can expose a dependency that is not linked at
  278. // the repository root; both are backed by the root workspace's lockfile.
  279. for (const store of ['node_modules', 'native/landlock-run/node_modules']) {
  280. const direct = resolve(root, store, name, 'package.json')
  281. if (existsSync(direct)) {
  282. const candidate = JSON.parse(readFileSync(direct, 'utf8')) as typeof manifest
  283. if (expectedVersion === undefined || candidate?.version === expectedVersion) {
  284. manifest = candidate
  285. break
  286. }
  287. }
  288. const virtual = resolve(root, store, '.pnpm')
  289. if (!existsSync(virtual)) continue
  290. manifest = virtualManifest(virtual, name, expectedVersion)
  291. if (manifest !== undefined) break
  292. }
  293. return manifest
  294. }
  295. /** License and repository URL for an installed external package, from the pnpm store. */
  296. function installedMetadata(name: string): { license: string; repo: string } {
  297. const override = OVERRIDES[name]
  298. const manifest = installedManifest(name)
  299. const license = override?.license ?? manifest?.license
  300. const rawRepo = typeof manifest?.repository === 'string' ? manifest.repository : manifest?.repository?.url ?? manifest?.homepage
  301. const repo = override?.repo ?? normalizeRepo(rawRepo)
  302. if (license === undefined || repo === undefined) {
  303. throw new Error(`gen-third-party-notices: cannot resolve ${license === undefined ? 'license' : 'repository'} for ${name}; run \`pnpm install\`, or add an OVERRIDES entry.`)
  304. }
  305. return { license, repo }
  306. }
  307. function collectClaudeDistribution(): ClaudeDistribution {
  308. const manifest = installedManifest(CLAUDE_AGENT_SDK_PACKAGE)
  309. if (manifest === undefined) {
  310. throw new Error(
  311. `gen-third-party-notices: cannot resolve ${CLAUDE_AGENT_SDK_PACKAGE}; run \`pnpm install\`.`,
  312. )
  313. }
  314. const distribution = claudeDistributionFromManifest(manifest)
  315. let installedPayloads = 0
  316. for (const payload of distribution.payloads) {
  317. const installed = installedManifest(payload.name, payload.version)
  318. if (installed === undefined) continue
  319. installedPayloads += 1
  320. if (
  321. installed.name !== payload.name
  322. || installed.version !== payload.version
  323. || installed.license !== CLAUDE_PLATFORM_DECLARED_LICENSE
  324. ) {
  325. throw new Error(
  326. `gen-third-party-notices: installed ${payload.name} does not match its SDK-declared version and ${CLAUDE_PLATFORM_DECLARED_LICENSE} license field.`,
  327. )
  328. }
  329. }
  330. if (installedPayloads === 0) {
  331. throw new Error(
  332. 'gen-third-party-notices: no SDK-declared Claude platform payload is installed; install optional dependencies before regenerating.',
  333. )
  334. }
  335. return distribution
  336. }
  337. /** Normalize a manifest repository/homepage value to a browsable https URL. */
  338. function normalizeRepo(raw: string | undefined): string | undefined {
  339. if (raw === undefined || raw === '') return undefined
  340. let url = raw
  341. .replace(/^git\+ssh:\/\/git@/, 'https://')
  342. .replace(/^git\+/, '')
  343. .replace(/^git:\/\//, 'https://')
  344. .replace(/^github:/, 'https://github.com/')
  345. .replace(/\.git$/, '')
  346. if (!url.startsWith('http')) url = `https://github.com/${url}`
  347. return url
  348. }
  349. /**
  350. * External npm dependencies, tiered by which workspace area declares them at
  351. * runtime: a package is runtime when any manifest outside `DEV_ONLY_AREAS`
  352. * names it in `dependencies`/`optionalDependencies`. A package declared only
  353. * by tooling, test infrastructure, the website, or the demo leaves — whatever
  354. * the declaring section is called — is development-only.
  355. */
  356. function collectNpmDeps(): ExternalDep[] {
  357. const { manifests, names } = loadWorkspaceManifests()
  358. return [...tierExternalDeps(manifests, names)]
  359. .filter(([name]) => !FIRST_PARTY.has(name))
  360. .sort(([a], [b]) => a.localeCompare(b))
  361. .map(([name, runtime]) => ({ name, ...installedMetadata(name), runtime }))
  362. }
  363. /**
  364. * Tier every external dependency the workspace declares.
  365. * @param manifests - workspace manifests keyed by repository-relative path.
  366. * @param names - every workspace package name, which never counts as external.
  367. * @returns each external package mapped to whether it is a runtime dependency.
  368. */
  369. export function tierExternalDeps(manifests: Map<string, Manifest>, names: Set<string>): Map<string, boolean> {
  370. const tiers = new Map<string, boolean>()
  371. // `tsx` is runtime by fiat: the root source-run scripts execute through its ESM hook.
  372. tiers.set('tsx', true)
  373. for (const [path, manifest] of manifests) {
  374. const devOnly = DEV_ONLY_AREAS.some(area => (area.endsWith('/') ? path.startsWith(area) : path === area))
  375. for (const kind of ALL_KINDS) {
  376. for (const [dep, range] of Object.entries(manifest[kind] ?? {})) {
  377. if (names.has(dep) || range.startsWith('workspace:')) continue
  378. const runtime = !devOnly && (RUNTIME_KINDS as readonly string[]).includes(kind)
  379. tiers.set(dep, (tiers.get(dep) ?? false) || runtime)
  380. }
  381. }
  382. }
  383. return tiers
  384. }
  385. /** A vendored package row parsed out of the `vendor/README.md` manifest table. */
  386. export interface VendoredRow {
  387. npmName: string
  388. /** The name this package carries upstream; MIT attribution names the fork's origin, not our scope. */
  389. upstreamName: string
  390. upstream: string
  391. }
  392. /**
  393. * Parse the vendored-package manifest table out of `vendor/README.md`.
  394. * @param text - the complete `vendor/README.md` contents.
  395. * @returns one row per manifest-table entry, in table order.
  396. */
  397. export function parseVendoredRows(text: string): VendoredRow[] {
  398. const rows: VendoredRow[] = []
  399. for (const line of text.split('\n')) {
  400. const match = new RegExp(String.raw`^\| \x60\S+\/\x60 \| \x60([^\x60]+)\x60 \| \x60([^\x60]+)\x60 \| \S+ \| `
  401. + String.raw`(https:\/\/\S+?)(?: \([^)]*\))? \| \x60[0-9a-f]+\x60 \|$`).exec(line)
  402. if (match === null) continue
  403. const [, npmName, upstreamName, upstream] = match
  404. if (npmName === undefined || upstreamName === undefined || upstream === undefined) continue
  405. rows.push({ npmName, upstreamName, upstream })
  406. }
  407. return rows
  408. }
  409. /**
  410. * Parse the vendored manifest table and confirm it accounts for every vendored
  411. * directory. The `vendor/` tree — not the table — is the set that must be
  412. * disclosed, so a row that stops matching the table format is a hard error
  413. * rather than a package that quietly vanishes from the notices.
  414. */
  415. function collectVendored(): VendoredRow[] {
  416. const rows = parseVendoredRows(readFileSync(resolve(root, 'vendor/README.md'), 'utf8'))
  417. const onDisk = new Map<string, string>()
  418. for (const entry of readdirSync(resolve(root, 'vendor'), { withFileTypes: true })) {
  419. if (!entry.isDirectory()) continue
  420. const manifest = readManifest(`vendor/${entry.name}/package.json`)
  421. if (manifest.name !== undefined) onDisk.set(manifest.name, entry.name)
  422. }
  423. const parsed = new Set(rows.map(row => row.npmName))
  424. const missing = [...onDisk.keys()].filter(name => !parsed.has(name))
  425. if (missing.length > 0) {
  426. 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.`)
  427. }
  428. for (const row of rows) {
  429. const dir = onDisk.get(row.npmName)
  430. if (dir === undefined) throw new Error(`gen-third-party-notices: vendored package ${row.npmName} from vendor/README.md has no vendor/ directory.`)
  431. const license = readManifest(`vendor/${dir}/package.json`).license
  432. if (license !== 'MIT') {
  433. throw new Error(`gen-third-party-notices: vendored ${row.npmName} declares license ${JSON.stringify(license)}; the vendored section assumes MIT throughout.`)
  434. }
  435. }
  436. return rows
  437. }
  438. /** Whether a parsed TOML value is a table rather than an array or scalar. */
  439. function isTomlTable(value: TomlValueWithoutBigInt | undefined): value is TomlTableWithoutBigInt {
  440. return value !== undefined && typeof value === 'object' && !Array.isArray(value)
  441. }
  442. /** Parse one PEP 508 requirement string into its distribution name. */
  443. function parsePythonRequirement(requirement: string): string {
  444. const name = /^\s*([a-zA-Z][a-zA-Z0-9._-]*)\s*(?:\[[^\]]*\])?\s*(?:[<>=!~;@].*)?$/.exec(requirement)?.[1]
  445. if (name === undefined) {
  446. throw new Error(`gen-third-party-notices: cannot read a distribution name from the requirement ${JSON.stringify(requirement)}.`)
  447. }
  448. return name
  449. }
  450. /** Add the string requirements from one parsed TOML array. */
  451. function collectPythonRequirementArray(
  452. names: string[],
  453. value: TomlValueWithoutBigInt | undefined,
  454. location: string,
  455. allowGroupIncludes = false,
  456. ): void {
  457. if (value === undefined) return
  458. if (!Array.isArray(value)) {
  459. throw new Error(`gen-third-party-notices: ${location} must be an array.`)
  460. }
  461. for (const item of value) {
  462. if (typeof item === 'string') {
  463. names.push(parsePythonRequirement(item))
  464. continue
  465. }
  466. if (allowGroupIncludes && isTomlTable(item) && typeof item['include-group'] === 'string' && Object.keys(item).length === 1) {
  467. continue
  468. }
  469. throw new Error(`gen-third-party-notices: ${location} contains an unsupported requirement entry.`)
  470. }
  471. }
  472. /** Read an optional TOML table and reject a present non-table value. */
  473. function optionalTomlTable(value: TomlValueWithoutBigInt | undefined, location: string): TomlTableWithoutBigInt | undefined {
  474. if (value === undefined || isTomlTable(value)) return value
  475. throw new Error(`gen-third-party-notices: ${location} must be a table.`)
  476. }
  477. /**
  478. * Parse a `pyproject.toml` project identity and every requirement it declares:
  479. * `requires` under
  480. * `[build-system]`, `dependencies` under `[project]`, and every key under
  481. * `[project.optional-dependencies]` and `[dependency-groups]`. A TOML parser
  482. * owns comments, quoted keys, escapes, and array boundaries; unsupported
  483. * requirement forms fail instead of disappearing from the notices.
  484. * @param text - the complete `pyproject.toml` contents.
  485. * @returns the local project name and declared requirement names.
  486. */
  487. function parsePyproject(text: string): { projectName?: string; requirements: string[] } {
  488. const names: string[] = []
  489. const document = parseToml(text, { integersAsBigInt: false })
  490. const buildSystem = optionalTomlTable(document['build-system'], '[build-system]')
  491. const project = optionalTomlTable(document.project, '[project]')
  492. const projectName = project?.name
  493. if (projectName !== undefined && typeof projectName !== 'string') {
  494. throw new Error('gen-third-party-notices: [project].name must be a string.')
  495. }
  496. collectPythonRequirementArray(names, buildSystem?.requires, '[build-system].requires')
  497. collectPythonRequirementArray(names, project?.dependencies, '[project].dependencies')
  498. const optional = optionalTomlTable(project?.['optional-dependencies'], '[project.optional-dependencies]')
  499. for (const [group, requirements] of Object.entries(optional ?? {})) {
  500. collectPythonRequirementArray(names, requirements, `[project.optional-dependencies].${group}`)
  501. }
  502. const groups = optionalTomlTable(document['dependency-groups'], '[dependency-groups]')
  503. for (const [group, requirements] of Object.entries(groups ?? {})) {
  504. collectPythonRequirementArray(names, requirements, `[dependency-groups].${group}`, true)
  505. }
  506. return projectName === undefined
  507. ? { requirements: names }
  508. : { projectName, requirements: names }
  509. }
  510. /**
  511. * Read every requirement name declared by one `pyproject.toml`.
  512. * @param text - the complete `pyproject.toml` contents.
  513. * @returns each declared requirement's distribution name, in file order.
  514. */
  515. export function parsePyprojectRequirements(text: string): string[] {
  516. return parsePyproject(text).requirements
  517. }
  518. /** Normalize a Python distribution name according to the packaging name rule. */
  519. function normalizePythonDistributionName(name: string): string {
  520. return name.toLowerCase().replace(/[-_.]+/g, '-')
  521. }
  522. /**
  523. * Resolve external Python dependencies after excluding local project names.
  524. * @param pyprojects - complete local `pyproject.toml` contents.
  525. * @param metadata - disclosure metadata for every external dependency.
  526. * @returns disclosed dependencies in normalized name order.
  527. */
  528. export function collectPythonDependencies(
  529. pyprojects: string[],
  530. metadata: PythonMetadata = PYTHON_METADATA,
  531. ): { name: string; license: string; repo: string; role: string }[] {
  532. const parsed = pyprojects.map(parsePyproject)
  533. const firstParty = new Set(parsed.flatMap(({ projectName }) => (
  534. projectName === undefined ? [] : [normalizePythonDistributionName(projectName)]
  535. )))
  536. const found = new Set(parsed
  537. .flatMap(({ requirements }) => requirements.map(normalizePythonDistributionName))
  538. .filter(name => !firstParty.has(name)))
  539. return [...found].sort((a, b) => a.localeCompare(b)).map((name) => {
  540. const entry = metadata[name]
  541. if (entry === undefined) throw new Error(`gen-third-party-notices: python dependency ${name} is missing from PYTHON_METADATA.`)
  542. return { name, ...entry }
  543. })
  544. }
  545. /** Direct Python dependencies named by the `pyproject.toml` manifests under `python/`. */
  546. function collectPython(): { name: string; license: string; repo: string; role: string }[] {
  547. const manifests = globSync('python/*/pyproject.toml', { cwd: root })
  548. if (manifests.length === 0) throw new Error('gen-third-party-notices: no python/*/pyproject.toml found; the Python tree moved.')
  549. return collectPythonDependencies(manifests.map(path => readFileSync(resolve(root, path), 'utf8')))
  550. }
  551. /** pnpm-patched external packages, from `pnpm-workspace.yaml`. */
  552. function collectPatched(): { spec: string; patch: string }[] {
  553. const workspace = yaml.load(readFileSync(resolve(root, 'pnpm-workspace.yaml'), 'utf8')) as { patchedDependencies?: Record<string, string> }
  554. return Object.entries(workspace.patchedDependencies ?? {}).map(([spec, patch]) => ({ spec, patch }))
  555. }
  556. /** Verify each build-time tool pin still appears in its owning script. */
  557. function verifyBuildTimePins(): void {
  558. for (const tool of BUILD_TIME_TOOLS) {
  559. const text = readFileSync(resolve(root, tool.pinSource), 'utf8')
  560. if (!text.includes(tool.name)) {
  561. throw new Error(`gen-third-party-notices: ${tool.pinSource} no longer references ${tool.name}; update BUILD_TIME_TOOLS.`)
  562. }
  563. }
  564. }
  565. /** SPDX identifiers this project may ship without further review. */
  566. 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'])
  567. /** Evaluate a parsed SPDX expression under the repository's license policy. */
  568. function isPermissiveSpdx(expression: ReturnType<typeof parseSpdx>): boolean {
  569. if ('conjunction' in expression) {
  570. return expression.conjunction === 'and'
  571. ? isPermissiveSpdx(expression.left) && isPermissiveSpdx(expression.right)
  572. : isPermissiveSpdx(expression.left) || isPermissiveSpdx(expression.right)
  573. }
  574. return expression.plus !== true
  575. && expression.exception === undefined
  576. && PERMISSIVE_LICENSES.has(expression.license)
  577. }
  578. /**
  579. * Whether an SPDX expression grants terms this project may ship under.
  580. * `OR` needs one permissive alternative, because the consumer chooses; `AND`
  581. * needs all of them, because every obligation applies. Anything that is not a
  582. * recognized permissive identifier — copyleft, an exception clause, or a
  583. * license this list has never seen — evaluates to false, so an unfamiliar
  584. * expression fails closed rather than passing on a partial match.
  585. * @param license - the SPDX expression from the package manifest.
  586. * @returns true when the expression's obligations are all permissive.
  587. */
  588. export function isPermissive(license: string): boolean {
  589. // Some npm manifests use a slash for a choice despite SPDX requiring `OR`.
  590. const normalized = license.replace(/\s*\/\s*/g, ' OR ').trim()
  591. try {
  592. return isPermissiveSpdx(parseSpdx(normalized))
  593. } catch {
  594. return false
  595. }
  596. }
  597. /**
  598. * Render the sentence that isolates non-permissive development tooling, or
  599. * nothing at all when every development dependency is permissive.
  600. * @param deps - development dependencies whose license is not permissive.
  601. * @returns the paragraph to place after the development table.
  602. */
  603. function renderNonPermissiveNote(deps: ExternalDep[]): string {
  604. if (deps.length === 0) return ''
  605. const named = deps.map(dep => `\`${dep.name}\` (${dep.license})`)
  606. const subject = named.length === 1 ? named[0] : `${named.slice(0, -1).join(', ')} and ${named.at(-1)}`
  607. 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`
  608. }
  609. /** Render one npm dependency table. */
  610. function renderNpmTable(deps: ExternalDep[]): string {
  611. const lines = ['| Package | License |', '| --- | --- |']
  612. for (const dep of deps) lines.push(`| [\`${dep.name}\`](${dep.repo}) | ${dep.license} |`)
  613. return lines.join('\n')
  614. }
  615. function renderClaudeDistribution(
  616. distribution: ClaudeDistribution | undefined,
  617. ): string {
  618. if (distribution === undefined) return ''
  619. const rows = distribution.payloads.map(payload =>
  620. `| [\`${payload.name}\`](https://www.npmjs.com/package/${payload.name}) | ${payload.version} | ${CLAUDE_PLATFORM_DECLARED_LICENSE} |`,
  621. )
  622. return `
  623. ## Official Claude Code platform payloads
  624. 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.
  625. 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.
  626. | Optional platform package | Version | Declared license |
  627. | --- | --- | --- |
  628. ${rows.join('\n')}
  629. `
  630. }
  631. /**
  632. * Render the complete notices document.
  633. * @returns the exact bytes `THIRD_PARTY_NOTICES.md` must hold.
  634. */
  635. export function render(): string {
  636. verifyBuildTimePins()
  637. const npm = collectNpmDeps()
  638. const runtimeDeps = npm.filter(dep => dep.runtime)
  639. const devDeps = npm.filter(dep => !dep.runtime)
  640. const vendored = collectVendored()
  641. const python = collectPython()
  642. const patched = collectPatched()
  643. const claudeDistribution = runtimeDeps.some(
  644. dep => dep.name === CLAUDE_AGENT_SDK_PACKAGE,
  645. )
  646. ? collectClaudeDistribution()
  647. : undefined
  648. const nonPermissiveDev = devDeps.filter(dep => !isPermissive(dep.license))
  649. // A copyleft license reaching a shipped surface is a distribution decision,
  650. // not a rendering detail; the notices cannot quietly absorb it.
  651. const nonPermissiveRuntime = runtimeDeps.filter(dep =>
  652. !isPermissive(dep.license)
  653. && !isOwnerAuthorizedRuntime(dep.name),
  654. )
  655. if (nonPermissiveRuntime.length > 0) {
  656. 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.`)
  657. }
  658. const patchedLines = patched.map(({ spec, patch }) => `- \`${spec}\` — [\`${patch}\`](${patch})`)
  659. return `<!-- Generated by scripts/gen-third-party-notices.ts — do not edit by hand.
  660. Run \`pnpm run gen-third-party-notices\` to regenerate. -->
  661. # Third-Party Notices
  662. 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.
  663. 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.
  664. 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).
  665. ## Vendored source (\`vendor/\`)
  666. 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).
  667. | Package | Upstream name | Upstream | License |
  668. | --- | --- | --- | --- |
  669. ${vendored.map(row => `| \`${row.npmName}\` | \`${row.upstreamName}\` | [${row.upstream.replace('https://', '')}](${row.upstream}) | MIT |`).join('\n')}
  670. ## Runtime npm dependencies
  671. 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.
  672. ${renderNpmTable(runtimeDeps)}
  673. 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:
  674. ${patchedLines.join('\n')}
  675. ${renderClaudeDistribution(claudeDistribution)}
  676. ## Development-only npm dependencies
  677. 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.
  678. ${renderNpmTable(devDeps)}
  679. ${renderNonPermissiveNote(nonPermissiveDev)}
  680. ## Python SDK dependencies (\`python/\`)
  681. Direct dependencies of the \`pyproject.toml\` manifests, plus \`uv\` as the development workflow tool.
  682. | Package | License | Role |
  683. | --- | --- | --- |
  684. ${python.map(dep => `| [\`${dep.name}\`](${dep.repo}) | ${dep.license} | ${dep.role} |`).join('\n')}
  685. | [\`uv\`](https://github.com/astral-sh/uv) | MIT / Apache-2.0 | development workflow tool |
  686. ## Fetched at build time
  687. | Package | License | Role |
  688. | --- | --- | --- |
  689. ${BUILD_TIME_TOOLS.map(tool => `| [\`${tool.name}\`](${tool.repo}) | ${tool.license} | ${tool.role} |`).join('\n')}
  690. ## First-party native packages
  691. \`@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.
  692. `
  693. }
  694. /** CLI entry: default writes the notices, `--check` fails if the committed copy
  695. * is stale. Guarded behind an entry-point check so importing this module for
  696. * tests neither regenerates the committed file nor calls process.exit. */
  697. function main(): void {
  698. const content = render()
  699. if (process.argv.includes('--check')) {
  700. let committed: string | null = null
  701. try {
  702. committed = readFileSync(resolve(root, OUT), 'utf8')
  703. } catch {
  704. // Only ENOENT (not yet generated) is expected; a present-but-unreadable
  705. // file is not a state this repo produces, and the remedy is the same.
  706. committed = null
  707. }
  708. if (committed === content) {
  709. console.log(`gen-third-party-notices: ${OUT} is up to date.`)
  710. process.exit(0)
  711. }
  712. console.error(`gen-third-party-notices: ${OUT} is stale. Run \`pnpm run gen-third-party-notices\` and commit ${OUT}.`)
  713. process.exit(1)
  714. }
  715. writeFileSync(resolve(root, OUT), content)
  716. console.log(`gen-third-party-notices: wrote ${OUT}.`)
  717. }
  718. if (process.argv[1] !== undefined && import.meta.filename === resolve(process.argv[1])) {
  719. main()
  720. }