@standardagents/code 0.14.1-issue.658.a1599e-linux-x64-gnu → 0.14.1-issue.663.d242d1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,4 @@
1
+ #!/usr/bin/env node
2
+ import { main } from '../lib/launcher.mjs'
3
+
4
+ main('standard')
@@ -0,0 +1,4 @@
1
+ #!/usr/bin/env node
2
+ import { main } from '../lib/launcher.mjs'
3
+
4
+ main('standardd')
@@ -0,0 +1,344 @@
1
+ import { createHash, createPublicKey, verify } from 'node:crypto'
2
+ import { closeSync, constants, fstatSync, lstatSync, openSync, readSync, readdirSync } from 'node:fs'
3
+ import { dirname, join } from 'node:path'
4
+ import { isPreviewBuild, normalizeBackendProfile } from './backend-profile.mjs'
5
+
6
+ export const ARTIFACT_FORMAT = 'standard-npm-native-target-v2'
7
+ export const ARTIFACT_FILES = Object.freeze([
8
+ 'bin/standard', 'bin/standardd', 'bin/tmux', 'licenses/THIRD-PARTY.txt',
9
+ ])
10
+ export const BUNDLE_ARTIFACT_FORMAT = 'standard-npm-native-target-v3'
11
+ export const BUNDLE_ARTIFACT_FILES = Object.freeze([
12
+ // Stapled notarization tickets are distinct from the code signature seals.
13
+ 'Standard Code.app/Contents/CodeResources',
14
+ 'Standard Code.app/Contents/Info.plist',
15
+ 'Standard Code.app/Contents/MacOS/standard',
16
+ 'Standard Code.app/Contents/_CodeSignature/CodeResources',
17
+ 'Standard Code Daemon.app/Contents/CodeResources',
18
+ 'Standard Code Daemon.app/Contents/Info.plist',
19
+ 'Standard Code Daemon.app/Contents/MacOS/standardd',
20
+ 'Standard Code Daemon.app/Contents/Helpers/tmux',
21
+ 'Standard Code Daemon.app/Contents/_CodeSignature/CodeResources',
22
+ ...['TMUX-ARTIFACT-MANIFEST.sha256', 'TMUX-ARTIFACT-METADATA.txt',
23
+ 'TMUX-BUILD-TOOLS.txt', 'TMUX-OTOOL-L.txt', 'TMUX-SIGNED-RUNTIME.sha256',
24
+ 'licenses/libevent.txt', 'licenses/tmux.txt',
25
+ ].map(path => `Standard Code Daemon.app/Contents/Resources/tmux/${path}`),
26
+ 'licenses/THIRD-PARTY.txt',
27
+ ])
28
+
29
+ export const RUNNER_ASSET_NAMES = Object.freeze([
30
+ 'index.mjs', 'worker.mjs', 'loader.mjs', 'sdk.mjs', 'runtime.json', 'THIRD-PARTY.txt',
31
+ ])
32
+ export const MAX_RUNNER_ASSET_BYTES = 16 * 1024 * 1024
33
+ export const RUNNER_ARTIFACT_FILES = Object.freeze([
34
+ ...ARTIFACT_FILES, ...RUNNER_ASSET_NAMES.map(name => `lib/standard-plugin-runner/${name}`),
35
+ ])
36
+ export const BUNDLE_RUNNER_ARTIFACT_FILES = Object.freeze([
37
+ ...BUNDLE_ARTIFACT_FILES,
38
+ ...RUNNER_ASSET_NAMES.map(name => `Standard Code Daemon.app/Contents/Resources/plugin-runner/${name}`),
39
+ ])
40
+
41
+ export function artifactFiles(manifest) {
42
+ const hasRunner = manifest.files?.some(file => file.path?.includes('/plugin-runner/') || file.path?.startsWith('lib/standard-plugin-runner/'))
43
+ if (manifest.schema === 2 && manifest.format === ARTIFACT_FORMAT
44
+ && manifest.target?.endsWith('-unknown-linux-gnu')) return hasRunner ? RUNNER_ARTIFACT_FILES : ARTIFACT_FILES
45
+ if (manifest.schema === 3 && manifest.format === BUNDLE_ARTIFACT_FORMAT
46
+ && manifest.target?.endsWith('-apple-darwin')) return hasRunner ? BUNDLE_RUNNER_ARTIFACT_FILES : BUNDLE_ARTIFACT_FILES
47
+ throw new Error('Native artifact identity is invalid')
48
+ }
49
+
50
+ export function artifactBinaryPath(manifest, command) {
51
+ if (!['standard', 'standardd', 'tmux'].includes(command)) throw new Error('Invalid artifact command')
52
+ artifactFiles(manifest)
53
+ if (manifest.target.endsWith('-unknown-linux-gnu')) return `bin/${command}`
54
+ if (command === 'tmux') return 'Standard Code Daemon.app/Contents/Helpers/tmux'
55
+ return `${command === 'standard' ? 'Standard Code' : 'Standard Code Daemon'}.app/Contents/MacOS/${command}`
56
+ }
57
+
58
+ export function artifactDirectories(files) {
59
+ const directories = new Set()
60
+ for (const file of files) {
61
+ for (let directory = dirname(file); directory !== '.'; directory = dirname(directory)) directories.add(directory)
62
+ }
63
+ return [...directories].sort()
64
+ }
65
+
66
+ // Bundle signatures seal resources too: reject unmanifested contents and links
67
+ // at every directory level, including links in an executable's ancestors.
68
+ export function verifyArtifactTree(root, files, metadata = ['manifest.json', 'manifest.sig', 'package.json']) {
69
+ const allowedFiles = new Set([...files, ...metadata])
70
+ const allowedDirectories = new Set(artifactDirectories(files))
71
+ function visit(relative) {
72
+ const path = join(root, relative)
73
+ if (!lstatSync(path).isDirectory()) throw new Error(`Invalid artifact directory: ${path}`)
74
+ for (const name of readdirSync(path)) {
75
+ const child = relative ? `${relative}/${name}` : name
76
+ const entry = lstatSync(join(root, child))
77
+ if (entry.isDirectory() && allowedDirectories.has(child)) visit(child)
78
+ else if (!entry.isFile() || !allowedFiles.has(child)) throw new Error(`Unexpected artifact content: ${child}`)
79
+ }
80
+ }
81
+ visit('')
82
+ for (const directory of allowedDirectories) {
83
+ if (!lstatSync(join(root, directory)).isDirectory()) throw new Error(`Invalid artifact directory: ${directory}`)
84
+ }
85
+ }
86
+
87
+ // Check a native signed archive's listing before extraction: `names` from
88
+ // `tar -tzf` and the entry type letters from `tar -tvzf`. The archive must be
89
+ // exactly one of the signed layouts, with only regular files and the
90
+ // directories those files need. Returns the matching file list.
91
+ export function nativeArchiveLayout(names, types) {
92
+ const listed = names.map(name => name.replace(/^\.\//, '')).sort()
93
+ const layout = [ARTIFACT_FILES, BUNDLE_ARTIFACT_FILES, RUNNER_ARTIFACT_FILES, BUNDLE_RUNNER_ARTIFACT_FILES].find(files => {
94
+ const expected = [...artifactDirectories(files).map(path => `${path}/`), ...files, 'manifest.json', 'manifest.sig'].sort()
95
+ return listed.join('\n') === expected.join('\n')
96
+ })
97
+ if (!layout) throw new Error('native artifact archive has unexpected paths')
98
+ const expectedTypes = '-'.repeat(layout.length + 2) + 'd'.repeat(artifactDirectories(layout).length)
99
+ if ([...types].sort().join('') !== expectedTypes) {
100
+ throw new Error('native artifact archive must contain only regular files and expected directories')
101
+ }
102
+ return layout
103
+ }
104
+
105
+ // The four native targets the launcher has ever installed. The two deferred
106
+ // ones stay so their published history verifies.
107
+ export const NATIVE_ARTIFACT_TARGETS = Object.freeze([
108
+ 'aarch64-apple-darwin', 'x86_64-apple-darwin',
109
+ 'aarch64-unknown-linux-gnu', 'x86_64-unknown-linux-gnu',
110
+ ])
111
+ // The browser viewer runtime: a fifth, distinct artifact kind that the same
112
+ // build workers compile and sign. It never installs through the launcher.
113
+ export const WEB_ARTIFACT_TARGET = 'wasm32-unknown-unknown'
114
+ export const ARTIFACT_TARGETS = Object.freeze([...NATIVE_ARTIFACT_TARGETS, WEB_ARTIFACT_TARGET])
115
+
116
+ // Web artifact (schema 4): the wasm-bindgen output, the bundled fonts, their
117
+ // licenses, and the build record, at the artifact root. The font and license
118
+ // sets vary with the pinned font list, so the manifest enumerates what the
119
+ // build produced and the verifier checks each path against these rules.
120
+ export const WEB_ARTIFACT_FORMAT = 'standard-npm-web-target-v1'
121
+ export const WEB_ARTIFACT_SCHEMA = 4
122
+ export const WEB_ARTIFACT_REQUIRED_FILES = Object.freeze([
123
+ 'build.json', 'pkg/standard_web.js', 'pkg/standard_web_bg.wasm',
124
+ ])
125
+ export const WEB_ARTIFACT_OPTIONAL_FILES = Object.freeze([
126
+ 'pkg/standard_web.d.ts', 'pkg/standard_web_bg.wasm.d.ts',
127
+ ])
128
+ // One level deep, one file kind each; at least one entry of each.
129
+ export const WEB_ARTIFACT_DIRECTORIES = Object.freeze({ fonts: /\.ttf$/, licenses: /\.txt$/ })
130
+ export const WEB_ARTIFACT_FILE_NAME = /^[A-Za-z0-9][A-Za-z0-9._-]*$/
131
+ export const MAX_WEB_ASSET_BYTES = 64 * 1024 * 1024
132
+
133
+ // Whether one artifact-relative path may appear in a web artifact.
134
+ export function webArtifactPathAllowed(path) {
135
+ if (typeof path !== 'string') return false
136
+ const parts = path.split('/')
137
+ if (!parts.every(part => WEB_ARTIFACT_FILE_NAME.test(part))) return false
138
+ if (WEB_ARTIFACT_REQUIRED_FILES.includes(path) || WEB_ARTIFACT_OPTIONAL_FILES.includes(path)) return true
139
+ return parts.length === 2 && Boolean(WEB_ARTIFACT_DIRECTORIES[parts[0]]?.test(parts[1]))
140
+ }
141
+
142
+ // Check a complete web file list: every path allowed, every required file
143
+ // present, each directory non-empty, no duplicates. Returns the sorted list.
144
+ export function webArtifactFileList(paths) {
145
+ if (!Array.isArray(paths) || paths.some(path => !webArtifactPathAllowed(path))) {
146
+ throw new Error('Web artifact file manifest is invalid')
147
+ }
148
+ const files = [...paths].sort()
149
+ if (new Set(files).size !== files.length) throw new Error('Web artifact file manifest is invalid')
150
+ const missing = WEB_ARTIFACT_REQUIRED_FILES.filter(path => !files.includes(path))
151
+ for (const directory of Object.keys(WEB_ARTIFACT_DIRECTORIES)) {
152
+ if (!files.some(path => path.startsWith(`${directory}/`))) missing.push(`${directory}/`)
153
+ }
154
+ if (missing.length) throw new Error(`Web artifact is incomplete: missing ${missing.join(', ')}`)
155
+ return files
156
+ }
157
+
158
+ // Enumerate a built web artifact root as the file list its manifest binds.
159
+ // Every entry must be a regular file the rules allow; anything else fails.
160
+ export function webArtifactFilesOnDisk(root, metadata = ['manifest.json', 'manifest.sig']) {
161
+ const files = []
162
+ function visit(relative) {
163
+ for (const name of readdirSync(join(root, relative))) {
164
+ const child = relative ? `${relative}/${name}` : name
165
+ if (!relative && metadata.includes(child)) continue
166
+ const entry = lstatSync(join(root, child))
167
+ if (entry.isDirectory() && !relative && Object.hasOwn(WEB_ARTIFACT_DIRECTORIES, child)) visit(child)
168
+ else if (entry.isDirectory() && !relative && child === 'pkg') visit(child)
169
+ else if (!entry.isFile() || !webArtifactPathAllowed(child)) throw new Error(`Unexpected artifact content: ${child}`)
170
+ else files.push(child)
171
+ }
172
+ }
173
+ visit('')
174
+ return webArtifactFileList(files)
175
+ }
176
+ // Public trust anchor, not a credential. Never obtain the verification key
177
+ // from the package being verified or a mutable registry response.
178
+ export const ARTIFACT_PUBLIC_KEY = `-----BEGIN PUBLIC KEY-----
179
+ MCowBQYDK2VwAyEAk+Ndu0WtdSgUFkraXP5CAUlQqzm+EN/My2AwkoPOMqg=
180
+ -----END PUBLIC KEY-----
181
+ `
182
+
183
+ export function validArtifactVersion(version) {
184
+ return typeof version === 'string'
185
+ && /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/.test(version)
186
+ && (version.match(/^[^-]+-(.*)$/)?.[1].split('.') ?? []).every(part => !/^0\d+$/.test(part))
187
+ }
188
+
189
+ function regularFile(path, limit) {
190
+ const descriptor = openSync(path, constants.O_RDONLY | constants.O_NOFOLLOW)
191
+ try {
192
+ const metadata = fstatSync(descriptor)
193
+ if (!metadata.isFile() || metadata.size < 1 || metadata.size > limit) throw new Error(`Invalid artifact file: ${path}`)
194
+ return { descriptor, metadata }
195
+ } catch (error) { closeSync(descriptor); throw error }
196
+ }
197
+
198
+ function boundedBytes(path, limit) {
199
+ const { descriptor } = regularFile(path, limit)
200
+ try {
201
+ const buffer = Buffer.alloc(limit + 1)
202
+ let size = 0
203
+ while (size <= limit) {
204
+ const count = readSync(descriptor, buffer, size, buffer.length - size, null)
205
+ if (!count) return buffer.subarray(0, size)
206
+ size += count
207
+ }
208
+ throw new Error(`Artifact exceeds size limit: ${path}`)
209
+ } finally { closeSync(descriptor) }
210
+ }
211
+
212
+ // Read and authenticate an artifact's manifest against the pinned key. The
213
+ // bytes that were signed are the bytes parsed; nothing is trusted before this.
214
+ function signedManifest(root, publicKey, label) {
215
+ if (!lstatSync(root).isDirectory()) throw new Error(`Invalid artifact directory: ${root}`)
216
+ const bytes = boundedBytes(join(root, 'manifest.json'), 64 * 1024)
217
+ const signature = boundedBytes(join(root, 'manifest.sig'), 256).toString('utf8').trim()
218
+ const key = createPublicKey(publicKey)
219
+ if (key.asymmetricKeyType !== 'ed25519' || !verify(null, bytes, key, Buffer.from(signature, 'base64'))) {
220
+ throw new Error(`${label} artifact signature is invalid`)
221
+ }
222
+ return JSON.parse(bytes)
223
+ }
224
+
225
+ // Every manifested file must exist with exactly its signed size and digest.
226
+ function verifyFileDigests(root, manifest, limitFor, label) {
227
+ const buffer = Buffer.alloc(1024 * 1024)
228
+ for (const file of manifest.files) {
229
+ if (!Number.isSafeInteger(file.size) || !/^[0-9a-f]{64}$/.test(file.sha256)) throw new Error(`${label} artifact file metadata is invalid`)
230
+ const path = join(root, file.path)
231
+ const { descriptor, metadata } = regularFile(path, limitFor(file.path))
232
+ try {
233
+ if (metadata.size !== file.size) throw new Error(`${label} artifact size mismatch: ${file.path}`)
234
+ const hash = createHash('sha256')
235
+ let size = 0
236
+ for (;;) {
237
+ const count = readSync(descriptor, buffer, 0, buffer.length, null)
238
+ if (!count) break
239
+ size += count
240
+ if (size > file.size) throw new Error(`${label} artifact grew while verifying: ${file.path}`)
241
+ hash.update(buffer.subarray(0, count))
242
+ }
243
+ if (size !== file.size || hash.digest('hex') !== file.sha256) throw new Error(`${label} artifact digest mismatch: ${file.path}`)
244
+ } finally { closeSync(descriptor) }
245
+ }
246
+ }
247
+
248
+ export function verifyNativeArtifact(root, expected = {}, publicKey = ARTIFACT_PUBLIC_KEY) {
249
+ const manifest = signedManifest(root, publicKey, 'Native')
250
+ const files = artifactFiles(manifest)
251
+ if (manifest.repository !== 'standardagents/code-rs'
252
+ || !NATIVE_ARTIFACT_TARGETS.includes(manifest.target)
253
+ || !/^[0-9a-f]{40}$/.test(manifest.commit)
254
+ || !validArtifactVersion(manifest.version)
255
+ || ['commit', 'version', 'target'].some(name => expected[name] != null && manifest[name] !== expected[name])
256
+ || manifest.signing?.algorithm !== 'ed25519') throw new Error('Native artifact identity is invalid')
257
+ if (Object.hasOwn(manifest, 'backendProfile') && (manifest.backendProfile == null || manifest.backendProfile === '')) {
258
+ throw new Error('Native artifact backend profile cannot be null')
259
+ }
260
+ const backendProfile = normalizeBackendProfile(manifest.backendProfile)
261
+ if (backendProfile && !isPreviewBuild(manifest.version)) {
262
+ throw new Error('Native artifact preview backend profile is not valid for this version')
263
+ }
264
+ if (!Array.isArray(manifest.files) || manifest.files.map(file => file.path).sort().join(',') !== [...files].sort().join(',')) {
265
+ throw new Error('Native artifact file manifest is invalid')
266
+ }
267
+ const runnerFiles = manifest.target.endsWith('-apple-darwin')
268
+ ? BUNDLE_RUNNER_ARTIFACT_FILES.slice(BUNDLE_ARTIFACT_FILES.length)
269
+ : RUNNER_ARTIFACT_FILES.slice(ARTIFACT_FILES.length)
270
+ if (!manifest.files.some(file => runnerFiles.includes(file.path))) {
271
+ for (const path of runnerFiles) {
272
+ try { lstatSync(join(root, path)) }
273
+ catch (error) { if (error.code === 'ENOENT') continue; throw error }
274
+ throw new Error('Native artifact contains unsigned plugin runner files')
275
+ }
276
+ }
277
+ if (manifest.schema === 3) verifyArtifactTree(root, files)
278
+ else for (const directory of artifactDirectories(files)) {
279
+ if (!lstatSync(join(root, directory)).isDirectory()) throw new Error(`Invalid artifact directory: ${directory}`)
280
+ }
281
+ const tmux = manifest.files.find(file => file.path === artifactBinaryPath(manifest, 'tmux'))
282
+ if (manifest.runtime?.tmuxVersion !== '3.7' || manifest.runtime.tmuxSha256 !== tmux.sha256) {
283
+ throw new Error('Native artifact tmux identity is invalid')
284
+ }
285
+ const protocol = manifest.runtime.accountUpdateProtocol
286
+ if (protocol != null && (!Number.isSafeInteger(protocol) || protocol < 1 || protocol > 0xffff_ffff)) {
287
+ throw new Error('Native artifact account update protocol is invalid')
288
+ }
289
+ if (manifest.target.endsWith('-apple-darwin')
290
+ && (manifest.signing.platformCodeSignature !== 'apple-developer-id'
291
+ || manifest.signing.notarization?.status !== 'Accepted'
292
+ || !/^[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}$/i.test(manifest.signing.notarization?.submissionId ?? ''))) {
293
+ throw new Error('macOS artifact lacks signed notarization acceptance')
294
+ }
295
+ if (manifest.target.endsWith('-unknown-linux-gnu')
296
+ && !/^\d+\.\d+(?:\.\d+)?$/.test(manifest.runtime.minimumGlibc ?? '')) throw new Error('Linux artifact lacks its glibc requirement')
297
+ verifyFileDigests(root, manifest, path => runnerFiles.includes(path) ? MAX_RUNNER_ASSET_BYTES : 256 * 1024 * 1024, 'Native')
298
+ return manifest
299
+ }
300
+
301
+ // Verify a web artifact root: the Ed25519 signature, the schema-4 identity,
302
+ // the file rules, the exact on-disk file set (nothing unmanifested, no
303
+ // links), the build record, and every digest. Returns the manifest.
304
+ export function verifyWebArtifact(root, expected = {}, publicKey = ARTIFACT_PUBLIC_KEY) {
305
+ const manifest = signedManifest(root, publicKey, 'Web')
306
+ if (manifest.schema !== WEB_ARTIFACT_SCHEMA || manifest.format !== WEB_ARTIFACT_FORMAT
307
+ || manifest.target !== WEB_ARTIFACT_TARGET
308
+ || manifest.repository !== 'standardagents/code-rs'
309
+ || !/^[0-9a-f]{40}$/.test(manifest.commit)
310
+ || !validArtifactVersion(manifest.version)
311
+ || ['commit', 'version', 'target'].some(name => expected[name] != null && manifest[name] !== expected[name])
312
+ || manifest.signing?.algorithm !== 'ed25519') throw new Error('Web artifact identity is invalid')
313
+ if (Object.hasOwn(manifest, 'backendProfile') && (manifest.backendProfile == null || manifest.backendProfile === '')) {
314
+ throw new Error('Web artifact backend profile cannot be null')
315
+ }
316
+ const backendProfile = normalizeBackendProfile(manifest.backendProfile)
317
+ if (backendProfile && !isPreviewBuild(manifest.version)) {
318
+ throw new Error('Web artifact preview backend profile is not valid for this version')
319
+ }
320
+ if (!Array.isArray(manifest.files)) throw new Error('Web artifact file manifest is invalid')
321
+ const files = webArtifactFileList(manifest.files.map(file => file?.path))
322
+ verifyArtifactTree(root, files)
323
+ verifyFileDigests(root, manifest, () => MAX_WEB_ASSET_BYTES, 'Web')
324
+ // The build record is the identity the bundle itself reports; it must name
325
+ // the signed build, not a local or foreign one.
326
+ let record
327
+ try { record = JSON.parse(boundedBytes(join(root, 'build.json'), 4096)) } catch { record = null }
328
+ if (record?.schema !== 1 || record.commit !== manifest.commit || record.version !== manifest.version) {
329
+ throw new Error('Web artifact build record does not name the signed build')
330
+ }
331
+ return manifest
332
+ }
333
+
334
+ export function requireCompatibleGlibc(manifest, runtimeVersion) {
335
+ if (!manifest.target.endsWith('-unknown-linux-gnu')) return
336
+ const minimum = manifest.runtime.minimumGlibc
337
+ if (!/^\d+\.\d+(?:\.\d+)?$/.test(runtimeVersion ?? '')) throw new Error('Cannot determine this machine’s glibc version')
338
+ const actual = runtimeVersion.split('.').map(Number)
339
+ const required = minimum.split('.').map(Number)
340
+ for (let index = 0; index < 3; index++) {
341
+ if ((actual[index] ?? 0) > (required[index] ?? 0)) return
342
+ if ((actual[index] ?? 0) < (required[index] ?? 0)) throw new Error(`This Standard build requires glibc ${minimum}; this machine has ${runtimeVersion}`)
343
+ }
344
+ }
@@ -0,0 +1,114 @@
1
+ const PROFILE_KEYS = ['schema', 'id', 'label', 'apiOrigin', 'relayEnvironment']
2
+ const PROFILE_ID = /^[a-z0-9][a-z0-9-]{0,47}$/
3
+ const DNS_LABEL = /^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/
4
+ const PROFILE_HOST_SUFFIXES = ['.standardcode.ai', '.standardagentbuilder.com']
5
+
6
+ export const BACKEND_PROFILE_SCHEMA = 1
7
+
8
+ export function isPreviewBuild(version) {
9
+ return typeof version === 'string' && /-(?:issue|branch)\./.test(version)
10
+ }
11
+
12
+ /**
13
+ * Validate and normalize the preview backend profile embedded in a native
14
+ * artifact. Production is represented by an absent or null profile.
15
+ */
16
+ export function normalizeBackendProfile(value) {
17
+ if (value == null || value === '') return null
18
+ if (!isPlainObject(value)) throw new Error('backend profile must be an object')
19
+ const keys = Object.keys(value).sort()
20
+ if (keys.join(',') !== [...PROFILE_KEYS].sort().join(',')) {
21
+ throw new Error('backend profile has unexpected fields')
22
+ }
23
+ if (value.schema !== BACKEND_PROFILE_SCHEMA) throw new Error('backend profile schema is unsupported')
24
+ if (typeof value.id !== 'string' || !PROFILE_ID.test(value.id) || value.id === 'production') {
25
+ throw new Error('backend profile id is invalid')
26
+ }
27
+ if (typeof value.label !== 'string' || !/^[\x20-\x7e]{1,64}$/.test(value.label)) {
28
+ throw new Error('backend profile label must be printable ASCII up to 64 characters')
29
+ }
30
+ const apiOrigin = canonicalApiOrigin(value.apiOrigin)
31
+ if (apiOrigin === 'https://api.standardcode.ai') {
32
+ throw new Error('preview backend profile cannot use the production API origin')
33
+ }
34
+ if (!['staging', 'production'].includes(value.relayEnvironment)) {
35
+ throw new Error('backend profile relayEnvironment must be staging or production')
36
+ }
37
+ return {
38
+ schema: BACKEND_PROFILE_SCHEMA,
39
+ id: value.id,
40
+ label: value.label,
41
+ apiOrigin,
42
+ relayEnvironment: value.relayEnvironment,
43
+ }
44
+ }
45
+
46
+ export function serializeBackendProfile(value) {
47
+ const profile = normalizeBackendProfile(value)
48
+ return profile ? JSON.stringify(profile) : ''
49
+ }
50
+
51
+ export function backendProfilesEqual(left, right) {
52
+ const a = normalizeBackendProfile(left)
53
+ const b = normalizeBackendProfile(right)
54
+ return JSON.stringify(a) === JSON.stringify(b)
55
+ }
56
+
57
+ export function backendProfileIdentitiesEqual(left, right) {
58
+ const a = normalizeBackendProfile(left)
59
+ const b = normalizeBackendProfile(right)
60
+ return (a?.id ?? 'production') === (b?.id ?? 'production')
61
+ && (a?.apiOrigin ?? 'https://api.standardcode.ai') === (b?.apiOrigin ?? 'https://api.standardcode.ai')
62
+ && (a?.relayEnvironment ?? 'production') === (b?.relayEnvironment ?? 'production')
63
+ }
64
+
65
+ export async function backendProfileFingerprint(value) {
66
+ const profile = normalizeBackendProfile(value)
67
+ const id = profile?.id ?? 'production'
68
+ const apiOrigin = profile?.apiOrigin ?? 'https://api.standardcode.ai'
69
+ const relayEnvironment = profile?.relayEnvironment ?? 'production'
70
+ const bytes = new TextEncoder().encode(
71
+ `standard-backend-v1\0${id}\0${apiOrigin}\0${relayEnvironment}`,
72
+ )
73
+ const digest = await crypto.subtle.digest('SHA-256', bytes)
74
+ return Array.from(new Uint8Array(digest), byte => byte.toString(16).padStart(2, '0')).join('')
75
+ }
76
+
77
+ /** A preview backend has a separate follow channel on the same Git branch. */
78
+ export async function backendProfileTag(baseTag, value) {
79
+ const profile = normalizeBackendProfile(value)
80
+ if (!profile) return baseTag
81
+ if (!/^(?:branch-|issue-)[a-z0-9-]+$/.test(baseTag)) {
82
+ throw new Error('preview backend profiles require a branch channel')
83
+ }
84
+ const tag = `${baseTag}-b-${(await backendProfileFingerprint(profile)).slice(0, 16)}`
85
+ if (tag.length > 64) throw new Error('backend-specific channel exceeds the tag length limit')
86
+ return tag
87
+ }
88
+
89
+ export function canonicalApiOrigin(value) {
90
+ if (typeof value !== 'string' || !value || value.trim() !== value) {
91
+ throw new Error('backend profile apiOrigin must be a canonical HTTPS origin')
92
+ }
93
+ let url
94
+ try { url = new URL(value) } catch { throw new Error('backend profile apiOrigin must be a canonical HTTPS origin') }
95
+ if (url.protocol !== 'https:' || url.username || url.password || url.port
96
+ || !['', '/'].includes(url.pathname) || url.search || url.hash
97
+ || value !== url.origin) {
98
+ throw new Error('backend profile apiOrigin must be a canonical HTTPS origin')
99
+ }
100
+ const hostname = url.hostname
101
+ if (!hostname || hostname.length > 253 || hostname !== hostname.toLowerCase()) {
102
+ throw new Error('backend profile apiOrigin hostname is invalid')
103
+ }
104
+ const labels = hostname.split('.')
105
+ if (labels.some(label => !DNS_LABEL.test(label))
106
+ || !PROFILE_HOST_SUFFIXES.some(suffix => hostname.endsWith(suffix))) {
107
+ throw new Error('backend profile apiOrigin hostname is not a supported first-party host')
108
+ }
109
+ return url.origin
110
+ }
111
+
112
+ function isPlainObject(value) {
113
+ return value !== null && typeof value === 'object' && !Array.isArray(value)
114
+ }
@@ -0,0 +1,93 @@
1
+ import { spawnSync } from 'node:child_process'
2
+ import { createHash, randomUUID } from 'node:crypto'
3
+ import { chmodSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs'
4
+ import { join } from 'node:path'
5
+ import { fileURLToPath } from 'node:url'
6
+
7
+ import { artifactBinaryPath, nativeArchiveLayout, verifyNativeArtifact } from './artifact.mjs'
8
+
9
+ // A release's root package names each native target's signed archive in
10
+ // `standardArtifacts`; npm only selects the platform. The archive downloads
11
+ // from the build coordinator, which serves it from R2, and installs under this
12
+ // package's `native/<target>/` once its size, digest, layout, and signed
13
+ // manifest all check out. The daemon's launcher repair finds it there too.
14
+ export const ARTIFACT_ORIGIN = 'https://builds.standardcode.ai'
15
+ const MAX_ARCHIVE = 128 * 1024 * 1024
16
+ const PACKAGE_ROOT = fileURLToPath(new URL('..', import.meta.url))
17
+
18
+ export function nativeDirectory(target, root = PACKAGE_ROOT) {
19
+ return join(root, 'native', target)
20
+ }
21
+
22
+ export function packageMetadata(root = PACKAGE_ROOT) {
23
+ return JSON.parse(readFileSync(join(root, 'package.json'), 'utf8'))
24
+ }
25
+
26
+ // The signed archive a package names for `target`, or null when its binaries
27
+ // install as an npm platform package instead.
28
+ export function artifactPointer(metadata, target) {
29
+ const artifacts = metadata.standardArtifacts
30
+ if (artifacts === undefined) return null
31
+ const pointer = artifacts?.schema === 1 ? artifacts.targets?.[target] : undefined
32
+ if (!pointer
33
+ || pointer.url !== `${ARTIFACT_ORIGIN}/artifacts/${metadata.version}/${target}.tar.gz`
34
+ || !/^[0-9a-f]{64}$/.test(pointer.sha256 ?? '')
35
+ || !Number.isSafeInteger(pointer.size) || pointer.size < 1 || pointer.size > MAX_ARCHIVE) {
36
+ throw new Error(`This package names no valid native archive for ${target}`)
37
+ }
38
+ return pointer
39
+ }
40
+
41
+ // The installed, verified artifact directory for `target`, or null.
42
+ export function installedArtifact(target, root = PACKAGE_ROOT, publicKey = undefined) {
43
+ const directory = nativeDirectory(target, root)
44
+ try {
45
+ return { directory, manifest: verifyNativeArtifact(directory, { version: packageMetadata(root).version, target }, publicKey) }
46
+ } catch {
47
+ return null
48
+ }
49
+ }
50
+
51
+ function tar(run, args) {
52
+ const result = run('tar', args, { encoding: 'utf8', maxBuffer: 16 * 1024 * 1024 })
53
+ if (result.error) throw result.error
54
+ if (result.status !== 0) throw new Error(`tar ${args[0]} failed: ${result.stderr}`)
55
+ return result.stdout
56
+ }
57
+
58
+ export async function installNativeArtifact({ target, root = PACKAGE_ROOT, fetchImplementation = fetch, run = spawnSync, publicKey = undefined }) {
59
+ const installed = installedArtifact(target, root, publicKey)
60
+ if (installed) return installed.directory
61
+ const metadata = packageMetadata(root)
62
+ const pointer = artifactPointer(metadata, target)
63
+ if (!pointer) throw new Error(`This package carries no native archive for ${target}`)
64
+ const response = await fetchImplementation(pointer.url)
65
+ if (!response.ok) throw new Error(`Downloading the native archive failed with HTTP ${response.status}`)
66
+ const bytes = Buffer.from(await response.arrayBuffer())
67
+ if (bytes.length !== pointer.size || createHash('sha256').update(bytes).digest('hex') !== pointer.sha256) {
68
+ throw new Error('The downloaded native archive does not match its published size and digest')
69
+ }
70
+ const work = join(root, 'native', `.install-${randomUUID()}`)
71
+ mkdirSync(work, { recursive: true, mode: 0o700 })
72
+ try {
73
+ const archive = join(work, 'archive.tar.gz')
74
+ writeFileSync(archive, bytes, { mode: 0o600, flag: 'wx' })
75
+ nativeArchiveLayout(
76
+ tar(run, ['-tzf', archive]).trim().split('\n'),
77
+ tar(run, ['-tvzf', archive]).trim().split('\n').map(line => line[0]),
78
+ )
79
+ const extracted = join(work, 'artifact')
80
+ mkdirSync(extracted, { mode: 0o700 })
81
+ tar(run, ['-xzf', archive, '-C', extracted])
82
+ const manifest = verifyNativeArtifact(extracted, { version: metadata.version, target }, publicKey)
83
+ for (const command of ['standard', 'standardd', 'tmux']) {
84
+ chmodSync(join(extracted, artifactBinaryPath(manifest, command)), 0o755)
85
+ }
86
+ const destination = nativeDirectory(target, root)
87
+ rmSync(destination, { recursive: true, force: true })
88
+ renameSync(extracted, destination)
89
+ return destination
90
+ } finally {
91
+ rmSync(work, { recursive: true, force: true })
92
+ }
93
+ }
@@ -0,0 +1,102 @@
1
+ import { spawnSync } from 'node:child_process'
2
+ import { readFileSync, realpathSync, statSync } from 'node:fs'
3
+ import { createRequire } from 'node:module'
4
+ import { dirname, join } from 'node:path'
5
+ import process from 'node:process'
6
+
7
+ import { platformPackage } from './platform.mjs'
8
+ import { artifactBinaryPath, requireCompatibleGlibc, verifyNativeArtifact } from './artifact.mjs'
9
+ import { artifactPointer, installNativeArtifact, installedArtifact, packageMetadata } from './install.mjs'
10
+
11
+ const require = createRequire(import.meta.url)
12
+ const COMMANDS = new Set(['standard', 'standardd'])
13
+
14
+ export function resolveBinary(command, options = {}) {
15
+ if (!COMMANDS.has(command)) {
16
+ throw new Error(`Unknown Standard executable: ${command}`)
17
+ }
18
+ const environment = options.environment ?? process.env
19
+ const overrideDirectory = environment.STANDARD_CODE_BINARY_DIR
20
+ const binaryPath = overrideDirectory
21
+ ? join(overrideDirectory, command)
22
+ : resolvePackagedBinary(command, options)
23
+ const stat = statSync(binaryPath)
24
+ if (!stat.isFile()) {
25
+ throw new Error(`Resolved Standard executable is not a file: ${binaryPath}`)
26
+ }
27
+ return binaryPath
28
+ }
29
+
30
+ function resolvePackagedBinary(command, options) {
31
+ const platform = platformPackage(
32
+ options.platform,
33
+ options.architecture,
34
+ options.report,
35
+ )
36
+ const resolve = options.resolve ?? require.resolve
37
+ const report = options.report ?? process.report
38
+ // A release that carries no binaries on npm installs its signed R2 archive
39
+ // under this package instead (see install.mjs).
40
+ const downloaded = installedArtifact(platform.rustTarget, options.packageRoot)
41
+ if (downloaded) {
42
+ requireCompatibleGlibc(downloaded.manifest, report?.getReport()?.header?.glibcVersionRuntime)
43
+ return join(downloaded.directory, artifactBinaryPath(downloaded.manifest, command))
44
+ }
45
+ try {
46
+ const root = dirname(realpathSync(resolve(`${platform.packageName}/manifest.json`)))
47
+ const version = JSON.parse(readFileSync(new URL('../package.json', import.meta.url))).version
48
+ const artifact = verifyNativeArtifact(root, { version, target: platform.rustTarget })
49
+ requireCompatibleGlibc(artifact, report?.getReport()?.header?.glibcVersionRuntime)
50
+ return join(root, artifactBinaryPath(artifact, command))
51
+ } catch (error) {
52
+ const detail = error instanceof Error ? error.message : String(error)
53
+ throw new Error(
54
+ `The native package ${platform.packageName} is missing or incomplete. `
55
+ + `Reinstall @standardagents/code for this platform. (${detail})`,
56
+ )
57
+ }
58
+ }
59
+
60
+ export function spawnBinary(command, args, options = {}) {
61
+ const binary = resolveBinary(command, options)
62
+ return spawnSync(binary, args, {
63
+ stdio: options.stdio ?? 'inherit',
64
+ env: options.environment ?? process.env,
65
+ })
66
+ }
67
+
68
+ // Install this platform's signed R2 archive when the package names one and
69
+ // has no binaries installed yet. Package managers that skip install scripts
70
+ // (pnpm by default) reach this on the first launch instead of postinstall.
71
+ export async function ensureNativeBinaries(options = {}) {
72
+ if (options.environment?.STANDARD_CODE_BINARY_DIR ?? process.env.STANDARD_CODE_BINARY_DIR) return
73
+ const platform = platformPackage(options.platform, options.architecture, options.report)
74
+ if (installedArtifact(platform.rustTarget, options.packageRoot)) return
75
+ if (!artifactPointer(packageMetadata(options.packageRoot), platform.rustTarget)) return
76
+ try {
77
+ const resolve = options.resolve ?? require.resolve
78
+ resolve(`${platform.packageName}/manifest.json`)
79
+ return
80
+ } catch {
81
+ // No npm platform package: download the archive.
82
+ }
83
+ await installNativeArtifact({ target: platform.rustTarget, root: options.packageRoot, fetchImplementation: options.fetchImplementation })
84
+ }
85
+
86
+ export async function main(command) {
87
+ try {
88
+ await ensureNativeBinaries()
89
+ const result = spawnBinary(command, process.argv.slice(2))
90
+ if (result.error) throw result.error
91
+ if (result.signal) {
92
+ console.error(`${command} terminated by ${result.signal}`)
93
+ process.exitCode = 1
94
+ return
95
+ }
96
+ process.exitCode = result.status ?? 1
97
+ } catch (error) {
98
+ const detail = error instanceof Error ? error.message : String(error)
99
+ console.error(`${command}: ${detail}`)
100
+ process.exitCode = 1
101
+ }
102
+ }