@dsh-ray/assistant-verifier 0.0.0-stage → 0.2.0

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.
Files changed (113) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +286 -2
  3. package/cordis.patch.yml +10 -0
  4. package/lib/config.d.ts +47 -0
  5. package/lib/config.d.ts.map +1 -0
  6. package/lib/config.js +82 -0
  7. package/lib/config.js.map +1 -0
  8. package/lib/creation-review-native.d.ts +30 -0
  9. package/lib/creation-review-native.d.ts.map +1 -0
  10. package/lib/creation-review-native.js +137 -0
  11. package/lib/creation-review-native.js.map +1 -0
  12. package/lib/creation-review-store.d.ts +108 -0
  13. package/lib/creation-review-store.d.ts.map +1 -0
  14. package/lib/creation-review-store.js +715 -0
  15. package/lib/creation-review-store.js.map +1 -0
  16. package/lib/creation-review.d.ts +317 -0
  17. package/lib/creation-review.d.ts.map +1 -0
  18. package/lib/creation-review.js +842 -0
  19. package/lib/creation-review.js.map +1 -0
  20. package/lib/drivers.d.ts +153 -0
  21. package/lib/drivers.d.ts.map +1 -0
  22. package/lib/drivers.js +825 -0
  23. package/lib/drivers.js.map +1 -0
  24. package/lib/host.d.ts +93 -0
  25. package/lib/host.d.ts.map +1 -0
  26. package/lib/host.js +2 -0
  27. package/lib/host.js.map +1 -0
  28. package/lib/index.d.ts +26 -0
  29. package/lib/index.d.ts.map +1 -0
  30. package/lib/index.js +18 -0
  31. package/lib/index.js.map +1 -0
  32. package/lib/linux-behavior-assets.d.ts +17 -0
  33. package/lib/linux-behavior-assets.d.ts.map +1 -0
  34. package/lib/linux-behavior-assets.js +73 -0
  35. package/lib/linux-behavior-assets.js.map +1 -0
  36. package/lib/linux-behavior-runner.d.ts +10 -0
  37. package/lib/linux-behavior-runner.d.ts.map +1 -0
  38. package/lib/linux-behavior-runner.js +69 -0
  39. package/lib/linux-behavior-runner.js.map +1 -0
  40. package/lib/linux-behavior-runtime.d.ts +67 -0
  41. package/lib/linux-behavior-runtime.d.ts.map +1 -0
  42. package/lib/linux-behavior-runtime.js +500 -0
  43. package/lib/linux-behavior-runtime.js.map +1 -0
  44. package/lib/memory-review-native.d.ts +50 -0
  45. package/lib/memory-review-native.d.ts.map +1 -0
  46. package/lib/memory-review-native.js +166 -0
  47. package/lib/memory-review-native.js.map +1 -0
  48. package/lib/memory-review.d.ts +50 -0
  49. package/lib/memory-review.d.ts.map +1 -0
  50. package/lib/memory-review.js +363 -0
  51. package/lib/memory-review.js.map +1 -0
  52. package/lib/native-behavior-artifact.d.ts +9 -0
  53. package/lib/native-behavior-artifact.d.ts.map +1 -0
  54. package/lib/native-behavior-artifact.js +144 -0
  55. package/lib/native-behavior-artifact.js.map +1 -0
  56. package/lib/native-behavior-worker.d.ts +3 -0
  57. package/lib/native-behavior-worker.d.ts.map +1 -0
  58. package/lib/native-behavior-worker.js +453 -0
  59. package/lib/native-behavior-worker.js.map +1 -0
  60. package/lib/plugin-behavior-config.d.ts +34 -0
  61. package/lib/plugin-behavior-config.d.ts.map +1 -0
  62. package/lib/plugin-behavior-config.js +170 -0
  63. package/lib/plugin-behavior-config.js.map +1 -0
  64. package/lib/plugin-behavior-runner.d.ts +57 -0
  65. package/lib/plugin-behavior-runner.d.ts.map +1 -0
  66. package/lib/plugin-behavior-runner.js +910 -0
  67. package/lib/plugin-behavior-runner.js.map +1 -0
  68. package/lib/review-authority-lineage.d.ts +109 -0
  69. package/lib/review-authority-lineage.d.ts.map +1 -0
  70. package/lib/review-authority-lineage.js +135 -0
  71. package/lib/review-authority-lineage.js.map +1 -0
  72. package/lib/review-maintenance.d.ts +20 -0
  73. package/lib/review-maintenance.d.ts.map +1 -0
  74. package/lib/review-maintenance.js +24 -0
  75. package/lib/review-maintenance.js.map +1 -0
  76. package/lib/revision-regression-review.d.ts +41 -0
  77. package/lib/revision-regression-review.d.ts.map +1 -0
  78. package/lib/revision-regression-review.js +379 -0
  79. package/lib/revision-regression-review.js.map +1 -0
  80. package/lib/revision-review.d.ts +242 -0
  81. package/lib/revision-review.d.ts.map +1 -0
  82. package/lib/revision-review.js +600 -0
  83. package/lib/revision-review.js.map +1 -0
  84. package/lib/service.d.ts +138 -0
  85. package/lib/service.d.ts.map +1 -0
  86. package/lib/service.js +878 -0
  87. package/lib/service.js.map +1 -0
  88. package/lib/source-review-git.d.ts +32 -0
  89. package/lib/source-review-git.d.ts.map +1 -0
  90. package/lib/source-review-git.js +241 -0
  91. package/lib/source-review-git.js.map +1 -0
  92. package/lib/source-review-native.d.ts +27 -0
  93. package/lib/source-review-native.d.ts.map +1 -0
  94. package/lib/source-review-native.js +149 -0
  95. package/lib/source-review-native.js.map +1 -0
  96. package/lib/source-review-store.d.ts +44 -0
  97. package/lib/source-review-store.d.ts.map +1 -0
  98. package/lib/source-review-store.js +212 -0
  99. package/lib/source-review-store.js.map +1 -0
  100. package/lib/source-review.d.ts +86 -0
  101. package/lib/source-review.d.ts.map +1 -0
  102. package/lib/source-review.js +255 -0
  103. package/lib/source-review.js.map +1 -0
  104. package/lib/store.d.ts +84 -0
  105. package/lib/store.d.ts.map +1 -0
  106. package/lib/store.js +386 -0
  107. package/lib/store.js.map +1 -0
  108. package/lib/version.d.ts +2 -0
  109. package/lib/version.d.ts.map +1 -0
  110. package/lib/version.js +2 -0
  111. package/lib/version.js.map +1 -0
  112. package/package.json +144 -3
  113. package/runtime/plugin-observer-launcher.c +246 -0
@@ -0,0 +1,910 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { NativeMacVerifierRunner } from '@dsh-ray/assistant-isolation';
3
+ import { behaviorNativeRuntimeDigest, NATIVE_BEHAVIOR_BOUNDARY, LINUX_BEHAVIOR_BOUNDARY, validatePluginBehaviorRunnerConfig } from './plugin-behavior-config.js';
4
+ export { NATIVE_BEHAVIOR_BOUNDARY, LINUX_BEHAVIOR_BOUNDARY, validatePluginBehaviorRunnerConfig, validatePluginBehaviorDeploymentConfig } from './plugin-behavior-config.js';
5
+ export { LINUX_BEHAVIOR_COMMAND, validateLinuxPluginBehaviorRuntime, verifyLinuxPluginBehaviorRuntime, linuxPluginBehaviorRuntimeDigest, prepareLinuxPluginBehaviorRuntime, readLinuxPluginBehaviorRuntime } from './linux-behavior-runtime.js';
6
+ import { linuxPluginBehaviorRuntimeDigest } from './linux-behavior-runtime.js';
7
+ import { LinuxBehaviorRunner } from './linux-behavior-runner.js';
8
+ import { nativeBehaviorFiles } from './native-behavior-artifact.js';
9
+ import { NATIVE_BEHAVIOR_SOURCE } from './native-behavior-worker.js';
10
+ const MAX_PACK_BYTES = 512 * 1024;
11
+ const MAX_OPERATION_BYTES = 64 * 1024;
12
+ const MAX_WORKER_OUTPUT_BYTES = 64 * 1024;
13
+ const SHA256 = /^[a-f0-9]{64}$/u;
14
+ const SAFE_ID = /^[A-Za-z0-9][A-Za-z0-9_.:-]{0,95}$/u;
15
+ const SAFE_TOOL = /^[a-z][a-z0-9_-]{0,95}$/u;
16
+ const BOUNDARY = 'process-seccomp-v1';
17
+ const PLUGIN_KINDS = new Set(['tool', 'service', 'channel', 'ui']);
18
+ export const isPluginKind = (value) => typeof value === 'string' && PLUGIN_KINDS.has(value);
19
+ function canonicalJson(value) {
20
+ try {
21
+ if (!deepJson(value))
22
+ return undefined;
23
+ const serialized = JSON.stringify(value);
24
+ return serialized === undefined ? undefined : serialized;
25
+ }
26
+ catch {
27
+ return undefined;
28
+ }
29
+ }
30
+ function deepJson(value, seen = new Set()) {
31
+ if (value === null || typeof value === 'string' || typeof value === 'boolean')
32
+ return true;
33
+ if (typeof value === 'number')
34
+ return Number.isFinite(value);
35
+ if (typeof value !== 'object' || seen.has(value))
36
+ return false;
37
+ seen.add(value);
38
+ if (Array.isArray(value)) {
39
+ const valid = value.every(item => deepJson(item, seen));
40
+ seen.delete(value);
41
+ return valid;
42
+ }
43
+ if (Object.getPrototypeOf(value) !== Object.prototype)
44
+ return false;
45
+ const valid = Object.keys(value).every(key => {
46
+ const descriptor = Object.getOwnPropertyDescriptor(value, key);
47
+ return descriptor !== undefined && Object.hasOwn(descriptor, 'value') && deepJson(descriptor.value, seen);
48
+ });
49
+ seen.delete(value);
50
+ return valid;
51
+ }
52
+ function validOperation(value) {
53
+ if (value === null || typeof value !== 'object' || Array.isArray(value))
54
+ return false;
55
+ const operation = value;
56
+ if (operation.kind === 'discover')
57
+ return Object.keys(operation).length === 1;
58
+ if (operation.kind !== 'invoke' || typeof operation.schemaDigest !== 'string' || !SHA256.test(operation.schemaDigest)
59
+ || !Array.isArray(operation.calls) || operation.calls.length < 1 || operation.calls.length > 8
60
+ || Object.keys(operation).length !== 3)
61
+ return false;
62
+ const ids = new Set();
63
+ for (const call of operation.calls) {
64
+ if (!call || typeof call !== 'object' || Object.keys(call).length !== 3
65
+ || !SAFE_ID.test(call.id) || !SAFE_TOOL.test(call.toolName) || ids.has(call.id) || !deepJson(call.arguments))
66
+ return false;
67
+ ids.add(call.id);
68
+ }
69
+ return true;
70
+ }
71
+ function validObservation(value, operation, sha256, requestedKind) {
72
+ if (value === null || typeof value !== 'object' || Array.isArray(value))
73
+ return false;
74
+ const record = value;
75
+ if (Object.hasOwn(record, 'pluginKind')) {
76
+ if (!isPluginKind(record.pluginKind))
77
+ return false;
78
+ if (requestedKind !== undefined && record.pluginKind !== requestedKind)
79
+ return false;
80
+ }
81
+ else if (requestedKind !== undefined) {
82
+ return false;
83
+ }
84
+ if (record.schemaVersion !== 2 || record.boundary !== BOUNDARY || record.status !== 'observed' || record.artifactSha256 !== sha256
85
+ || record.quiescent !== true || !SHA256.test(record.schemaDigest)
86
+ || !record.environment || typeof record.environment !== 'object')
87
+ return false;
88
+ const environment = record.environment;
89
+ if (['node', 'cordis', 'tools', 'systemPrompt'].some(key => typeof environment[key] !== 'string'
90
+ || environment[key].length > 80))
91
+ return false;
92
+ if (operation.kind === 'discover') {
93
+ if (!Array.isArray(record.schemas) || record.schemas.length < 1 || record.schemas.length > 64 || record.calls !== undefined)
94
+ return false;
95
+ if (createHash('sha256').update(JSON.stringify(record.schemas)).digest('hex') !== record.schemaDigest)
96
+ return false;
97
+ const names = new Set();
98
+ for (const schema of record.schemas) {
99
+ if (!schema || typeof schema !== 'object' || !SAFE_TOOL.test(schema.name ?? '')
100
+ || names.has(schema.name))
101
+ return false;
102
+ names.add(schema.name);
103
+ }
104
+ }
105
+ else if (!Array.isArray(record.calls) || record.calls.length !== operation.calls.length
106
+ || record.schemaDigest !== operation.schemaDigest || record.schemas !== undefined
107
+ || record.calls.some((call, index) => !call || typeof call !== 'object'
108
+ || call.id !== operation.calls[index].id
109
+ || call.toolName !== operation.calls[index].toolName
110
+ || !Object.hasOwn(call, 'result')))
111
+ return false;
112
+ return true;
113
+ }
114
+ function validLinuxFrame(value, operation, expected) {
115
+ const fields = ['schemaVersion', 'boundary', 'status', 'artifactSha256', 'quiescent', 'environment', 'schemaDigest',
116
+ operation.kind === 'discover' ? 'schemas' : 'calls',
117
+ ...(Object.hasOwn(value, 'pluginKind') ? ['pluginKind'] : [])];
118
+ const environment = value.environment;
119
+ return Object.keys(value).length === fields.length && fields.every(key => Object.hasOwn(value, key))
120
+ && Object.keys(environment).length === 4
121
+ && Object.entries(expected).every(([key, version]) => environment[key] === version)
122
+ && (operation.kind === 'discover' || value.calls.every(call => !Array.isArray(call) && Object.keys(call).length === 3));
123
+ }
124
+ /** Host-only behavior observation. The candidate and worker receive no oracle or promotion authority. */
125
+ export class PluginBehaviorRunner {
126
+ #runner;
127
+ #native;
128
+ #linux;
129
+ #runtimeDigest;
130
+ #authorityDigest;
131
+ #environment;
132
+ #modulesPath;
133
+ constructor(input) {
134
+ const config = validatePluginBehaviorRunnerConfig(input);
135
+ this.#authorityDigest = config.authorityDigest;
136
+ this.#native = 'backend' in config && config.backend === 'macos-seatbelt';
137
+ this.#linux = 'backend' in config && config.backend === 'linux-native';
138
+ if ('backend' in config && config.backend === 'linux-native') {
139
+ const versions = config.runtime.runtime.versions;
140
+ this.#runtimeDigest = linuxPluginBehaviorRuntimeDigest(config.runtime);
141
+ this.#environment = { node: versions.node, cordis: versions.cordis, tools: versions.tools, systemPrompt: versions.systemPrompt };
142
+ this.#runner = new LinuxBehaviorRunner(config);
143
+ }
144
+ else if (this.#native) {
145
+ const native = config;
146
+ this.#runtimeDigest = behaviorNativeRuntimeDigest(native.runtime);
147
+ this.#environment = { node: native.runtime.versions.node, cordis: native.runtime.versions.cordis,
148
+ tools: native.runtime.versions.tools, systemPrompt: native.runtime.versions.systemPrompt };
149
+ this.#modulesPath = native.runtime.modulesPath;
150
+ this.#runner = new NativeMacVerifierRunner({ ...native, source: NATIVE_BEHAVIOR_SOURCE });
151
+ }
152
+ else
153
+ throw new Error('plugin behavior runner requires a native backend');
154
+ }
155
+ async run(input) {
156
+ const artifactSha256 = Buffer.isBuffer(input.artifact)
157
+ ? createHash('sha256').update(input.artifact).digest('hex') : '';
158
+ const unknown = (reason, quiescent = false, jobId) => ({ status: 'unknown', quiescent, artifactSha256, reason, ...(jobId ? { jobId } : {}) });
159
+ if (!Buffer.isBuffer(input.artifact) || input.artifact.length < 1 || input.artifact.length > MAX_PACK_BYTES)
160
+ return unknown('plugin-artifact-out-of-bound', true);
161
+ if (input.pluginKind !== undefined && !isPluginKind(input.pluginKind))
162
+ return unknown('plugin-operation-invalid', true);
163
+ let operation;
164
+ try {
165
+ const serialized = canonicalJson(input.operation);
166
+ const snapshot = serialized === undefined ? undefined : JSON.parse(serialized);
167
+ if (!validOperation(snapshot))
168
+ return unknown('plugin-operation-invalid', true);
169
+ operation = snapshot;
170
+ }
171
+ catch {
172
+ return unknown('plugin-operation-invalid', true);
173
+ }
174
+ let staged;
175
+ if (this.#native) {
176
+ try {
177
+ staged = nativeBehaviorFiles(input.artifact);
178
+ }
179
+ catch {
180
+ return unknown('plugin-artifact-invalid', true);
181
+ }
182
+ }
183
+ // Stable per frozen request: the durable runner must see identical bytes for a replay key.
184
+ // This is only frame correlation. Single-process candidate output is untrusted.
185
+ const kindField = input.pluginKind !== undefined ? { pluginKind: input.pluginKind } : {};
186
+ const nonce = this.#native ? createHash('sha256').update(JSON.stringify({ authorityDigest: this.#authorityDigest,
187
+ key: input.key, artifactSha256, operation, ...kindField })).digest('hex') : undefined;
188
+ const request = this.#native
189
+ ? { schemaVersion: 1, nonce, artifactSha256, entry: staged.entry,
190
+ modulesPath: this.#modulesPath, operation, ...kindField }
191
+ : { schemaVersion: 1, sha256: artifactSha256, sizeBytes: input.artifact.length, operation, ...kindField };
192
+ const stdin = canonicalJson(request);
193
+ if (stdin === undefined || Buffer.byteLength(stdin) > MAX_OPERATION_BYTES)
194
+ return unknown('plugin-operation-out-of-bound', true);
195
+ let isolated;
196
+ try {
197
+ isolated = this.#native
198
+ ? await this.#runner.run(input.key, staged.files, stdin, input.signal)
199
+ : await this.#runner.run(input.key, input.artifact.toString('base64'), stdin, input.signal);
200
+ }
201
+ catch {
202
+ return unknown('plugin-runner-unavailable');
203
+ }
204
+ if (isolated.status !== 'succeeded' || isolated.quiescent !== true || isolated.exitCode !== 0)
205
+ return unknown(isolated.reason ?? 'plugin-runner-unsettled', isolated.quiescent, isolated.jobId);
206
+ if (Buffer.byteLength(isolated.stdout) > MAX_WORKER_OUTPUT_BYTES || !isolated.stdout.endsWith('\n')
207
+ || isolated.stdout.indexOf('\n') !== isolated.stdout.length - 1)
208
+ return unknown('plugin-worker-output-invalid', true, isolated.jobId);
209
+ try {
210
+ const value = JSON.parse(isolated.stdout.slice(0, -1));
211
+ if (this.#native) {
212
+ if (!value || typeof value !== 'object' || Array.isArray(value))
213
+ return unknown('plugin-worker-output-invalid', true, isolated.jobId);
214
+ const frame = value;
215
+ const header = frame.wireVersion === 1 && frame.nonce === nonce && frame.artifactSha256 === artifactSha256
216
+ && frame.operationDigest === createHash('sha256').update(JSON.stringify(operation)).digest('hex');
217
+ if (!header)
218
+ return unknown('plugin-worker-output-invalid', true, isolated.jobId);
219
+ if (frame.status === 'unknown' && typeof frame.reason === 'string' && frame.reason.length > 0
220
+ && frame.reason.length <= 128 && Object.keys(frame).length === 6)
221
+ return unknown(frame.reason, true, isolated.jobId);
222
+ const hasPluginKind = Object.hasOwn(frame, 'pluginKind');
223
+ if (hasPluginKind && (!isPluginKind(frame.pluginKind) || (input.pluginKind !== undefined && frame.pluginKind !== input.pluginKind)))
224
+ return unknown('plugin-worker-observation-invalid', true, isolated.jobId);
225
+ if (!hasPluginKind && input.pluginKind !== undefined)
226
+ return unknown('plugin-worker-observation-invalid', true, isolated.jobId);
227
+ if (frame.status !== 'result' || !SHA256.test(frame.schemaDigest)
228
+ || Object.keys(frame).length !== (hasPluginKind ? 8 : 7))
229
+ return unknown('plugin-worker-observation-invalid', true, isolated.jobId);
230
+ if (operation.kind === 'discover') {
231
+ if (!Array.isArray(frame.schemas) || frame.schemas.length < 1 || frame.schemas.length > 64
232
+ || frame.calls !== undefined || createHash('sha256').update(JSON.stringify(frame.schemas)).digest('hex') !== frame.schemaDigest)
233
+ return unknown('plugin-worker-observation-invalid', true, isolated.jobId);
234
+ const names = new Set();
235
+ for (const schema of frame.schemas) {
236
+ const name = schema?.name;
237
+ if (typeof name !== 'string' || !SAFE_TOOL.test(name) || names.has(name))
238
+ return unknown('plugin-worker-observation-invalid', true, isolated.jobId);
239
+ names.add(name);
240
+ }
241
+ }
242
+ else {
243
+ const calls = operation.calls;
244
+ if (frame.schemaDigest !== operation.schemaDigest || !Array.isArray(frame.calls)
245
+ || frame.calls.length !== calls.length || frame.schemas !== undefined
246
+ || frame.calls.some((call, index) => !call || typeof call !== 'object'
247
+ || call.id !== calls[index].id
248
+ || call.toolName !== calls[index].toolName
249
+ || !Object.hasOwn(call, 'result')))
250
+ return unknown('plugin-worker-observation-invalid', true, isolated.jobId);
251
+ }
252
+ return { status: 'observed', quiescent: true, artifactSha256, jobId: isolated.jobId,
253
+ boundary: NATIVE_BEHAVIOR_BOUNDARY, runtimeDigest: this.#runtimeDigest, environment: this.#environment,
254
+ ...(isPluginKind(frame.pluginKind) ? { pluginKind: frame.pluginKind } : {}),
255
+ schemaDigest: frame.schemaDigest,
256
+ ...(operation.kind === 'discover' ? { schemas: frame.schemas }
257
+ : { calls: frame.calls }) };
258
+ }
259
+ if (value !== null && typeof value === 'object' && !Array.isArray(value)) {
260
+ const record = value;
261
+ if (record.schemaVersion === 2 && record.boundary === BOUNDARY && record.status === 'unknown'
262
+ && typeof record.reason === 'string' && record.reason.length > 0 && record.reason.length <= 128
263
+ && Object.keys(record).length === 4)
264
+ return unknown(record.reason, true, isolated.jobId);
265
+ }
266
+ if (!validObservation(value, operation, artifactSha256, input.pluginKind))
267
+ return unknown('plugin-worker-observation-invalid', true, isolated.jobId);
268
+ const observation = value;
269
+ if (this.#linux && !validLinuxFrame(observation, operation, this.#environment))
270
+ return unknown('plugin-worker-observation-invalid', true, isolated.jobId);
271
+ return { status: 'observed', quiescent: true, artifactSha256, jobId: isolated.jobId,
272
+ ...(this.#linux ? { boundary: LINUX_BEHAVIOR_BOUNDARY, runtimeDigest: this.#runtimeDigest } : {}),
273
+ ...(isPluginKind(observation.pluginKind) ? { pluginKind: observation.pluginKind } : {}),
274
+ environment: observation.environment, schemaDigest: observation.schemaDigest,
275
+ ...(operation.kind === 'discover' ? { schemas: observation.schemas } : { calls: observation.calls }) };
276
+ }
277
+ catch {
278
+ return unknown('plugin-worker-output-invalid', true, isolated.jobId);
279
+ }
280
+ }
281
+ close() { return this.#runner.close(); }
282
+ }
283
+ /* DSH_PLUGIN_VERIFIER_WORKER_START
284
+ // Inlined into the native behavior worker; this code executes inside the isolation
285
+ // worker, never in the Host process.
286
+ import { createHash } from 'node:crypto'
287
+ import { spawn } from 'node:child_process'
288
+ import { existsSync, mkdirSync, readFileSync, symlinkSync, unlinkSync, writeFileSync } from 'node:fs'
289
+ import { dirname, join, resolve } from 'node:path'
290
+ import { gunzipSync } from 'node:zlib'
291
+
292
+ const limit = 512 * 1024
293
+ const safeId = /^[A-Za-z0-9][A-Za-z0-9_.:-]{0,95}$/
294
+ const safeTool = /^[a-z][a-z0-9_-]{0,95}$/
295
+ const shaPattern = /^[a-f0-9]{64}$/
296
+ const kinds = new Set(['tool', 'service', 'channel', 'ui'])
297
+ const fail = reason => { throw new Error(reason) }
298
+ const digest = bytes => createHash('sha256').update(bytes).digest('hex')
299
+ const stripComment = line => {
300
+ let q = ''
301
+ for (let i = 0; i < line.length; i += 1) {
302
+ const c = line[i]
303
+ if (q) { if (c === q && line[i - 1] !== '\\') q = '' }
304
+ else if (c === "'" || c === '"') q = c
305
+ else if (c === '#' && (i === 0 || /\s/.test(line[i - 1]))) return line.slice(0, i)
306
+ }
307
+ return line
308
+ }
309
+ const parseScalar = raw => {
310
+ const s = stripComment(raw).trim()
311
+ if (!s || s.startsWith('!!js') || s.startsWith('#')) return undefined
312
+ if (s === 'true') return true
313
+ if (s === 'false') return false
314
+ if (s === 'null' || s === '~') return null
315
+ if (s === '[]') return []
316
+ if (s === '{}') return Object.create(null)
317
+ if (/^-?\d+(?:\.\d+)?$/.test(s)) return Number(s)
318
+ if ((s.startsWith("'") && s.endsWith("'")) || (s.startsWith('"') && s.endsWith('"'))) return s.slice(1, -1)
319
+ return s
320
+ }
321
+ const isNonEmptyDecl = raw => {
322
+ const val = parseScalar(raw)
323
+ if (val === undefined || val === false || val === null || val === '') return false
324
+ if (Array.isArray(val)) return val.length > 0
325
+ if (typeof val === 'object') return Object.keys(val).length > 0
326
+ return true
327
+ }
328
+ function parsePatchMeta(rawYaml) {
329
+ const inject = []
330
+ const config = Object.create(null)
331
+ let inInject = false, injectIndent = -1, inConfig = false, configIndent = -1, configStack = []
332
+ let hasEntry = false, hasUiDecl = false, hasChannelDecl = false, hasServiceDecl = false, pendingDecl = null
333
+ for (const rawLine of rawYaml.split(/\r?\n/)) {
334
+ const line = stripComment(rawLine)
335
+ if (!line.trim()) continue
336
+ const indent = line.length - line.trimStart().length
337
+ const trimmed = line.trim()
338
+ if (pendingDecl) {
339
+ if (indent > pendingDecl.indent) {
340
+ const kv = /^(?:-\s+)?[A-Za-z0-9_-]+\s*:\s*(.*)$/.exec(trimmed)
341
+ if (!kv || !kv[1].trim() || isNonEmptyDecl(kv[1])) {
342
+ if (pendingDecl.kind === 'ui') hasUiDecl = true
343
+ else if (pendingDecl.kind === 'channel') hasChannelDecl = true
344
+ else hasServiceDecl = true
345
+ pendingDecl = null
346
+ }
347
+ } else pendingDecl = null
348
+ }
349
+ if (/^-+\s*insert\s*:/.test(trimmed) || /^name\s*:/.test(trimmed)) hasEntry = true
350
+ if (inInject) {
351
+ if (indent > injectIndent && trimmed.startsWith('- ')) {
352
+ const val = parseScalar(trimmed.slice(2))
353
+ if (typeof val === 'string' && val) inject.push(val)
354
+ continue
355
+ }
356
+ if (indent <= injectIndent && !trimmed.startsWith('- ')) inInject = false
357
+ }
358
+ if (inConfig) {
359
+ if (indent <= configIndent) { inConfig = false; configStack = [] }
360
+ else {
361
+ while (configStack.length > 1 && indent <= configStack[configStack.length - 1].indent) configStack.pop()
362
+ const match = /^([A-Za-z0-9_-]+)\s*:\s*(.*)$/.exec(trimmed)
363
+ if (match && match[1] !== '__proto__' && match[1] !== 'constructor' && match[1] !== 'prototype') {
364
+ const rest = match[2].trim(), targetObj = configStack[configStack.length - 1].obj
365
+ if (!rest) {
366
+ const child = Object.create(null)
367
+ targetObj[match[1]] = child
368
+ configStack.push({ obj: child, indent })
369
+ } else {
370
+ const val = parseScalar(rest)
371
+ if (val !== undefined) targetObj[match[1]] = val
372
+ }
373
+ }
374
+ continue
375
+ }
376
+ }
377
+ const injectMatch = /^(?:-\s+)?inject\s*:\s*(.*)$/.exec(trimmed)
378
+ if (injectMatch) {
379
+ const rest = injectMatch[1].trim()
380
+ if (rest.startsWith('[') && rest.endsWith(']')) {
381
+ for (const item of rest.slice(1, -1).split(',')) {
382
+ const val = parseScalar(item)
383
+ if (typeof val === 'string' && val) inject.push(val)
384
+ }
385
+ } else if (!rest) { inInject = true; injectIndent = indent }
386
+ continue
387
+ }
388
+ const configMatch = /^(?:-\s+)?config\s*:\s*(.*)$/.exec(trimmed)
389
+ if (configMatch) {
390
+ if (!configMatch[1].trim()) { inConfig = true; configIndent = indent; configStack = [{ obj: config, indent }] }
391
+ continue
392
+ }
393
+ const declMatch = /^(?:-\s+)?(ui|routes|sections|settings|channel|services|provides)\s*:\s*(.*)$/.exec(trimmed)
394
+ if (declMatch) {
395
+ const key = declMatch[1], rest = declMatch[2].trim()
396
+ const kind = key === 'channel' ? 'channel' : (key === 'services' || key === 'provides') ? 'service' : 'ui'
397
+ if (rest) {
398
+ if (isNonEmptyDecl(rest)) {
399
+ if (kind === 'ui') hasUiDecl = true
400
+ else if (kind === 'channel') hasChannelDecl = true
401
+ else hasServiceDecl = true
402
+ }
403
+ } else pendingDecl = { kind, indent }
404
+ }
405
+ }
406
+ return { hasEntry, inject, config, hasUiDecl, hasChannelDecl, hasServiceDecl }
407
+ }
408
+ const hasNonEmptyObj = v => Boolean(v && typeof v === 'object' && !Array.isArray(v) && Object.keys(v).length > 0)
409
+ function readPackageMeta(destination, seen, manifest) {
410
+ const pkgDir = join(destination, 'package')
411
+ const dsh = manifest.dsh && typeof manifest.dsh === 'object' ? manifest.dsh : {}
412
+ const clientExp = manifest.exports && typeof manifest.exports === 'object' ? manifest.exports['./client'] : undefined
413
+ const clientPath = typeof clientExp === 'string' ? clientExp
414
+ : clientExp && typeof clientExp === 'object' ? (clientExp.default ?? clientExp.import) : undefined
415
+ let hasClientExport = false, clientExportMissing = false
416
+ if (typeof clientPath === 'string') {
417
+ if (/^\.\/lib\/[A-Za-z0-9._/-]+\.js$/.test(clientPath) && !clientPath.split('/').includes('..')
418
+ && existsSync(join(pkgDir, clientPath))) hasClientExport = true
419
+ else clientExportMissing = true
420
+ }
421
+ const pkg = {
422
+ dshKind: kinds.has(dsh.kind) ? dsh.kind : undefined,
423
+ dshClient: hasNonEmptyObj(dsh.client),
424
+ dshUi: hasNonEmptyObj(dsh.ui),
425
+ dshChannel: hasNonEmptyObj(dsh.channel),
426
+ hasClientExport,
427
+ clientExportMissing,
428
+ }
429
+ let patch = { hasEntry: false, inject: [], config: Object.create(null), hasUiDecl: false, hasChannelDecl: false, hasServiceDecl: false }
430
+ if (seen.has('package/cordis.patch.yml')) {
431
+ const rawPatch = readFileSync(join(pkgDir, 'cordis.patch.yml'), 'utf8')
432
+ if (Buffer.byteLength(rawPatch) <= 64 * 1024) patch = parsePatchMeta(rawPatch)
433
+ }
434
+ return { pkg, patch }
435
+ }
436
+ const text = bytes => {
437
+ const end = bytes.indexOf(0)
438
+ const sliced = end < 0 ? bytes : bytes.subarray(0, end)
439
+ const value = sliced.toString('utf8')
440
+ if (!Buffer.from(value, 'utf8').equals(sliced)) fail('invalid-utf8-tar')
441
+ return value
442
+ }
443
+ const octal = bytes => {
444
+ const raw = text(bytes).trim()
445
+ if (!/^[0-7]+$/.test(raw)) fail('invalid-tar-number')
446
+ const value = Number.parseInt(raw, 8)
447
+ if (!Number.isSafeInteger(value)) fail('invalid-tar-number')
448
+ return value
449
+ }
450
+ const parsePax = bytes => {
451
+ const values = {}
452
+ for (let at = 0; at < bytes.length;) {
453
+ const space = bytes.indexOf(32, at)
454
+ if (space < 0) fail('invalid-pax')
455
+ const size = Number(bytes.subarray(at, space).toString('ascii'))
456
+ if (!Number.isSafeInteger(size) || size <= space - at + 2 || at + size > bytes.length || bytes[at + size - 1] !== 10) fail('invalid-pax')
457
+ const line = bytes.subarray(space + 1, at + size - 1).toString('utf8')
458
+ const equal = line.indexOf('=')
459
+ if (equal < 1 || Object.hasOwn(values, line.slice(0, equal))) fail('invalid-pax')
460
+ values[line.slice(0, equal)] = line.slice(equal + 1)
461
+ at += size
462
+ }
463
+ return values
464
+ }
465
+ function extract(bytes) {
466
+ let tar
467
+ try { tar = gunzipSync(bytes, { maxOutputLength: 16 * 1024 * 1024 }) }
468
+ catch { fail('invalid-or-oversized-tgz') }
469
+ const destination = '/workspace/plugin'
470
+ mkdirSync(destination, { mode: 0o700 })
471
+ let at = 0, extension = {}, global = {}, count = 0
472
+ const seen = new Set()
473
+ while (at + 512 <= tar.length) {
474
+ const header = tar.subarray(at, at + 512)
475
+ if (header.every(byte => byte === 0)) break
476
+ const expectedChecksum = octal(header.subarray(148, 156))
477
+ let checksum = 0
478
+ for (let index = 0; index < 512; index += 1) checksum += index >= 148 && index < 156 ? 32 : header[index]
479
+ if (expectedChecksum !== checksum) fail('invalid-tar-checksum')
480
+ const size = octal(header.subarray(124, 136))
481
+ const end = at + 512 + size
482
+ if (!Number.isSafeInteger(end) || end > tar.length || ++count > 256) fail('invalid-tar-member')
483
+ const kind = String.fromCharCode(header[156] || 48)
484
+ if (kind === 'g' || kind === 'x') {
485
+ if (size > 1_048_576) fail('oversized-tar-extension')
486
+ const parsed = parsePax(tar.subarray(at + 512, end))
487
+ if (kind === 'g') global = { ...global, ...parsed }
488
+ else extension = parsed
489
+ } else {
490
+ const attributes = { ...global, ...extension }
491
+ if (Object.keys(attributes).some(key => !['path', 'mtime', 'atime', 'ctime', 'comment', 'uid', 'gid', 'uname', 'gname', 'mode'].includes(key))) fail('unsupported-tar-extension')
492
+ const prefix = text(header.subarray(345, 500))
493
+ const rawName = prefix ? prefix + '/' + text(header.subarray(0, 100)) : text(header.subarray(0, 100))
494
+ const raw = attributes.path ?? rawName
495
+ const name = typeof raw === 'string' && raw.endsWith('/') ? raw.slice(0, -1) : raw
496
+ if (typeof name !== 'string' || name.length > 256
497
+ || name !== 'package' && (!name.startsWith('package/')
498
+ || name.slice(8).split('/').some(part => !part || part === '.' || part === '..' || !/^[A-Za-z0-9._-]+$/.test(part)))) fail('unsafe-tar-path')
499
+ if (seen.has(name) || (kind !== '0' && kind !== '5' && kind !== '7')
500
+ || name === 'package' && kind !== '5') fail('duplicate-or-unsafe-tar-entry')
501
+ seen.add(name)
502
+ const target = join(destination, name)
503
+ if (resolve(target) !== target || target !== join(destination, 'package') && !target.startsWith(destination + '/')) fail('unsafe-tar-path')
504
+ if (kind === '5') mkdirSync(target, { recursive: true, mode: 0o700 })
505
+ else {
506
+ mkdirSync(dirname(target), { recursive: true, mode: 0o700 })
507
+ writeFileSync(target, tar.subarray(at + 512, end), { flag: 'wx', mode: 0o600 })
508
+ }
509
+ extension = {}
510
+ }
511
+ at = end + (512 - size % 512) % 512
512
+ }
513
+ if (at + 1024 > tar.length || !tar.subarray(at).every(byte => byte === 0)) fail('invalid-tar-trailer')
514
+ if (!seen.has('package/package.json')) fail('missing-package-manifest')
515
+ const manifest = JSON.parse(readFileSync(join(destination, 'package/package.json'), 'utf8'))
516
+ if (!manifest || typeof manifest !== 'object' || typeof manifest.main !== 'string'
517
+ || !/^\.\/lib\/[A-Za-z0-9._/-]+\.js$/.test(manifest.main)
518
+ || manifest.main.split('/').includes('..')) fail('invalid-package-entry')
519
+ const entry = join(destination, 'package', manifest.main)
520
+ if (!existsSync(entry)) fail('missing-package-entry')
521
+ const meta = readPackageMeta(destination, seen, manifest)
522
+ symlinkSync('/opt/dsh-plugin-verifier/node_modules', join(destination, 'package/node_modules'))
523
+ return { entry, meta }
524
+ }
525
+ function validOperation(value) {
526
+ if (!value || typeof value !== 'object' || Array.isArray(value)) return false
527
+ if (value.kind === 'discover') return Object.keys(value).length === 1
528
+ if (value.kind !== 'invoke' || Object.keys(value).length !== 3 || !shaPattern.test(value.schemaDigest)
529
+ || !Array.isArray(value.calls) || value.calls.length < 1 || value.calls.length > 8) return false
530
+ const ids = new Set()
531
+ for (const call of value.calls) {
532
+ if (!call || typeof call !== 'object' || Object.keys(call).length !== 3
533
+ || !safeId.test(call.id) || !safeTool.test(call.toolName) || ids.has(call.id)) return false
534
+ ids.add(call.id)
535
+ }
536
+ return true
537
+ }
538
+ function version(name) {
539
+ return JSON.parse(readFileSync('/opt/dsh-plugin-verifier/node_modules/' + name + '/package.json', 'utf8')).version
540
+ }
541
+ const unknown = reason => ({ schemaVersion: 2, boundary: 'process-seccomp-v1', status: 'unknown', reason })
542
+ const decoded = bytes => new TextDecoder('utf-8', { fatal: true }).decode(bytes)
543
+ function validChild(value, operation, requestedKind) {
544
+ if (!value || typeof value !== 'object' || Array.isArray(value) || value.wireVersion !== 1) return false
545
+ if (value.status === 'unknown') return Object.keys(value).length === 3
546
+ && typeof value.reason === 'string' && value.reason.length > 0 && value.reason.length <= 128
547
+ const hasKind = Object.hasOwn(value, 'pluginKind')
548
+ if (hasKind && (!kinds.has(value.pluginKind) || (requestedKind !== undefined && value.pluginKind !== requestedKind))) return false
549
+ if (!hasKind && requestedKind !== undefined) return false
550
+ if (value.status !== 'result' || !Array.isArray(value.schemas) || value.schemas.length < 1
551
+ || value.schemas.length > 64 || Object.keys(value).length !== (operation.kind === 'discover' ? 3 : 4) + (hasKind ? 1 : 0)) return false
552
+ const names = new Set()
553
+ for (const schema of value.schemas) {
554
+ if (!schema || typeof schema !== 'object' || Array.isArray(schema)
555
+ || !safeTool.test(schema.name) || names.has(schema.name)) return false
556
+ names.add(schema.name)
557
+ }
558
+ if (operation.kind === 'discover') return value.calls === undefined
559
+ if (!Array.isArray(value.calls) || value.calls.length !== operation.calls.length) return false
560
+ for (let index = 0; index < value.calls.length; index += 1) {
561
+ const call = value.calls[index], requested = operation.calls[index]
562
+ if (!call || typeof call !== 'object' || Array.isArray(call) || Object.keys(call).length !== 3
563
+ || call.id !== requested.id || call.toolName !== requested.toolName || !names.has(call.toolName)
564
+ || !Object.hasOwn(call, 'result')) return false
565
+ }
566
+ return true
567
+ }
568
+ function observeChild(entry, operation, requestedKind, meta) {
569
+ return new Promise(resolvePromise => {
570
+ let child
571
+ try {
572
+ child = spawn('/opt/dsh-plugin-verifier/candidate-launcher', [], {
573
+ cwd: '/workspace/plugin/package',
574
+ env: { PATH: '/usr/bin:/bin', LANG: 'C', LC_ALL: 'C', NODE_ENV: 'production' },
575
+ stdio: ['pipe', 'ignore', 'ignore', 'pipe'],
576
+ })
577
+ } catch { resolvePromise({ reason: 'candidate-launch-failed' }); return }
578
+ let bytes = Buffer.alloc(0), overflow = false, error = false, timedOut = false
579
+ const timer = setTimeout(() => { timedOut = true; child.kill('SIGKILL') }, 8000)
580
+ child.stdio[3].on('data', chunk => {
581
+ if (overflow) return
582
+ if (bytes.length + chunk.length > 60 * 1024) {
583
+ overflow = true
584
+ child.kill('SIGKILL')
585
+ } else bytes = Buffer.concat([bytes, chunk])
586
+ })
587
+ child.once('error', () => { error = true })
588
+ child.stdin.on('error', () => { error = true })
589
+ child.once('close', (code, signal) => {
590
+ clearTimeout(timer)
591
+ if (timedOut || overflow || error || code !== 0 || signal !== null) {
592
+ resolvePromise({ reason: timedOut ? 'candidate-timeout' : 'candidate-process-unsettled' }); return
593
+ }
594
+ try {
595
+ const text = decoded(bytes)
596
+ if (!text.endsWith('\n') || text.indexOf('\n') !== text.length - 1) fail('candidate-result-invalid')
597
+ const value = JSON.parse(text.slice(0, -1))
598
+ resolvePromise(validChild(value, operation, requestedKind) ? { value } : { reason: 'candidate-result-invalid' })
599
+ } catch { resolvePromise({ reason: 'candidate-result-invalid' }) }
600
+ })
601
+ child.stdin.end(JSON.stringify({ operation, entry, ...(requestedKind !== undefined ? { pluginKind: requestedKind } : {}), meta }) + '\n')
602
+ })
603
+ }
604
+ let result
605
+ try {
606
+ const encoded = readFileSync('/workspace/artifact', 'utf8')
607
+ const request = JSON.parse(readFileSync('/workspace/input', 'utf8'))
608
+ // Remove both staged files before any candidate process exists. The candidate
609
+ // gets only its operation and the extracted package through its stdin/path.
610
+ unlinkSync('/workspace/artifact')
611
+ unlinkSync('/workspace/input')
612
+ if (!request || request.schemaVersion !== 1 || !shaPattern.test(request.sha256)
613
+ || !Number.isSafeInteger(request.sizeBytes) || request.sizeBytes < 1 || request.sizeBytes > limit
614
+ || (request.pluginKind !== undefined && !kinds.has(request.pluginKind))
615
+ || !validOperation(request.operation) || !/^[A-Za-z0-9+/]+={0,2}$/.test(encoded)) fail('invalid-worker-input')
616
+ const packed = Buffer.from(encoded, 'base64')
617
+ if (packed.length !== request.sizeBytes || packed.toString('base64') !== encoded || digest(packed) !== request.sha256) fail('artifact-mismatch')
618
+ const { entry, meta } = extract(packed)
619
+ const child = await observeChild(entry, request.operation, request.pluginKind, meta)
620
+ if (!child.value) fail(child.reason)
621
+ if (child.value.status === 'unknown') fail(child.value.reason)
622
+ const schemas = child.value.schemas
623
+ const schemaDigest = digest(Buffer.from(JSON.stringify(schemas)))
624
+ if (request.operation.kind === 'invoke' && schemaDigest !== request.operation.schemaDigest) fail('schema-digest-changed')
625
+ const base = { schemaVersion: 2, boundary: 'process-seccomp-v1', status: 'observed',
626
+ artifactSha256: request.sha256, quiescent: true,
627
+ ...(child.value.pluginKind !== undefined ? { pluginKind: child.value.pluginKind } : {}),
628
+ environment: { node: process.version, cordis: version('@deepseek-ai/cordis'),
629
+ tools: version('@deepseek-ai/dsh-tools'), systemPrompt: version('@deepseek-ai/dsh-system-prompt') }, schemaDigest }
630
+ result = request.operation.kind === 'discover' ? { ...base, schemas } : { ...base, calls: child.value.calls }
631
+ } catch (error) {
632
+ result = unknown(error instanceof Error ? error.message.slice(0, 128) : 'worker-error')
633
+ }
634
+ const output = JSON.stringify(result)
635
+ if (Buffer.byteLength(output) > 60 * 1024) process.stdout.write(JSON.stringify(unknown('worker-output-too-large')) + '\n')
636
+ else process.stdout.write(output + '\n')
637
+ DSH_PLUGIN_VERIFIER_WORKER_END */
638
+ /* DSH_PLUGIN_VERIFIER_CANDIDATE_START
639
+ // Executes only after the fixed launcher installs seccomp and Node permissions.
640
+ import { createHash } from 'node:crypto'
641
+ import { writeSync } from 'node:fs'
642
+ import { pathToFileURL } from 'node:url'
643
+ import { Context, Service } from '@deepseek-ai/cordis'
644
+ import SystemPrompt from '@deepseek-ai/dsh-system-prompt'
645
+ import ToolRuntime, { projectToolSchema } from '@deepseek-ai/dsh-tools'
646
+ import { ToolExecutionPipeline, executeToolBatch } from '@deepseek-ai/dsh-tools/pipeline'
647
+
648
+ const safeTool = /^[a-z][a-z0-9_-]{0,95}$/
649
+ const safeEnum = /^[A-Za-z0-9_.:-]{1,64}$/
650
+ const safeMethod = /^[A-Za-z][A-Za-z0-9_]{0,63}$/
651
+ const kinds = new Set(['tool', 'service', 'channel', 'ui'])
652
+ const skipMethods = new Set(['constructor', 'start', 'stop', 'dispose', 'init'])
653
+ const cordisOrig = Symbol.for('cordis.original')
654
+ const unwrap = v => (v && typeof v === 'object' ? v[cordisOrig] : undefined) ?? v
655
+ const badHealth = h => !h || typeof h !== 'object' || h.ready === false || h.ok === false || h.status === 'error' || h.status === 'unhealthy'
656
+ const listMethods = val => {
657
+ if (!val || typeof val !== 'object') return []
658
+ const seen = new Set()
659
+ for (let obj = val; obj && obj !== Object.prototype; obj = Object.getPrototypeOf(obj)) {
660
+ for (const k of Object.getOwnPropertyNames(obj)) {
661
+ if (!skipMethods.has(k) && !k.startsWith('_') && safeMethod.test(k) && safeEnum.test(k) && typeof val[k] === 'function') seen.add(k)
662
+ }
663
+ }
664
+ return [...seen].slice(0, 16)
665
+ }
666
+ const checkAdapter = a => Boolean(a && typeof a === 'object' && typeof a.channel === 'string' && a.channel
667
+ && typeof a.account === 'string' && a.account && a.capabilities && typeof a.capabilities === 'object'
668
+ && typeof a.start === 'function' && typeof a.send === 'function')
669
+ const hasNonEmpty = (v, seen = new Set()) => {
670
+ if (typeof v === 'function') return true
671
+ if (!v || typeof v !== 'object' || seen.has(v)) return false
672
+ seen.add(v)
673
+ const ok = Array.isArray(v)
674
+ ? v.some(x => typeof x === 'function' || (x !== undefined && x !== null && x !== false && x !== '' && (typeof x !== 'object' || hasNonEmpty(x, seen))))
675
+ : Object.values(v).some(x => typeof x === 'function' || (x !== undefined && x !== null && x !== false && x !== '' && (typeof x !== 'object' || hasNonEmpty(x, seen))))
676
+ seen.delete(v)
677
+ return ok
678
+ }
679
+ const validTypertObj = v => Boolean(v && typeof v === 'object' && !Array.isArray(v)
680
+ && typeof v.package === 'string' && v.package.trim().length > 0
681
+ && (hasNonEmpty(v.schemas) || hasNonEmpty(v.invocations) || hasNonEmpty(v.descriptors)
682
+ || hasNonEmpty(v.routes) || hasNonEmpty(v.sections) || hasNonEmpty(v.settings) || hasNonEmpty(v.model)))
683
+ const validUiObj = v => typeof v === 'function' || Boolean(v && typeof v === 'object' && !Array.isArray(v)
684
+ && (hasNonEmpty(v.routes) || hasNonEmpty(v.sections) || hasNonEmpty(v.settings)
685
+ || validTypertObj(v) || validTypertObj(v.TYPERT)
686
+ || typeof v.render === 'function' || typeof v.mount === 'function' || typeof v.component === 'function'))
687
+ let fiber, ctx, result, disposed = true, providedNames = []
688
+ const channelAdapters = new Set()
689
+ const typertContributions = new Set()
690
+ class TypertSeam extends Service {
691
+ constructor(c) { super(c, 'typert') }
692
+ register(contribution) {
693
+ if (!validTypertObj(contribution)) throw new Error('invalid-ui-contribution')
694
+ return this.ctx.effect(() => {
695
+ typertContributions.add(contribution)
696
+ return () => { typertContributions.delete(contribution) }
697
+ }, 'typert.register()')
698
+ }
699
+ }
700
+ try {
701
+ const chunks = []
702
+ let total = 0
703
+ for await (const chunk of process.stdin) {
704
+ total += chunk.length
705
+ if (total > 64 * 1024) throw new Error('candidate-input-too-large')
706
+ chunks.push(chunk)
707
+ }
708
+ const request = JSON.parse(Buffer.concat(chunks).toString('utf8'))
709
+ if (!request || typeof request.entry !== 'string'
710
+ || !/^\/workspace\/plugin\/package\/lib\/[A-Za-z0-9._/-]+\.js$/.test(request.entry)
711
+ || request.entry.split('/').includes('..')
712
+ || (request.pluginKind !== undefined && !kinds.has(request.pluginKind))
713
+ || !request.operation || !['discover', 'invoke'].includes(request.operation.kind)) throw new Error('candidate-input-invalid')
714
+ const meta = request.meta ?? { pkg: {}, patch: { inject: [], config: {} } }
715
+ const pkg = meta.pkg ?? {}, patch = meta.patch ?? { inject: [], config: {} }
716
+ ctx = new Context()
717
+ await ctx.plugin(SystemPrompt, { includeHarnessIdentity: false, includeRuntimeContext: false, personaPrefix: '' })
718
+ await ctx.plugin(ToolRuntime)
719
+ const pipeline = new ToolExecutionPipeline(ctx)
720
+ ctx.tools.setExecutor({
721
+ describe: tools => ({ schemas: tools.map(definition => projectToolSchema(definition, false)) }),
722
+ execute: input => executeToolBatch(input, pipeline, () => 1),
723
+ })
724
+ const mod = await import(pathToFileURL(request.entry).href)
725
+ const target = mod.default ?? mod
726
+ const declaredInject = [...new Set([
727
+ ...(Array.isArray(target?.inject) ? target.inject : []),
728
+ ...(Array.isArray(mod?.inject) ? mod.inject : []),
729
+ ...(Array.isArray(patch.inject) ? patch.inject : []),
730
+ ].filter(v => typeof v === 'string'))]
731
+ if (request.pluginKind === 'channel' || declaredInject.includes('assistantDelivery') || pkg.dshChannel || patch.hasChannelDecl) {
732
+ ctx.provide('assistantDelivery', {
733
+ registerAdapter(adapter) {
734
+ if (!checkAdapter(adapter)) throw new Error('invalid-channel-adapter')
735
+ channelAdapters.add(adapter)
736
+ return async () => { channelAdapters.delete(adapter) }
737
+ },
738
+ health: () => ({ ready: true }),
739
+ })
740
+ }
741
+ if (request.pluginKind === 'ui' || declaredInject.includes('typert') || pkg.dshClient || pkg.dshUi || patch.hasUiDecl) {
742
+ new TypertSeam(ctx)
743
+ }
744
+ const hasPatchCfg = patch.config && typeof patch.config === 'object' && Object.keys(patch.config).length > 0
745
+ const pluginCfg = hasPatchCfg ? patch.config : (typeof target?.Config === 'function' || typeof mod?.Config === 'function' ? {} : undefined)
746
+ fiber = pluginCfg !== undefined ? ctx.plugin(target, pluginCfg) : ctx.plugin(target)
747
+ let activationTimer
748
+ try {
749
+ await Promise.race([fiber, new Promise((_, reject) => {
750
+ activationTimer = setTimeout(() => reject(new Error('plugin-activation-timeout')), 5000)
751
+ })])
752
+ } finally { clearTimeout(activationTimer) }
753
+ await new Promise(resolve => setImmediate(resolve))
754
+ if (fiber.state !== 2) throw new Error('plugin-fiber-not-active')
755
+ const toolSchemas = (await ctx.systemPrompt.assemble({})).tools ?? []
756
+ const provisions = [...(fiber.provisions ?? [])]
757
+ const uiExports = Boolean(validTypertObj(mod.TYPERT) || validTypertObj(mod.TYPERT_REMOTE)
758
+ || hasNonEmpty(mod.routes) || hasNonEmpty(mod.sections) || hasNonEmpty(mod.settings) || validUiObj(mod.ui)
759
+ || (target && typeof target === 'object' && (validTypertObj(target.TYPERT) || validTypertObj(target.TYPERT_REMOTE)
760
+ || hasNonEmpty(target.routes) || hasNonEmpty(target.sections) || hasNonEmpty(target.settings) || validUiObj(target.ui))))
761
+ const channelExports = Boolean(mod.adapter || mod.channel || (target && typeof target === 'object' && (target.adapter || target.channel)))
762
+ const channelProvisions = provisions.filter(p => checkAdapter(p.value))
763
+ const isChannelProvision = channelProvisions.length > 0
764
+ let effectiveKind = request.pluginKind
765
+ if (!effectiveKind) {
766
+ if (Array.isArray(toolSchemas) && toolSchemas.length >= 1) effectiveKind = 'tool'
767
+ else if (typertContributions.size > 0 || pkg.hasClientExport || pkg.clientExportMissing || uiExports) effectiveKind = 'ui'
768
+ else if (channelAdapters.size > 0 || pkg.dshChannel || patch.hasChannelDecl || declaredInject.includes('assistantDelivery') || channelExports || isChannelProvision) effectiveKind = 'channel'
769
+ else if (provisions.length > 0 || pkg.dshKind === 'service' || patch.hasServiceDecl || (typeof (target?.apply ?? target) === 'function' && ((fiber._disposables?.length ?? 0) > 0 || patch.hasEntry))) effectiveKind = 'service'
770
+ else throw new Error('invalid-tool-schemas')
771
+ }
772
+ providedNames = provisions.map(p => p.name)
773
+ let schemas = []
774
+ const toolNames = new Set()
775
+ for (const s of Array.isArray(toolSchemas) ? toolSchemas : []) {
776
+ if (!s || !safeTool.test(s.name) || toolNames.has(s.name)) throw new Error('invalid-tool-schemas')
777
+ toolNames.add(s.name)
778
+ }
779
+ if (effectiveKind === 'tool') {
780
+ if (!Array.isArray(toolSchemas) || toolSchemas.length < 1 || toolSchemas.length > 64) throw new Error('invalid-tool-schemas')
781
+ schemas = toolSchemas
782
+ } else if (effectiveKind === 'service') {
783
+ if (provisions.length < 1 && !((fiber._disposables?.length ?? 0) >= 1 && typeof (target?.apply ?? target) === 'function')) throw new Error('invalid-service-plugin')
784
+ const svcMap = new Map(), svcMethods = new Map(), allMethods = new Set()
785
+ for (const p of provisions) {
786
+ if (unwrap(ctx.get(p.name)) !== p.value || (typeof p.check === 'function' && p.check() === false)) throw new Error('service-provision-invalid')
787
+ if (typeof p.value?.health === 'function' && badHealth(await p.value.health())) throw new Error('service-health-failed')
788
+ svcMap.set(p.name, p)
789
+ if (safeEnum.test(p.name)) {
790
+ const ms = listMethods(p.value)
791
+ if (ms.length > 0) { svcMethods.set(p.name, new Set(ms)); for (const m of ms) allMethods.add(m) }
792
+ }
793
+ }
794
+ schemas.push({ name: 'service_lifecycle_probe', parameters: { type: 'object', properties: {
795
+ check: { type: 'string', enum: ['status', 'health', 'provisions'] }, service: { type: 'string' },
796
+ }, additionalProperties: false } })
797
+ const svcNames = [...svcMethods.keys()].slice(0, 16), mNames = [...allMethods].slice(0, 16)
798
+ if (svcNames.length > 0 && mNames.length > 0) {
799
+ schemas.push({ name: 'service_method_probe', parameters: { type: 'object', properties: {
800
+ service: { type: 'string', enum: svcNames }, method: { type: 'string', enum: mNames }, input: { type: 'object', additionalProperties: true },
801
+ }, required: ['service', 'method'], additionalProperties: false } })
802
+ }
803
+ for (const s of toolSchemas) if (schemas.length < 64 && !schemas.some(x => x.name === s.name)) schemas.push(s)
804
+ var invokeNonTool = async call => {
805
+ if (call.toolName === 'service_lifecycle_probe') {
806
+ const filter = typeof call.arguments?.service === 'string' ? call.arguments.service : undefined
807
+ if (filter && !svcMap.has(filter)) throw new Error('unknown-service')
808
+ const health = []
809
+ for (const [n, p] of svcMap) {
810
+ if (filter && n !== filter) continue
811
+ if (unwrap(ctx.get(n)) !== p.value || (typeof p.check === 'function' && p.check() === false)) throw new Error('service-provision-invalid')
812
+ const h = typeof p.value?.health === 'function' ? await p.value.health() : { ready: true }
813
+ if (badHealth(h)) throw new Error('service-health-failed')
814
+ health.push({ service: n, health: h })
815
+ }
816
+ const value = { kind: 'service', active: fiber.state === 2, provisions: providedNames, disposables: fiber._disposables?.length ?? 0, health }
817
+ return { isError: false, value, content: [{ type: 'text', text: JSON.stringify(value) }] }
818
+ }
819
+ if (call.toolName === 'service_method_probe') {
820
+ const s = call.arguments?.service, m = call.arguments?.method
821
+ if (typeof s !== 'string' || typeof m !== 'string' || !svcMethods.get(s)?.has(m)) throw new Error('invalid-service-method')
822
+ const res = await svcMap.get(s).value[m](call.arguments?.input)
823
+ const value = { kind: 'service', service: s, method: m, result: res ?? null }
824
+ return { isError: false, value, content: [{ type: 'text', text: JSON.stringify(value) }] }
825
+ }
826
+ return undefined
827
+ }
828
+ } else if (effectiveKind === 'channel') {
829
+ const exported = [mod.adapter, mod.channel, target?.adapter, target?.channel].filter(Boolean)
830
+ if (channelAdapters.size < 1 && channelProvisions.length < 1 && exported.length < 1) throw new Error('invalid-channel-plugin')
831
+ for (const a of [...channelAdapters, ...channelProvisions.map(p => p.value), ...exported]) if (!checkAdapter(a)) throw new Error('invalid-channel-plugin')
832
+ for (const p of provisions) if (typeof p.value?.health === 'function' && badHealth(await p.value.health())) throw new Error('channel-unhealthy')
833
+ schemas.push({ name: 'channel_readiness_probe', parameters: { type: 'object', properties: {
834
+ check: { type: 'string', enum: ['adapters', 'capabilities', 'health'] }, channel: { type: 'string' },
835
+ }, additionalProperties: false } })
836
+ for (const s of toolSchemas) if (schemas.length < 64 && !schemas.some(x => x.name === s.name)) schemas.push(s)
837
+ var invokeNonTool = async call => {
838
+ if (call.toolName !== 'channel_readiness_probe') return undefined
839
+ const ch = typeof call.arguments?.channel === 'string' ? call.arguments.channel : undefined
840
+ const adapters = [...channelAdapters, ...channelProvisions.map(p => p.value), ...exported].filter(a => !ch || a.channel === ch).map(a => ({ channel: a.channel, account: a.account, capabilities: a.capabilities }))
841
+ if (ch && adapters.length === 0) throw new Error('unknown-channel')
842
+ const services = []
843
+ for (const p of provisions) if (typeof p.value?.health === 'function') {
844
+ const h = await p.value.health()
845
+ if (badHealth(h)) throw new Error('channel-unhealthy')
846
+ services.push({ service: p.name, health: h })
847
+ }
848
+ const value = { kind: 'channel', ready: true, adapters, services }
849
+ return { isError: false, value, content: [{ type: 'text', text: JSON.stringify(value) }] }
850
+ }
851
+ } else {
852
+ if (pkg.clientExportMissing) throw new Error('invalid-ui-plugin')
853
+ if (typertContributions.size < 1 && !uiExports && !pkg.hasClientExport) throw new Error('invalid-ui-plugin')
854
+ schemas.push({ name: 'ui_declaration_probe', parameters: { type: 'object', properties: {
855
+ check: { type: 'string', enum: ['contributions', 'routes', 'settings'] }, section: { type: 'string' },
856
+ }, additionalProperties: false } })
857
+ for (const s of toolSchemas) if (schemas.length < 64 && !schemas.some(x => x.name === s.name)) schemas.push(s)
858
+ var invokeNonTool = async call => {
859
+ if (call.toolName !== 'ui_declaration_probe') return undefined
860
+ const contribs = [...typertContributions].map(c => ({ package: c.package, face: c.face ?? null, schemas: Object.keys(c.schemas ?? {}), invocations: Object.keys(c.invocations ?? {}).length }))
861
+ const value = { kind: 'ui', ready: true, contributions: contribs, hasClientExport: Boolean(pkg.hasClientExport),
862
+ routes: hasNonEmpty(mod.routes) ? mod.routes : hasNonEmpty(target?.routes) ? target.routes : [],
863
+ sections: hasNonEmpty(mod.sections) ? mod.sections : hasNonEmpty(target?.sections) ? target.sections : [],
864
+ settings: hasNonEmpty(mod.settings) ? mod.settings : hasNonEmpty(target?.settings) ? target.settings : [] }
865
+ return { isError: false, value, content: [{ type: 'text', text: JSON.stringify(value) }] }
866
+ }
867
+ }
868
+ const schemaDigest = createHash('sha256').update(JSON.stringify(schemas)).digest('hex')
869
+ if (request.operation.kind === 'invoke' && request.operation.schemaDigest !== schemaDigest) throw new Error('schema-digest-changed')
870
+ const emitKind = request.pluginKind !== undefined || effectiveKind !== 'tool'
871
+ const kindOut = emitKind ? { pluginKind: effectiveKind } : {}
872
+ if (request.operation.kind === 'discover') result = { wireVersion: 1, status: 'result', ...kindOut, schemas }
873
+ else {
874
+ const calls = []
875
+ const probeNames = new Set(schemas.map(s => s.name))
876
+ for (const call of request.operation.calls) {
877
+ if (!probeNames.has(call.toolName)) throw new Error('unknown-invoked-tool')
878
+ if (effectiveKind !== 'tool' && !toolNames.has(call.toolName)) {
879
+ const res = await invokeNonTool(call)
880
+ calls.push({ id: call.id, toolName: call.toolName, result: res })
881
+ } else {
882
+ const batch = await ctx.tools.execute({
883
+ calls: [{ type: 'tool-call', id: call.id, name: call.toolName, arguments: JSON.stringify(call.arguments) }],
884
+ signal: new AbortController().signal,
885
+ })
886
+ if (!batch || !Array.isArray(batch.results) || batch.results.length !== 1 || !batch.results[0]?.result)
887
+ throw new Error('tool-batch-invalid')
888
+ calls.push({ id: call.id, toolName: call.toolName, result: batch.results[0].result })
889
+ }
890
+ }
891
+ result = { wireVersion: 1, status: 'result', ...kindOut, schemas, calls }
892
+ }
893
+ } catch (error) {
894
+ result = { wireVersion: 1, status: 'unknown', reason: error instanceof Error ? error.message.slice(0, 128) : 'candidate-error' }
895
+ } finally {
896
+ try { if (fiber) await fiber.dispose() } catch { disposed = false }
897
+ if (disposed) {
898
+ if (channelAdapters.size > 0 || typertContributions.size > 0) disposed = false
899
+ for (const svcName of providedNames) if (ctx?.get(svcName) !== undefined) disposed = false
900
+ }
901
+ try { if (ctx) await ctx.fiber.dispose() } catch { disposed = false }
902
+ }
903
+ if (!disposed) result = { wireVersion: 1, status: 'unknown', reason: 'plugin-disposal-unconfirmed' }
904
+ try {
905
+ const output = JSON.stringify(result)
906
+ if (Buffer.byteLength(output) > 60 * 1024) throw new Error('candidate-output-too-large')
907
+ writeSync(3, output + '\n')
908
+ } catch { process.exitCode = 1 }
909
+ DSH_PLUGIN_VERIFIER_CANDIDATE_END */
910
+ //# sourceMappingURL=plugin-behavior-runner.js.map