gen-third-party-notices.ts 35 KB

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