@dsh-ray/assistant-web-owner 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 (66) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +336 -2
  3. package/bin/dsh-autonomy-doctor.js +33 -0
  4. package/bin/dsh-web-owner-setup.js +33 -0
  5. package/cordis.patch.yml +6 -0
  6. package/lib/autonomy-grants.d.ts +295 -0
  7. package/lib/autonomy-grants.d.ts.map +1 -0
  8. package/lib/autonomy-grants.js +1218 -0
  9. package/lib/autonomy-grants.js.map +1 -0
  10. package/lib/autonomy.d.ts +46 -0
  11. package/lib/autonomy.d.ts.map +1 -0
  12. package/lib/autonomy.js +323 -0
  13. package/lib/autonomy.js.map +1 -0
  14. package/lib/client.d.ts +58 -0
  15. package/lib/client.d.ts.map +1 -0
  16. package/lib/client.js +20016 -0
  17. package/lib/client.js.map +1 -0
  18. package/lib/doctor.d.ts +63 -0
  19. package/lib/doctor.d.ts.map +1 -0
  20. package/lib/doctor.js +745 -0
  21. package/lib/doctor.js.map +1 -0
  22. package/lib/goal-admission.d.ts +94 -0
  23. package/lib/goal-admission.d.ts.map +1 -0
  24. package/lib/goal-admission.js +556 -0
  25. package/lib/goal-admission.js.map +1 -0
  26. package/lib/goal-setup.d.ts +15 -0
  27. package/lib/goal-setup.d.ts.map +1 -0
  28. package/lib/goal-setup.js +145 -0
  29. package/lib/goal-setup.js.map +1 -0
  30. package/lib/host-dsh.d.ts +18 -0
  31. package/lib/host-dsh.d.ts.map +1 -0
  32. package/lib/host-dsh.js +220 -0
  33. package/lib/host-dsh.js.map +1 -0
  34. package/lib/index.d.ts +65 -0
  35. package/lib/index.d.ts.map +1 -0
  36. package/lib/index.js +319 -0
  37. package/lib/index.js.map +1 -0
  38. package/lib/native-client.d.ts +18 -0
  39. package/lib/native-client.d.ts.map +1 -0
  40. package/lib/native-client.js +57 -0
  41. package/lib/native-client.js.map +1 -0
  42. package/lib/notices.d.ts +15 -0
  43. package/lib/notices.d.ts.map +1 -0
  44. package/lib/notices.js +17 -0
  45. package/lib/notices.js.map +1 -0
  46. package/lib/repair-setup.d.ts +50 -0
  47. package/lib/repair-setup.d.ts.map +1 -0
  48. package/lib/repair-setup.js +192 -0
  49. package/lib/repair-setup.js.map +1 -0
  50. package/lib/settings-route.d.ts +7 -0
  51. package/lib/settings-route.d.ts.map +1 -0
  52. package/lib/settings-route.js +38 -0
  53. package/lib/settings-route.js.map +1 -0
  54. package/lib/setup.d.ts +24 -0
  55. package/lib/setup.d.ts.map +1 -0
  56. package/lib/setup.js +601 -0
  57. package/lib/setup.js.map +1 -0
  58. package/lib/typert.d.ts +213 -0
  59. package/lib/typert.d.ts.map +1 -0
  60. package/lib/typert.js +71 -0
  61. package/lib/typert.js.map +1 -0
  62. package/lib/version.d.ts +2 -0
  63. package/lib/version.d.ts.map +1 -0
  64. package/lib/version.js +2 -0
  65. package/lib/version.js.map +1 -0
  66. package/package.json +187 -3
package/lib/setup.js ADDED
@@ -0,0 +1,601 @@
1
+ import { randomUUID } from 'node:crypto';
2
+ import { lstat, mkdir, readFile, rename, rm, writeFile } from 'node:fs/promises';
3
+ import { homedir } from 'node:os';
4
+ import { isAbsolute, join, normalize } from 'node:path';
5
+ import { isDeepStrictEqual } from 'node:util';
6
+ import { preflightAutonomyProfile, prepareAutonomyProfile, validateAutonomyOptions } from './autonomy.js';
7
+ import { canonicalPath, dumpEffectiveProfile, findExactRow, globalDshDatabasePath, mergeConfigMaps, publishedDatabaseDefault, sqliteStateExists, withinDshHome, } from './host-dsh.js';
8
+ import { ensurePrincipalLocally } from '@dsh-ray/assistant-delivery';
9
+ import { isMap, isScalar, isSeq, parseDocument } from 'yaml';
10
+ const key = /^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/u;
11
+ const slugs = ['personal-assistant', 'assistant-delivery', 'assistant-goals', 'assistant-web-owner'];
12
+ function fail(message) { throw new Error(`assistant-web-owner setup: ${message}`); }
13
+ function validate(input) {
14
+ if (input.isolation)
15
+ validateAutonomyOptions(input.isolation);
16
+ if (!key.test(input.profile) || !/^[a-z0-9][a-z0-9-]*$/u.test(input.preset))
17
+ fail('invalid profile or preset');
18
+ for (const value of [input.dshHome, input.workspace]) {
19
+ if (!isAbsolute(value) || value.includes('\0') || value.includes('*'))
20
+ fail('home and workspace must be literal absolute paths');
21
+ }
22
+ }
23
+ function parse(source, label) {
24
+ const document = parseDocument(source.trim() === '' ? '[]' : source, {
25
+ customTags: [{ tag: 'tag:yaml.org,2002:js', resolve: (value) => value }],
26
+ });
27
+ if (document.errors.length > 0 || !isSeq(document.contents))
28
+ fail(`${label} must be an unambiguous YAML sequence`);
29
+ return { document, rows: document.contents };
30
+ }
31
+ function map(value, label) {
32
+ if (!isMap(value))
33
+ fail(`${label} must be a mapping`);
34
+ return value;
35
+ }
36
+ function scopeConfigDatabasePath(options) {
37
+ const { config, explicitConfig, pathKeys, fallback, publishedDefault, label, companion = false, createIfMissing, input, document } = options;
38
+ const current = config.getIn(pathKeys, true);
39
+ const explicit = explicitConfig !== undefined && explicitConfig.hasIn(pathKeys);
40
+ let modified = false;
41
+ const inheritedDefault = !explicit && ((current === undefined && createIfMissing) || publishedDatabaseDefault(current, publishedDefault));
42
+ if (inheritedDefault) {
43
+ if (current !== undefined
44
+ && sqliteStateExists(publishedDefault, companion, fail)
45
+ && canonicalPath(publishedDefault, label, fail) !== canonicalPath(fallback, label, fail)) {
46
+ fail(`${label} published default contains existing state; perform an offline migration to ${fallback} before setup`);
47
+ }
48
+ config.setIn(pathKeys, document.createNode(fallback));
49
+ modified = true;
50
+ }
51
+ const updated = config.getIn(pathKeys, true);
52
+ if (updated !== undefined) {
53
+ withinDshHome(literalPath(updated, input, label), input.dshHome, label, fail);
54
+ }
55
+ return modified;
56
+ }
57
+ export function literalPath(node, input, label) {
58
+ if (!isScalar(node) || typeof node.value !== 'string')
59
+ fail(`${label} must be an absolute path`);
60
+ let value = node.value;
61
+ if (node.tag === 'tag:yaml.org,2002:js') {
62
+ // Recognize only the published path helper. Never evaluate arbitrary YAML JS.
63
+ const match = /^dshHomePath\(['"]([^'"\n]+)['"]\)$/u.exec(value);
64
+ if (match === null || isAbsolute(match[1]) || match[1].split('/').includes('..'))
65
+ fail(`${label} needs a literal path or dshHomePath`);
66
+ value = join(input.dshHome, match[1]);
67
+ }
68
+ else if (node.tag !== undefined && node.tag !== 'tag:yaml.org,2002:str')
69
+ fail(`${label} has an unsupported tag`);
70
+ if (!isAbsolute(value) || value.includes('\0') || value.includes('*'))
71
+ fail(`${label} must be a literal absolute path`);
72
+ return normalize(value);
73
+ }
74
+ /** Materialize complete Cordis config replacements while retaining YAML tags and custom siblings. */
75
+ export function prepareWebOwnerProfile(input, source, effectiveSource) {
76
+ validate(input);
77
+ const target = parse(source, 'profile patch');
78
+ const effective = parse(effectiveSource, 'effective profile');
79
+ const configs = new Map();
80
+ const explicitConfigs = new Map();
81
+ for (const slug of slugs) {
82
+ const inherited = findExactRow(effective.rows, slug, { required: true }, fail);
83
+ const existing = findExactRow(target.rows, slug, { required: false }, fail);
84
+ const existingConfig = existing?.has('config') ? map(existing.get('config', true), slug) : undefined;
85
+ explicitConfigs.set(slug, existingConfig);
86
+ const base = inherited.has('config') ? map(inherited.get('config', true), slug) : target.document.createNode({});
87
+ const config = existingConfig !== undefined ? mergeConfigMaps(base, existingConfig, fail) : map(base.clone(), slug);
88
+ const destination = existing ?? target.document.createNode({ id: `dsh-ray-${slug}`, name: `@dsh-ray/${slug}` });
89
+ destination.set('config', config);
90
+ if (existing === undefined)
91
+ target.rows.add(destination);
92
+ configs.set(slug, config);
93
+ }
94
+ const principal = { channel: 'web', account: input.profile, tenant: 'local', user: 'operator' };
95
+ const owner = configs.get('assistant-web-owner');
96
+ const identity = { account: principal.account, tenant: principal.tenant, user: principal.user };
97
+ if (owner.has('principal')) {
98
+ const old = map(owner.get('principal', true), 'existing Web identity');
99
+ for (const [field, value] of Object.entries(identity))
100
+ if (old.get(field) !== value)
101
+ fail('existing Web owner identity differs; explicit owner migration is required');
102
+ }
103
+ for (const [field, value] of Object.entries({ workspace: input.workspace, preset: input.preset })) {
104
+ if (owner.has(field) && owner.get(field) !== value)
105
+ fail(`existing Web ${field} differs; preserve the existing scope or migrate explicitly`);
106
+ owner.set(field, value);
107
+ }
108
+ owner.set('principal', target.document.createNode(identity));
109
+ if (!owner.has('maxExecutionMs'))
110
+ owner.set('maxExecutionMs', 300_000);
111
+ const delivery = configs.get('assistant-delivery');
112
+ const databasePath = literalPath(delivery.get('databasePath', true), input, 'Delivery databasePath');
113
+ withinDshHome(databasePath, input.dshHome, 'Delivery databasePath', fail);
114
+ withinDshHome(literalPath(delivery.get('spoolPath', true), input, 'Delivery spoolPath'), input.dshHome, 'Delivery spoolPath', fail);
115
+ // YAMLMap.set(string) mutates an existing scalar and retains its !!js tag.
116
+ // A selected literal must replace that node, or Loader evaluates /path as JS.
117
+ delivery.set('defaultWorkspace', target.document.createNode(input.workspace));
118
+ delivery.set('defaultAgentPreset', target.document.createNode(input.preset));
119
+ const goals = configs.get('assistant-goals');
120
+ scopeConfigDatabasePath({
121
+ config: goals,
122
+ explicitConfig: explicitConfigs.get('assistant-goals'),
123
+ pathKeys: ['databasePath'],
124
+ fallback: join(input.dshHome, 'assistant-goals', `${input.profile}.sqlite`),
125
+ publishedDefault: globalDshDatabasePath('assistant-goals'),
126
+ label: 'Goals databasePath',
127
+ createIfMissing: true,
128
+ input,
129
+ document: target.document,
130
+ });
131
+ const personal = configs.get('personal-assistant');
132
+ for (const sibling of ['personalMemory', 'personalWiki', 'assistantAutomations'])
133
+ map(personal.get(sibling, true), sibling);
134
+ const policy = map(personal.get('assistantPolicy', true), 'assistantPolicy');
135
+ withinDshHome(literalPath(policy.get('databasePath', true), input, 'Policy databasePath'), input.dshHome, 'Policy databasePath', fail);
136
+ let rules = policy.get('rules', true);
137
+ if (rules === undefined || (isScalar(rules) && rules.value === null)) {
138
+ rules = target.document.createNode([]);
139
+ policy.set('rules', rules);
140
+ }
141
+ if (!isSeq(rules))
142
+ fail('Policy rules must be a sequence');
143
+ const principalId = `web/${input.profile}/local/operator`;
144
+ const managed = [
145
+ { id: `dsh-ray-web-${input.profile}-ingest`, effect: 'allow', subject: { kind: 'external', id: principalId }, actions: ['ingest'], resource: { kind: 'message', id: '*' }, context: { initiators: ['external'] } },
146
+ { id: `dsh-ray-web-${input.profile}-capability`, effect: 'allow', subject: { kind: 'agent', id: input.preset, workspace: input.workspace, principal: principalId }, actions: ['*'], resource: { kind: '*', id: '*' }, context: { initiators: ['external'] } },
147
+ ];
148
+ for (const rule of managed) {
149
+ const matches = rules.items.filter(item => isMap(item) && item.get('id') === rule.id);
150
+ if (matches.length > 1)
151
+ fail(`duplicate managed rule ${rule.id}`);
152
+ if (matches[0] !== undefined) {
153
+ // Customizations are not silently overwritten, including edited allow/deny rules.
154
+ if (!isDeepStrictEqual(matches[0].toJSON(), rule))
155
+ fail(`managed rule ${rule.id} was customized; review it before setup`);
156
+ }
157
+ else
158
+ rules.add(target.document.createNode(rule));
159
+ }
160
+ const optionalStateRows = [
161
+ { slug: 'assistant-proactive', pathKeys: ['databasePath'], label: 'Proactive databasePath', subdir: 'assistant-proactive', filename: `${input.profile}.sqlite`, companion: true, createIfMissing: true, publishedSlug: 'assistant-proactive' },
162
+ { slug: 'assistant-dreaming', pathKeys: ['databasePath'], label: 'Dreaming databasePath', subdir: 'assistant-dreaming', filename: `${input.profile}.sqlite`, companion: false, createIfMissing: true, publishedSlug: 'assistant-dreaming' },
163
+ { slug: 'assistant-memory-learning', pathKeys: ['databasePath'], label: 'Memory learning databasePath', subdir: 'assistant-memory-learning', filename: `${input.profile}.sqlite`, companion: false, createIfMissing: true, publishedSlug: 'assistant-memory-learning' },
164
+ { slug: 'assistant-association', pathKeys: ['databasePath'], label: 'Association databasePath', subdir: 'assistant-association', filename: `${input.profile}.sqlite`, companion: false, createIfMissing: true, publishedSlug: 'assistant-association' },
165
+ { slug: 'assistant-work-items', pathKeys: ['databasePath'], label: 'Work-items databasePath', subdir: 'assistant-work-items', filename: `${input.profile}.sqlite`, companion: false, createIfMissing: true, publishedSlug: 'assistant-work-items' },
166
+ { slug: 'assistant-growth-driver', pathKeys: ['usageLearning', 'databasePath'], label: 'Growth usage databasePath', subdir: 'assistant-growth-driver', filename: `${input.profile}-usage.sqlite`, companion: false, createIfMissing: false, publishedSlug: 'assistant-growth-driver' },
167
+ ];
168
+ for (const spec of optionalStateRows) {
169
+ const inherited = findExactRow(effective.rows, spec.slug, { required: false, allowDisabled: true }, fail);
170
+ if (inherited === undefined)
171
+ continue;
172
+ const existing = findExactRow(target.rows, spec.slug, { required: false, allowDisabled: true }, fail);
173
+ const existingConfig = existing?.has('config') ? map(existing.get('config', true), spec.slug) : undefined;
174
+ const base = inherited.has('config') ? map(inherited.get('config', true), spec.slug) : target.document.createNode({});
175
+ const config = existingConfig !== undefined ? mergeConfigMaps(base, existingConfig, fail) : map(base.clone(), spec.slug);
176
+ const createMissing = spec.slug === 'assistant-growth-driver'
177
+ ? spec.createIfMissing || config.getIn(['usageLearning', 'enabled']) === true
178
+ : spec.createIfMissing;
179
+ const modified = scopeConfigDatabasePath({
180
+ config,
181
+ explicitConfig: existingConfig,
182
+ pathKeys: spec.pathKeys,
183
+ fallback: join(input.dshHome, spec.subdir, spec.filename),
184
+ publishedDefault: globalDshDatabasePath(spec.publishedSlug),
185
+ label: spec.label,
186
+ companion: spec.companion,
187
+ createIfMissing: createMissing,
188
+ input,
189
+ document: target.document,
190
+ });
191
+ if (spec.slug === 'assistant-work-items' && config.has('workRoot')) {
192
+ withinDshHome(literalPath(config.get('workRoot', true), input, 'Work-items workRoot'), input.dshHome, 'Work-items workRoot', fail);
193
+ }
194
+ if (existing !== undefined || modified) {
195
+ const destination = existing ?? target.document.createNode({ id: `dsh-ray-${spec.slug}`, name: `@dsh-ray/${spec.slug}` });
196
+ destination.set('config', config);
197
+ if (existing === undefined)
198
+ target.rows.add(destination);
199
+ }
200
+ }
201
+ return { patch: target.document.toString({ lineWidth: 0 }), databasePath, principal };
202
+ }
203
+ async function readPatch(path) {
204
+ try {
205
+ if (!(await lstat(path)).isFile())
206
+ fail('profile patch must be a regular file, not a symlink');
207
+ return await readFile(path, 'utf8');
208
+ }
209
+ catch (error) {
210
+ if (error.code === 'ENOENT')
211
+ return '';
212
+ throw error;
213
+ }
214
+ }
215
+ /** Local offline setup. A failed YAML commit may leave a newly paired identity; retry preserves its lineage. */
216
+ export async function configureWebOwner(input, effectiveSource) {
217
+ validate(input);
218
+ const directory = join(input.dshHome, 'profiles', input.profile);
219
+ if (!(await lstat(directory)).isDirectory())
220
+ fail('install the target profile first');
221
+ const lock = join(directory, '.assistant-web-owner-setup.lock');
222
+ try {
223
+ await mkdir(lock, { mode: 0o700 });
224
+ }
225
+ catch (error) {
226
+ if (error.code === 'EEXIST')
227
+ fail('another setup holds the profile lock; inspect the previous setup before retrying');
228
+ throw error;
229
+ }
230
+ const path = join(directory, 'cordis.patch.yml');
231
+ const temporary = `${path}.${randomUUID()}.tmp`;
232
+ try {
233
+ const before = await readPatch(path);
234
+ const plan = prepareWebOwnerProfile(input, before, effectiveSource);
235
+ await mkdir(input.workspace, { recursive: true });
236
+ let resolvedIsolation;
237
+ if (input.isolation) {
238
+ const preflight = preflightAutonomyProfile({ ...input, isolation: input.isolation }, plan.patch, effectiveSource);
239
+ const resources = await import('@dsh-ray/assistant-isolation/native-resources');
240
+ const metadata = JSON.parse(await readFile(new URL('../package.json', import.meta.url), 'utf8'));
241
+ if (typeof metadata.version !== 'string' || !/^[0-9]+\.[0-9]+\.[0-9]+(?:-[A-Za-z0-9.-]+)?$/u.test(metadata.version))
242
+ fail('invalid installed package version');
243
+ const selected = input.isolation.source ?? { kind: 'official-tag' };
244
+ const source = await resources.freezeLinuxRuntimeSource({ ...selected, version: metadata.version });
245
+ const preparation = { dshHome: input.dshHome, profile: input.profile, source };
246
+ const parsed = parse(preflight, 'autonomy preflight');
247
+ const isolationRow = parsed.rows.items.find(item => isMap(item) && item.get('id') === 'dsh-ray-assistant-isolation');
248
+ const hasExisting = map(isolationRow.get('config', true), 'Isolation config').has('linux');
249
+ if (!hasExisting)
250
+ await resources.prepareLinuxRuntime(preparation);
251
+ const prepared = await resources.readLinuxRuntime(preparation);
252
+ const cgroupRoots = await resources.discoverLinuxCgroupRoots();
253
+ resolvedIsolation = { backend: 'linux-native', linux: { runtime: prepared.runtime, cgroupRoots },
254
+ maxRuns: input.isolation.maxRuns, leaseMs: input.isolation.leaseMs, maxTotalDurationMs: input.isolation.maxTotalDurationMs };
255
+ // Reject descriptor/source/root drift before any owner pairing or grant write.
256
+ const complete = prepareAutonomyProfile({ ...input, isolation: resolvedIsolation }, plan.patch, effectiveSource);
257
+ await resources.probeLinuxIsolationRuntime(resolvedIsolation.linux);
258
+ // Re-read the immutable receipt after the disposable probe.
259
+ if (!isDeepStrictEqual((await resources.readLinuxRuntime(preparation)).runtime, prepared.runtime))
260
+ fail('Linux runtime changed during setup probe');
261
+ plan.patch = complete;
262
+ }
263
+ const owner = ensurePrincipalLocally({ databasePath: plan.databasePath, principal: plan.principal });
264
+ if (resolvedIsolation)
265
+ plan.patch = prepareAutonomyProfile({ ...input, isolation: resolvedIsolation }, plan.patch, effectiveSource, owner);
266
+ if (plan.patch === before)
267
+ return path;
268
+ await writeFile(temporary, plan.patch, { encoding: 'utf8', mode: 0o600, flag: 'wx' });
269
+ if (await readPatch(path) !== before)
270
+ fail('profile changed during setup; retry with its latest configuration');
271
+ await rename(temporary, path);
272
+ return path;
273
+ }
274
+ finally {
275
+ await rm(temporary, { force: true });
276
+ await rm(lock, { recursive: true, force: true });
277
+ }
278
+ }
279
+ export async function runWebOwnerSetup(argv = process.argv.slice(2)) {
280
+ if (argv.includes('--help') || argv.includes('-h')) {
281
+ process.stdout.write('Usage: dsh-web-owner-setup --profile <name> --workspace <absolute-path> [--preset standard] [--dsh-home <absolute-path>] [--isolation-backend linux-native] [--isolation-source-repository <absolute-committed-repository>] [--isolation-max-runs 20 --isolation-lease-ms 3600000 --isolation-runtime-ms 600000]\nAutonomy setup: [--autonomy-setup] [--enable-memory-learning|--disable-memory-learning] [--enable-dreaming|--pause-dreaming|--retire-dreaming|--disable-dreaming] [--enable-growth|--disable-growth] [--work-item-experiences|--no-work-item-experiences] [--usage-learning] [--model-provider <provider> --model-id <model> [--reasoning-effort <level>]] [--budget-tier <conservative|balanced>] [--daily-budget <n>] [--max-extractions <n>] [--lease-days <1..365>] [--session-id <id>] [--dry-run] [--json]\nGoal setup: use --list-goal-sessions to show real idle owner Sessions, or --goal-admission <private-absolute-task.json> [--session-id <existing-idle-session>]. Without --session-id, setup selects the sole matching idle Session and otherwise prints candidates.\nRepair setup: --repair-admission <private-absolute-json> installs preconfigured finite repair profiles after checking the current owner scope, owner route, Goals execution budget, exact model routes, Skills holdouts and Verifier profiles. It creates no Goal, Session, credential, grant, or unlimited authority.\nIsolation is linux-native only; Docker isolation was removed. Initializes one local Web owner without replacing existing owner authority. Stop the target Host before setup; configuration changes require restart.\n');
282
+ return;
283
+ }
284
+ const input = { dshHome: process.env.DSH_HOME ?? join(homedir(), '.dsh'), profile: 'web', workspace: '', preset: 'standard' };
285
+ const limits = { maxRuns: 20, leaseMs: 3_600_000, maxTotalDurationMs: 600_000 };
286
+ let isolationBackend;
287
+ let isolationRepository;
288
+ let isolated = false;
289
+ let goalAdmission;
290
+ let repairAdmission;
291
+ let sessionId;
292
+ let listGoalSessions = false;
293
+ let explicitAutonomyFlag = false;
294
+ let autonomyJson = false;
295
+ let autonomyDryRun = false;
296
+ let autonomyMemoryLearning;
297
+ let autonomyDreaming;
298
+ let autonomyGrowth;
299
+ let autonomyUsageLearning;
300
+ let autonomyWorkItemExperiences;
301
+ let autonomyModelProvider;
302
+ let autonomyModelId;
303
+ let autonomyReasoningEffort;
304
+ let autonomyBudgetTier;
305
+ let autonomyDailyBudget;
306
+ let autonomyMaxExtractions;
307
+ let autonomyLeaseDays;
308
+ const numeric = { '--isolation-max-runs': 'maxRuns', '--isolation-lease-ms': 'leaseMs', '--isolation-runtime-ms': 'maxTotalDurationMs' };
309
+ const fields = { '--dsh-home': 'dshHome', '--profile': 'profile', '--workspace': 'workspace', '--preset': 'preset' };
310
+ const autonomyValueFlags = new Set(['--model-provider', '--model-id', '--reasoning-effort', '--budget-tier', '--daily-budget', '--max-extractions', '--lease-days']);
311
+ const jsonRequestedEarly = argv.includes('--json');
312
+ function failSetup(message, code = 1) {
313
+ if (jsonRequestedEarly) {
314
+ process.stdout.write(`${JSON.stringify({ ok: false, error: message })}\n`);
315
+ process.exitCode = code;
316
+ }
317
+ fail(message);
318
+ }
319
+ for (let index = 0; index < argv.length; index++) {
320
+ const option = argv[index];
321
+ if (option === '--list-goal-sessions') {
322
+ listGoalSessions = true;
323
+ continue;
324
+ }
325
+ if (option === '--autonomy-setup') {
326
+ explicitAutonomyFlag = true;
327
+ continue;
328
+ }
329
+ if (option === '--json') {
330
+ autonomyJson = true;
331
+ explicitAutonomyFlag = true;
332
+ continue;
333
+ }
334
+ if (option === '--dry-run') {
335
+ autonomyDryRun = true;
336
+ explicitAutonomyFlag = true;
337
+ continue;
338
+ }
339
+ if (option === '--enable-memory-learning') {
340
+ if (autonomyMemoryLearning === false)
341
+ failSetup('cannot combine --enable-memory-learning and --disable-memory-learning', 2);
342
+ autonomyMemoryLearning = true;
343
+ explicitAutonomyFlag = true;
344
+ continue;
345
+ }
346
+ if (option === '--disable-memory-learning') {
347
+ if (autonomyMemoryLearning === true)
348
+ failSetup('cannot combine --enable-memory-learning and --disable-memory-learning', 2);
349
+ autonomyMemoryLearning = false;
350
+ explicitAutonomyFlag = true;
351
+ continue;
352
+ }
353
+ if (option === '--enable-dreaming') {
354
+ if (autonomyDreaming && autonomyDreaming !== 'enabled')
355
+ failSetup('conflicting dreaming mode flags', 2);
356
+ autonomyDreaming = 'enabled';
357
+ explicitAutonomyFlag = true;
358
+ continue;
359
+ }
360
+ if (option === '--pause-dreaming' || option === '--retire-dreaming') {
361
+ if (autonomyDreaming && autonomyDreaming !== 'paused')
362
+ failSetup('conflicting dreaming mode flags', 2);
363
+ autonomyDreaming = 'paused';
364
+ explicitAutonomyFlag = true;
365
+ continue;
366
+ }
367
+ if (option === '--disable-dreaming') {
368
+ if (autonomyDreaming && autonomyDreaming !== 'disabled')
369
+ failSetup('conflicting dreaming mode flags', 2);
370
+ autonomyDreaming = 'disabled';
371
+ explicitAutonomyFlag = true;
372
+ continue;
373
+ }
374
+ if (option === '--enable-growth') {
375
+ if (autonomyGrowth === false)
376
+ failSetup('cannot combine --enable-growth and --disable-growth', 2);
377
+ autonomyGrowth = true;
378
+ explicitAutonomyFlag = true;
379
+ continue;
380
+ }
381
+ if (option === '--disable-growth') {
382
+ if (autonomyGrowth === true)
383
+ failSetup('cannot combine --enable-growth and --disable-growth', 2);
384
+ autonomyGrowth = false;
385
+ explicitAutonomyFlag = true;
386
+ continue;
387
+ }
388
+ if (option === '--usage-learning') {
389
+ autonomyUsageLearning = true;
390
+ explicitAutonomyFlag = true;
391
+ continue;
392
+ }
393
+ if (option === '--work-item-experiences') {
394
+ if (autonomyWorkItemExperiences === false)
395
+ failSetup('cannot combine --work-item-experiences and --no-work-item-experiences', 2);
396
+ autonomyWorkItemExperiences = true;
397
+ explicitAutonomyFlag = true;
398
+ continue;
399
+ }
400
+ if (option === '--no-work-item-experiences') {
401
+ if (autonomyWorkItemExperiences === true)
402
+ failSetup('cannot combine --work-item-experiences and --no-work-item-experiences', 2);
403
+ autonomyWorkItemExperiences = false;
404
+ explicitAutonomyFlag = true;
405
+ continue;
406
+ }
407
+ if (!(option in fields) && !['--isolation-backend', '--isolation-source-repository', '--goal-admission', '--repair-admission', '--session-id'].includes(option) && !(option in numeric) && !autonomyValueFlags.has(option)) {
408
+ failSetup(`unknown option ${option}`, 2);
409
+ }
410
+ const value = argv[++index];
411
+ if (value === undefined || value.startsWith('--'))
412
+ failSetup(`${option} requires a value`, 2);
413
+ if (option === '--goal-admission')
414
+ goalAdmission = value;
415
+ else if (option === '--repair-admission')
416
+ repairAdmission = value;
417
+ else if (option === '--session-id')
418
+ sessionId = value;
419
+ else if (option === '--model-provider') {
420
+ autonomyModelProvider = value;
421
+ explicitAutonomyFlag = true;
422
+ }
423
+ else if (option === '--model-id') {
424
+ autonomyModelId = value;
425
+ explicitAutonomyFlag = true;
426
+ }
427
+ else if (option === '--reasoning-effort') {
428
+ if (!['none', 'minimal', 'low', 'medium', 'high', 'xhigh'].includes(value))
429
+ failSetup(`invalid --reasoning-effort '${value}'`, 2);
430
+ autonomyReasoningEffort = value;
431
+ explicitAutonomyFlag = true;
432
+ }
433
+ else if (option === '--budget-tier') {
434
+ if (value !== 'conservative' && value !== 'balanced')
435
+ failSetup(`--budget-tier must be conservative or balanced`, 2);
436
+ autonomyBudgetTier = value;
437
+ explicitAutonomyFlag = true;
438
+ }
439
+ else if (option === '--daily-budget') {
440
+ if (!/^[1-9][0-9]*$/.test(value))
441
+ failSetup('--daily-budget requires a positive integer', 2);
442
+ autonomyDailyBudget = Number(value);
443
+ explicitAutonomyFlag = true;
444
+ }
445
+ else if (option === '--max-extractions') {
446
+ if (!/^[1-9][0-9]*$/.test(value))
447
+ failSetup('--max-extractions requires a positive integer', 2);
448
+ autonomyMaxExtractions = Number(value);
449
+ explicitAutonomyFlag = true;
450
+ }
451
+ else if (option === '--lease-days') {
452
+ if (!/^[1-9][0-9]*$/.test(value) || Number(value) > 365)
453
+ failSetup('--lease-days requires an integer between 1 and 365', 2);
454
+ autonomyLeaseDays = Number(value);
455
+ explicitAutonomyFlag = true;
456
+ }
457
+ else if (option === '--isolation-backend') {
458
+ isolationBackend = value;
459
+ isolated = true;
460
+ }
461
+ else if (option === '--isolation-source-repository') {
462
+ isolationRepository = value;
463
+ isolated = true;
464
+ }
465
+ else if (option in numeric) {
466
+ if (!/^[1-9][0-9]*$/.test(value))
467
+ failSetup(`${option} requires a positive integer`, 2);
468
+ limits[numeric[option]] = Number(value);
469
+ isolated = true;
470
+ }
471
+ else
472
+ input[fields[option]] = value;
473
+ }
474
+ if (isolated) {
475
+ // Docker isolation was removed; isolated setup is linux-native only. An
476
+ // explicit backend other than linux-native fails rather than silently
477
+ // selecting a different execution boundary.
478
+ const backend = isolationBackend ?? 'linux-native';
479
+ if (backend !== 'linux-native')
480
+ failSetup('invalid isolation backend; Docker isolation was removed', 2);
481
+ input.isolation = { ...limits, backend: 'linux-native', ...(isolationRepository === undefined ? {} : { source: { kind: 'local-head', repository: isolationRepository } }) };
482
+ }
483
+ const autonomyMode = explicitAutonomyFlag;
484
+ if (autonomyMode && (listGoalSessions || goalAdmission !== undefined || repairAdmission !== undefined)) {
485
+ failSetup('--autonomy-setup cannot be combined with goal admission, repair admission, or --list-goal-sessions', 2);
486
+ }
487
+ if (autonomyMode) {
488
+ if (!key.test(input.profile) || !/^[a-z0-9][a-z0-9-]*$/u.test(input.preset))
489
+ failSetup('invalid profile or preset', 2);
490
+ if (!isAbsolute(input.dshHome) || input.dshHome.includes('\0') || input.dshHome.includes('*'))
491
+ failSetup('home must be a literal absolute path', 2);
492
+ if (input.workspace !== '')
493
+ validate(input);
494
+ else if (input.isolation)
495
+ failSetup('--isolated requires --workspace', 2);
496
+ }
497
+ else {
498
+ validate(input);
499
+ }
500
+ if (listGoalSessions && (goalAdmission !== undefined || repairAdmission !== undefined || sessionId !== undefined || isolated))
501
+ fail('--list-goal-sessions cannot be combined with setup, goal admission, repair admission, or isolation options');
502
+ if (sessionId !== undefined && goalAdmission === undefined && !autonomyMode)
503
+ fail('--session-id requires --goal-admission');
504
+ if (repairAdmission !== undefined && (goalAdmission !== undefined || sessionId !== undefined || isolated))
505
+ fail('--repair-admission cannot be combined with goal admission, session selection, or isolation options');
506
+ const readEffectiveSource = () => dumpEffectiveProfile(input.dshHome, input.profile, fail, 'could not read the effective DSH profile; check installed bundles and dsh --dump-config');
507
+ if (autonomyMode) {
508
+ try {
509
+ let basePath;
510
+ if (input.workspace !== '') {
511
+ if (autonomyDryRun)
512
+ failSetup('--dry-run cannot be combined with --workspace initial setup', 2);
513
+ const effective = await readEffectiveSource();
514
+ basePath = await configureWebOwner(input, effective);
515
+ }
516
+ const autonomyInput = {
517
+ dshHome: input.dshHome,
518
+ profile: input.profile,
519
+ ...(input.workspace !== '' ? { workspace: input.workspace, preset: input.preset } : {}),
520
+ ...(sessionId !== undefined ? { sessionId } : {}),
521
+ ...(autonomyMemoryLearning !== undefined ? { memoryLearning: autonomyMemoryLearning } : {}),
522
+ ...(autonomyDreaming !== undefined ? { dreaming: autonomyDreaming } : {}),
523
+ ...(autonomyGrowth !== undefined ? { growth: autonomyGrowth } : {}),
524
+ ...(autonomyUsageLearning !== undefined ? { usageLearning: autonomyUsageLearning } : {}),
525
+ ...(autonomyWorkItemExperiences !== undefined ? { workItemExperiences: autonomyWorkItemExperiences } : {}),
526
+ ...(autonomyModelProvider !== undefined ? { modelProvider: autonomyModelProvider } : {}),
527
+ ...(autonomyModelId !== undefined ? { modelId: autonomyModelId } : {}),
528
+ ...(autonomyReasoningEffort !== undefined ? { reasoningEffort: autonomyReasoningEffort } : {}),
529
+ ...(autonomyBudgetTier !== undefined ? { budgetTier: autonomyBudgetTier } : {}),
530
+ ...(autonomyDailyBudget !== undefined ? { dailyBudget: autonomyDailyBudget } : {}),
531
+ ...(autonomyMaxExtractions !== undefined ? { memoryMaxExtractions: autonomyMaxExtractions } : {}),
532
+ ...(autonomyLeaseDays !== undefined ? { leaseDays: autonomyLeaseDays } : {}),
533
+ dryRun: autonomyDryRun,
534
+ };
535
+ const { applyWebOwnerAutonomySetup } = await import('./autonomy-grants.js');
536
+ const result = await applyWebOwnerAutonomySetup(autonomyInput, {
537
+ readEffectiveSource: (home, prof) => dumpEffectiveProfile(home, prof, (msg) => { throw new Error(`assistant-web-owner setup: ${msg}`); }, 'could not read the effective DSH profile; check installed bundles and dsh --dump-config'),
538
+ });
539
+ if (autonomyJson) {
540
+ const jsonPayload = {
541
+ ok: result.ok,
542
+ dshHome: result.dshHome,
543
+ profile: result.profile,
544
+ dryRun: result.dryRun,
545
+ applied: result.applied,
546
+ patchPath: result.patchPath,
547
+ ...(basePath ? { baseSetupPath: basePath } : {}),
548
+ owner: result.owner,
549
+ modelRoute: result.modelRoute,
550
+ budgetTier: result.budgetTier,
551
+ leaseDays: result.leaseDays,
552
+ expiresAt: result.expiresAt,
553
+ enabled: result.enabled,
554
+ policyIds: result.policyIds,
555
+ prerequisites: result.prerequisites,
556
+ };
557
+ process.stdout.write(`${JSON.stringify(jsonPayload)}\n`);
558
+ return;
559
+ }
560
+ process.stdout.write(`Web owner RSI autonomy ${result.dryRun ? 'previewed (dry-run)' : 'configured'} for ${result.profile}: ${result.patchPath}\n`
561
+ + `Owner route: ${result.owner.authorityId} (${result.owner.principalId}); model: ${result.modelRoute.provider}/${result.modelRoute.model}; tier: ${result.budgetTier}; lease: ${result.leaseDays}d.\n`
562
+ + `Enabled: memoryLearning=${result.enabled.memoryLearning}, dreaming=${result.enabled.dreaming}, growth=${result.enabled.growth}, usageLearning=${result.enabled.usageLearning}, workItemExperiences=${result.enabled.workItemExperiences}.\n`);
563
+ return;
564
+ }
565
+ catch (error) {
566
+ const message = error instanceof Error ? error.message : String(error);
567
+ if (autonomyJson) {
568
+ process.stdout.write(`${JSON.stringify({ ok: false, error: message })}\n`);
569
+ process.exitCode = 1;
570
+ return;
571
+ }
572
+ throw error;
573
+ }
574
+ }
575
+ const effective = await readEffectiveSource();
576
+ if (listGoalSessions) {
577
+ const { listGoalAdmissionSessions } = await import('./goal-setup.js');
578
+ const sessions = await listGoalAdmissionSessions(input, effective);
579
+ process.stdout.write(sessions.length === 0 ? 'No matching idle Web owner Sessions. Open the native Web UI once; this command never creates a Session.\n' : `Idle Web owner Sessions:\n${sessions.map(id => ` ${id}\n`).join('')}`);
580
+ return;
581
+ }
582
+ if (goalAdmission !== undefined) {
583
+ const { configureGoalAdmission } = await import('./goal-setup.js');
584
+ const result = await configureGoalAdmission(input, effective, goalAdmission, sessionId, readEffectiveSource);
585
+ if (result.repositoryDelivery)
586
+ process.stdout.write(`Repository: ${result.repositoryDelivery.repository}; branch: ${result.repositoryDelivery.branch}. Authorized paths: ${result.repositoryDelivery.paths.join(', ')}. Independent acceptance: ${result.repositoryDelivery.acceptance}. Credential availability and remote GitHub access have not been tested.\n`);
587
+ process.stdout.write(`Goal configuration written: ${result.path}\nAdmission: ${result.admissionId}; Session: ${result.sessionId}. Existing authority and budget are preserved. Restart the target Host. v2 uses the already configured exact provider/model route; v1 retains deepseek-goal-metered. Model connectivity and runtime admission have not been tested.\n`);
588
+ return;
589
+ }
590
+ if (repairAdmission !== undefined) {
591
+ const { configureRepairAdmission } = await import('./repair-setup.js');
592
+ const result = await configureRepairAdmission(input, effective, repairAdmission, readEffectiveSource);
593
+ process.stdout.write(`Repair configuration written: ${result.path}\nProfile: ${result.id}. Existing authority and budgets were not expanded. Restart the target Host. Configuration completion is not real repair acceptance, canary success, or autonomous-improvement evidence.\n`);
594
+ return;
595
+ }
596
+ const path = await configureWebOwner(input, effective);
597
+ if (input.isolation)
598
+ process.stdout.write(`Isolated execution probe passed. Finite grant: autonomy-${input.profile}. Existing grant expiry and used budget are preserved. GitHub action credentials and autonomous goal verification are not configured by this step.\n`);
599
+ process.stdout.write(`Web owner configured for ${input.profile}: ${path}\nWorkspace: ${input.workspace}; preset: ${input.preset}. Model connectivity and runtime readiness require the installer checks.\n`);
600
+ }
601
+ //# sourceMappingURL=setup.js.map