@dsh-ray/assistant-dreaming 0.0.1-seed.0 → 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.
- package/LICENSE +21 -0
- package/README.md +302 -1
- package/cordis.patch.yml +5 -0
- package/lib/config.d.ts +88 -0
- package/lib/config.d.ts.map +1 -0
- package/lib/config.js +190 -0
- package/lib/config.js.map +1 -0
- package/lib/dream-agent.d.ts +58 -0
- package/lib/dream-agent.d.ts.map +1 -0
- package/lib/dream-agent.js +190 -0
- package/lib/dream-agent.js.map +1 -0
- package/lib/index.d.ts +20 -0
- package/lib/index.d.ts.map +1 -0
- package/lib/index.js +15 -0
- package/lib/index.js.map +1 -0
- package/lib/notify.d.ts +64 -0
- package/lib/notify.d.ts.map +1 -0
- package/lib/notify.js +52 -0
- package/lib/notify.js.map +1 -0
- package/lib/projection.d.ts +36 -0
- package/lib/projection.d.ts.map +1 -0
- package/lib/projection.js +162 -0
- package/lib/projection.js.map +1 -0
- package/lib/runtime.d.ts +69 -0
- package/lib/runtime.d.ts.map +1 -0
- package/lib/runtime.js +835 -0
- package/lib/runtime.js.map +1 -0
- package/lib/store.d.ts +120 -0
- package/lib/store.d.ts.map +1 -0
- package/lib/store.js +462 -0
- package/lib/store.js.map +1 -0
- package/lib/trigger.d.ts +136 -0
- package/lib/trigger.d.ts.map +1 -0
- package/lib/trigger.js +160 -0
- package/lib/trigger.js.map +1 -0
- package/lib/version.d.ts +2 -0
- package/lib/version.d.ts.map +1 -0
- package/lib/version.js +2 -0
- package/lib/version.js.map +1 -0
- package/package.json +117 -4
package/lib/runtime.js
ADDED
|
@@ -0,0 +1,835 @@
|
|
|
1
|
+
import { createHash, randomUUID } from 'node:crypto';
|
|
2
|
+
import { Context, Service } from '@deepseek-ai/cordis';
|
|
3
|
+
import { acceptanceDigest } from '@dsh-ray/task-acceptance-contract';
|
|
4
|
+
import { Config, normalizeConfig } from './config.js';
|
|
5
|
+
import { DreamStore, ownData } from './store.js';
|
|
6
|
+
import { decideTrigger, localDayKey, assignTicket, rollLottery, matchTickets } from './trigger.js';
|
|
7
|
+
import { buildDreamMaterial } from './projection.js';
|
|
8
|
+
import { runDreamAgent } from './dream-agent.js';
|
|
9
|
+
import { enqueueDreamNotification } from './notify.js';
|
|
10
|
+
/** Bounds how many recorded ideas may hold recall tickets per wake. */
|
|
11
|
+
const DREAM_RECORDED_TICKET_LIMIT = 100;
|
|
12
|
+
const EXECUTOR = 'assistant-dreaming-v1';
|
|
13
|
+
const OWNER = 'assistant-dreaming';
|
|
14
|
+
const CATALOG = acceptanceDigest({ executor: EXECUTOR, version: 1 });
|
|
15
|
+
const CORDIS_ORIGINAL = Symbol.for('cordis.original');
|
|
16
|
+
function unwrapService(service) {
|
|
17
|
+
return service?.[CORDIS_ORIGINAL] ?? service;
|
|
18
|
+
}
|
|
19
|
+
/**
|
|
20
|
+
* Terminal outcomes for the Automations Host-executor contract. Success may
|
|
21
|
+
* only carry the literal `none` tuple; a possible side effect must be
|
|
22
|
+
* retryability-unsafe and a pure no-op success must be retryability-safe.
|
|
23
|
+
* Budget reservation/settlement belongs to Automations, never to this
|
|
24
|
+
* executor, so no result here reports a budget settlement.
|
|
25
|
+
*/
|
|
26
|
+
const NO_EFFECT = Object.freeze({
|
|
27
|
+
outcome: 'succeeded', failureClass: 'none', failurePhase: 'none', failureCode: 'none',
|
|
28
|
+
sideEffectState: 'none', retryability: 'safe',
|
|
29
|
+
});
|
|
30
|
+
const EFFECT_OK = Object.freeze({
|
|
31
|
+
outcome: 'succeeded', failureClass: 'none', failurePhase: 'none', failureCode: 'none',
|
|
32
|
+
sideEffectState: 'possible', retryability: 'unsafe',
|
|
33
|
+
});
|
|
34
|
+
function failed(failureClass, failurePhase, failureCode, sideEffectState) {
|
|
35
|
+
const retryability = sideEffectState !== 'none' ? 'unsafe'
|
|
36
|
+
: failureClass === 'configuration' || failureClass === 'policy' || failureClass === 'budget'
|
|
37
|
+
? 'after-intervention' : 'safe';
|
|
38
|
+
return Object.freeze({
|
|
39
|
+
outcome: failureClass === 'cancelled' || failureClass === 'unknown' ? 'unknown' : 'failed',
|
|
40
|
+
failureClass, failurePhase, failureCode, sideEffectState, retryability,
|
|
41
|
+
});
|
|
42
|
+
}
|
|
43
|
+
/**
|
|
44
|
+
* The owner-enabled dreaming runtime. It registers exactly one system-owned
|
|
45
|
+
* `every` automation and, per slot, re-derives the deterministic trigger, then
|
|
46
|
+
* runs one frozen single-tool agent that may only record private ideas. It
|
|
47
|
+
* never notifies unless L1 is explicitly enabled, never adopts, promotes, or
|
|
48
|
+
* writes goals/work-items; with `enabled: false` it opens no database and
|
|
49
|
+
* registers nothing.
|
|
50
|
+
*
|
|
51
|
+
* Scheduling and per-occurrence budget reservation/settlement belong to
|
|
52
|
+
* `assistant-automations`; this executor is a pure consumer of the Host
|
|
53
|
+
* executor contract and never reserves budget itself.
|
|
54
|
+
*/
|
|
55
|
+
export class AssistantDreamingService extends Service {
|
|
56
|
+
static Config = Config;
|
|
57
|
+
static inject = ['assistantAutomations', 'assistantDelivery', 'assistantEvaluation',
|
|
58
|
+
'assistantGoals', 'assistantSkills', 'agents', 'sessions', 'tools'];
|
|
59
|
+
#config;
|
|
60
|
+
#lane;
|
|
61
|
+
#ports;
|
|
62
|
+
#store;
|
|
63
|
+
#flight;
|
|
64
|
+
#active = true;
|
|
65
|
+
#scheduler = 'dormant';
|
|
66
|
+
#lastRunAt = null;
|
|
67
|
+
#lastRunOutcome = null;
|
|
68
|
+
#lastSkipReason = null;
|
|
69
|
+
#unregister;
|
|
70
|
+
#unsubscribeWake;
|
|
71
|
+
#unsubscribeLlm;
|
|
72
|
+
#ideaChangeListeners = new Set();
|
|
73
|
+
#coldStartAnchorAt;
|
|
74
|
+
/**
|
|
75
|
+
* Fresh per-load reconcile nonce for the active transition. Automations
|
|
76
|
+
* caches `automation_system_reconciles` by idempotency key and replays the
|
|
77
|
+
* old receipt without touching the row, so a deterministic key would silently
|
|
78
|
+
* skip reactivation after a retire/reload. A new key per load converges to
|
|
79
|
+
* one active row (the store CAS is idempotent) and appends one audit receipt.
|
|
80
|
+
*/
|
|
81
|
+
#loadNonce = randomUUID();
|
|
82
|
+
constructor(ctx, input = {}) {
|
|
83
|
+
super(ctx, 'assistantDreaming');
|
|
84
|
+
const config = normalizeConfig(input);
|
|
85
|
+
this.#config = config;
|
|
86
|
+
this.#coldStartAnchorAt = Date.now();
|
|
87
|
+
this.#lane = config.scope === null ? 'inactive'
|
|
88
|
+
: acceptanceDigest({ scope: config.scope, databasePath: config.databasePath }).slice(0, 40);
|
|
89
|
+
if (!config.enabled) {
|
|
90
|
+
this.#scheduler = 'dormant';
|
|
91
|
+
return;
|
|
92
|
+
}
|
|
93
|
+
const ports = this.#portsFor(ctx);
|
|
94
|
+
this.#ports = ports;
|
|
95
|
+
this.#store = new DreamStore(config.databasePath, this.#lane);
|
|
96
|
+
try {
|
|
97
|
+
this.#store.interrupt();
|
|
98
|
+
this.#pruneStore(Date.now());
|
|
99
|
+
this.#coldStartAnchorAt = this.#store.ensureColdStartAnchor(this.#coldStartAnchorAt);
|
|
100
|
+
if (config.retired) {
|
|
101
|
+
// Owner pause: keep the ledger and definition, make sure the system
|
|
102
|
+
// automation is paused, and register no executor. This is the supported
|
|
103
|
+
// way to stop dreaming before disabling/uninstalling the bundle.
|
|
104
|
+
ports.automations.reconcileSystem(this.#reconcileInput('paused'));
|
|
105
|
+
this.#scheduler = 'dormant';
|
|
106
|
+
}
|
|
107
|
+
else {
|
|
108
|
+
const prereq = this.#evaluatePrerequisites(ports);
|
|
109
|
+
if (prereq.ok) {
|
|
110
|
+
this.#activateScheduler(ports);
|
|
111
|
+
}
|
|
112
|
+
else {
|
|
113
|
+
this.#scheduler = 'dormant';
|
|
114
|
+
this.#lastSkipReason = prereq.reason;
|
|
115
|
+
if (this.#canReconcilePolicy()) {
|
|
116
|
+
try {
|
|
117
|
+
ports.automations.reconcileSystem(this.#reconcileInput('paused'));
|
|
118
|
+
}
|
|
119
|
+
catch { /* stay dormant until ready */ }
|
|
120
|
+
}
|
|
121
|
+
if (typeof ports.automations.onSchedulerWake === 'function') {
|
|
122
|
+
this.#unsubscribeWake = ports.automations.onSchedulerWake(() => { this.#tryActivateIfReady(ports); });
|
|
123
|
+
}
|
|
124
|
+
if (typeof ctx.on === 'function') {
|
|
125
|
+
const disposeLlm = ctx.on('llm/adapters-updated', (() => { this.#tryActivateIfReady(ports); }));
|
|
126
|
+
this.#unsubscribeLlm = () => { disposeLlm(); };
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
catch (error) {
|
|
132
|
+
// Construction must not leak a registered executor or an open ledger:
|
|
133
|
+
// the Loader keeps this process alive and a retry would otherwise fail
|
|
134
|
+
// with a duplicate executor descriptor. This also covers a failed paused
|
|
135
|
+
// reconcile while the owner is trying to retire.
|
|
136
|
+
this.#active = false;
|
|
137
|
+
this.#scheduler = 'unavailable';
|
|
138
|
+
try {
|
|
139
|
+
this.#unsubscribeLlm?.();
|
|
140
|
+
}
|
|
141
|
+
catch { /* best-effort unload */ }
|
|
142
|
+
this.#unsubscribeLlm = undefined;
|
|
143
|
+
try {
|
|
144
|
+
this.#unsubscribeWake?.();
|
|
145
|
+
}
|
|
146
|
+
catch { /* best-effort unload */ }
|
|
147
|
+
this.#unsubscribeWake = undefined;
|
|
148
|
+
try {
|
|
149
|
+
this.#unregister?.();
|
|
150
|
+
}
|
|
151
|
+
catch { /* best-effort unload */ }
|
|
152
|
+
this.#unregister = undefined;
|
|
153
|
+
try {
|
|
154
|
+
this.#store.interrupt();
|
|
155
|
+
}
|
|
156
|
+
catch { /* store may already be closed */ }
|
|
157
|
+
this.#store.close();
|
|
158
|
+
this.#store = undefined;
|
|
159
|
+
throw error;
|
|
160
|
+
}
|
|
161
|
+
ctx.effect(() => () => {
|
|
162
|
+
this.#active = false;
|
|
163
|
+
this.#ideaChangeListeners.clear();
|
|
164
|
+
this.#unsubscribeLlm?.();
|
|
165
|
+
this.#unsubscribeLlm = undefined;
|
|
166
|
+
this.#unsubscribeWake?.();
|
|
167
|
+
this.#unsubscribeWake = undefined;
|
|
168
|
+
this.#unregister?.();
|
|
169
|
+
this.#unregister = undefined;
|
|
170
|
+
try {
|
|
171
|
+
this.#store?.interrupt();
|
|
172
|
+
}
|
|
173
|
+
catch { /* store may already be closed */ }
|
|
174
|
+
const closing = this.#flight;
|
|
175
|
+
this.#store?.close();
|
|
176
|
+
return closing;
|
|
177
|
+
}, 'assistant-dreaming.runtime');
|
|
178
|
+
}
|
|
179
|
+
/**
|
|
180
|
+
* Enforce the owner retention policy over the private idea ledger. Runs on
|
|
181
|
+
* plugin load and after every completed dream so a long-lived Host cannot
|
|
182
|
+
* keep expired ideas forever. Failure is observable but never fails a wake.
|
|
183
|
+
*/
|
|
184
|
+
#pruneStore(now) {
|
|
185
|
+
try {
|
|
186
|
+
const removed = this.#store?.prune(now, this.#config.retentionDays) ?? 0;
|
|
187
|
+
if (removed > 0)
|
|
188
|
+
this.#notifyIdeaChange();
|
|
189
|
+
}
|
|
190
|
+
catch (error) {
|
|
191
|
+
this.ctx.logger.warn(`assistant-dreaming: idea retention prune failed: ${error instanceof Error ? error.message : String(error)}`);
|
|
192
|
+
}
|
|
193
|
+
}
|
|
194
|
+
/**
|
|
195
|
+
* Register a stable ticket for every recallable subject derived from the
|
|
196
|
+
* current projected material and for this lane's unresolved recorded ideas.
|
|
197
|
+
* Pure registration: no randomness here, the ticket value comes from the
|
|
198
|
+
* HMAC seed in assignTicket.
|
|
199
|
+
*/
|
|
200
|
+
#registerTickets(store, material, now, seedDigest) {
|
|
201
|
+
for (const item of material.items) {
|
|
202
|
+
const subject = { kind: item.kind, key: item.evidenceRef };
|
|
203
|
+
const ticket = assignTicket({ seedDigest, lane: this.#lane, subject });
|
|
204
|
+
store.upsertTicket({ subjectKind: subject.kind, subjectKey: subject.key,
|
|
205
|
+
value: ticket.value, digest: ticket.digest, now });
|
|
206
|
+
}
|
|
207
|
+
// Recorded-but-unresolved ideas are recall subjects too, so a past dream
|
|
208
|
+
// can be revisited; resolved ones (validated/rejected/withdrawn) stop
|
|
209
|
+
// holding a ticket by never being re-registered.
|
|
210
|
+
store.pruneResolvedIdeaTickets();
|
|
211
|
+
for (const idea of store.listIdeas(DREAM_RECORDED_TICKET_LIMIT)) {
|
|
212
|
+
if (idea.state !== 'recorded')
|
|
213
|
+
continue;
|
|
214
|
+
const subject = { kind: 'recorded-idea', key: idea.id };
|
|
215
|
+
const ticket = assignTicket({ seedDigest, lane: this.#lane, subject });
|
|
216
|
+
store.upsertTicket({ subjectKind: subject.kind, subjectKey: subject.key,
|
|
217
|
+
value: ticket.value, digest: ticket.digest, now });
|
|
218
|
+
}
|
|
219
|
+
}
|
|
220
|
+
/**
|
|
221
|
+
* The "无事找事" lottery: roll one code-generated number and return the
|
|
222
|
+
* tickets within the circular window. Runs without a model call; an empty
|
|
223
|
+
* result means no subject is recalled this slot.
|
|
224
|
+
*/
|
|
225
|
+
#drawRecallHits(store, occurrence, seedDigest) {
|
|
226
|
+
const draw = rollLottery({ seedDigest, lane: this.#lane, occurrence });
|
|
227
|
+
const tickets = store.listTickets().map(row => ({
|
|
228
|
+
subject: { kind: row.subjectKind, key: row.subjectKey },
|
|
229
|
+
value: row.value, digest: row.digest,
|
|
230
|
+
}));
|
|
231
|
+
const hits = matchTickets({ draw, tickets, window: this.#config.lotteryWindow });
|
|
232
|
+
return { draw, hits };
|
|
233
|
+
}
|
|
234
|
+
#portsFor(ctx) {
|
|
235
|
+
const automations = ctx.get('assistantAutomations');
|
|
236
|
+
const delivery = ctx.get('assistantDelivery');
|
|
237
|
+
const evaluation = ctx.get('assistantEvaluation');
|
|
238
|
+
const goals = ctx.get('assistantGoals');
|
|
239
|
+
const skills = ctx.get('assistantSkills');
|
|
240
|
+
if (!automations || !delivery || !evaluation || !goals || !skills
|
|
241
|
+
|| !ctx.get('agents') || !ctx.get('sessions') || !ctx.get('tools')) {
|
|
242
|
+
throw new Error('assistant-dreaming: enabled dreaming requires automations, delivery, evaluation, goals, skills, agents, sessions and tools');
|
|
243
|
+
}
|
|
244
|
+
return { automations, delivery, evaluation, goals, skills };
|
|
245
|
+
}
|
|
246
|
+
#automationId() {
|
|
247
|
+
return `dsh-ray-assistant-dreaming:${this.#lane}`;
|
|
248
|
+
}
|
|
249
|
+
#configDigest() {
|
|
250
|
+
return acceptanceDigest({ lane: this.#lane, config: this.#config }).slice(0, 40);
|
|
251
|
+
}
|
|
252
|
+
#reconcileInput(desiredStatus) {
|
|
253
|
+
// Both transitions are load-scoped. Automations replays a cached
|
|
254
|
+
// `automation_system_reconciles` receipt for a repeated idempotency key
|
|
255
|
+
// without touching the row, so a deterministic paused key would make a
|
|
256
|
+
// second retire (or retire after resume) silently leave the row active
|
|
257
|
+
// while this plugin is already dormant. Reconcile is a local CAS converge
|
|
258
|
+
// operation: a fresh key per load is safe, and a repeated retire() in the
|
|
259
|
+
// same load still just replays the same paused receipt.
|
|
260
|
+
const key = `${this.#automationId()}:${this.#configDigest()}:${desiredStatus}:${this.#loadNonce}`;
|
|
261
|
+
return {
|
|
262
|
+
owner: OWNER,
|
|
263
|
+
automationId: this.#automationId(),
|
|
264
|
+
idempotencyKey: key,
|
|
265
|
+
desiredStatus,
|
|
266
|
+
definition: this.#definition(),
|
|
267
|
+
};
|
|
268
|
+
}
|
|
269
|
+
#definition() {
|
|
270
|
+
const scope = this.#config.scope;
|
|
271
|
+
return {
|
|
272
|
+
name: 'Bounded dreaming review',
|
|
273
|
+
schedule: { kind: 'every', anchorAt: new Date(0).toISOString(), intervalMs: this.#config.baseIntervalMs },
|
|
274
|
+
workspace: scope.workspace,
|
|
275
|
+
agentPreset: scope.preset,
|
|
276
|
+
timeoutMs: this.#config.maxDurationMs,
|
|
277
|
+
// A missed slot is skipped, never replayed: dreaming must not catch up
|
|
278
|
+
// with a burst of paid model calls after downtime.
|
|
279
|
+
misfire: { kind: 'skip' },
|
|
280
|
+
overlap: 'skip',
|
|
281
|
+
retrySafety: 'never',
|
|
282
|
+
maxRetries: 0,
|
|
283
|
+
principal: scope.principalId,
|
|
284
|
+
budgetId: this.#config.budgetId,
|
|
285
|
+
budgetAmount: this.#config.budgetAmount,
|
|
286
|
+
execution: {
|
|
287
|
+
kind: 'host', executorId: EXECUTOR, executorContractVersion: 1, runbookId: 'dream', runbookVersion: 1,
|
|
288
|
+
catalogDigest: CATALOG,
|
|
289
|
+
targetScope: { workspace: scope.workspace, preset: scope.preset },
|
|
290
|
+
scopeDigest: acceptanceDigest([scope.workspace, scope.preset]),
|
|
291
|
+
ownerRouteId: scope.ownerRouteId,
|
|
292
|
+
activationNonce: this.#configDigest(),
|
|
293
|
+
},
|
|
294
|
+
};
|
|
295
|
+
}
|
|
296
|
+
#executor(ports) {
|
|
297
|
+
return {
|
|
298
|
+
descriptor: { executorId: EXECUTOR, contractVersion: 1, catalogDigest: CATALOG },
|
|
299
|
+
accepts: (spec) => spec.executorId === EXECUTOR && spec.executorContractVersion === 1 && spec.catalogDigest === CATALOG
|
|
300
|
+
&& spec.runbookId === 'dream' && spec.runbookVersion === 1,
|
|
301
|
+
execute: (input) => {
|
|
302
|
+
const flight = this.#runSlot(ports, input);
|
|
303
|
+
this.#flight = flight;
|
|
304
|
+
void flight.finally(() => { if (this.#flight === flight)
|
|
305
|
+
this.#flight = undefined; }).catch(() => { });
|
|
306
|
+
return flight;
|
|
307
|
+
},
|
|
308
|
+
};
|
|
309
|
+
}
|
|
310
|
+
/** Latest trusted activity timestamp from Evaluation projections, or null. */
|
|
311
|
+
#latestActivity(ports, scope) {
|
|
312
|
+
const page = ports.evaluation.listTrustedTaskLearningProjections({ scope, limit: 1 });
|
|
313
|
+
const item = page.items[0];
|
|
314
|
+
const at = item?.receipt.objective?.occurredAt;
|
|
315
|
+
return typeof at === 'number' && Number.isFinite(at) ? at : null;
|
|
316
|
+
}
|
|
317
|
+
/** Check prerequisites (scope, owner route, policy/budget, model route) before reserving/spending budget. */
|
|
318
|
+
#evaluatePrerequisites(ports) {
|
|
319
|
+
const scope = this.#config.scope;
|
|
320
|
+
if (scope === null || this.#config.provider === null || this.#config.model === null
|
|
321
|
+
|| this.#config.budgetId === null || this.#config.budgetAmount === null) {
|
|
322
|
+
return { ok: false, reason: 'configuration-incomplete', failureClass: 'configuration', failureCode: 'dream-scope-unavailable' };
|
|
323
|
+
}
|
|
324
|
+
try {
|
|
325
|
+
ports.delivery.validateOwnerRoute({
|
|
326
|
+
authorityId: scope.ownerRouteId,
|
|
327
|
+
principalId: scope.principalId,
|
|
328
|
+
workspace: scope.workspace,
|
|
329
|
+
agentPreset: scope.preset,
|
|
330
|
+
});
|
|
331
|
+
if (typeof ports.delivery.inspectOwnerRouteState === 'function') {
|
|
332
|
+
const routeState = ports.delivery.inspectOwnerRouteState({
|
|
333
|
+
authorityId: scope.ownerRouteId,
|
|
334
|
+
principalId: scope.principalId,
|
|
335
|
+
workspace: scope.workspace,
|
|
336
|
+
agentPreset: scope.preset,
|
|
337
|
+
});
|
|
338
|
+
if (routeState.status !== 'active') {
|
|
339
|
+
return { ok: false, reason: 'scope-unavailable', failureClass: 'configuration', failureCode: 'dream-scope-unavailable' };
|
|
340
|
+
}
|
|
341
|
+
}
|
|
342
|
+
}
|
|
343
|
+
catch {
|
|
344
|
+
return { ok: false, reason: 'scope-unavailable', failureClass: 'configuration', failureCode: 'dream-scope-unavailable' };
|
|
345
|
+
}
|
|
346
|
+
const policy = unwrapService(this.ctx.get('assistantPolicy', false));
|
|
347
|
+
if (policy !== undefined) {
|
|
348
|
+
if (typeof policy.getEmergencyStop === 'function' && policy.getEmergencyStop().enabled === true) {
|
|
349
|
+
return { ok: false, reason: 'policy-emergency-stop', failureClass: 'policy', failureCode: 'dream-policy-denied' };
|
|
350
|
+
}
|
|
351
|
+
if (typeof policy.getBudgetConfig === 'function') {
|
|
352
|
+
const budget = policy.getBudgetConfig(this.#config.budgetId);
|
|
353
|
+
if (budget === undefined || budget.metric !== 'automation-runs' || budget.limit < this.#config.budgetAmount) {
|
|
354
|
+
return { ok: false, reason: 'budget-unavailable', failureClass: 'budget', failureCode: 'dream-budget-unavailable' };
|
|
355
|
+
}
|
|
356
|
+
}
|
|
357
|
+
if (typeof policy.evaluate === 'function') {
|
|
358
|
+
const decision = policy.evaluate({
|
|
359
|
+
subject: {
|
|
360
|
+
kind: 'background',
|
|
361
|
+
id: this.#automationId(),
|
|
362
|
+
workspace: scope.workspace,
|
|
363
|
+
principal: scope.principalId,
|
|
364
|
+
},
|
|
365
|
+
action: 'execute',
|
|
366
|
+
resource: { kind: 'automation', id: this.#automationId() },
|
|
367
|
+
context: { initiator: 'background' },
|
|
368
|
+
});
|
|
369
|
+
if (decision.effect !== 'allow') {
|
|
370
|
+
return { ok: false, reason: 'policy-denied', failureClass: 'policy', failureCode: 'dream-policy-denied' };
|
|
371
|
+
}
|
|
372
|
+
}
|
|
373
|
+
}
|
|
374
|
+
const llm = unwrapService(this.ctx.get('llm', false));
|
|
375
|
+
if (typeof llm?.listProviders === 'function') {
|
|
376
|
+
try {
|
|
377
|
+
const providers = llm.listProviders();
|
|
378
|
+
if (!Array.isArray(providers) || !providers.some(provider => provider?.id === this.#config.provider)) {
|
|
379
|
+
return { ok: false, reason: 'model-unavailable', failureClass: 'configuration', failureCode: 'dream-model-unavailable' };
|
|
380
|
+
}
|
|
381
|
+
}
|
|
382
|
+
catch {
|
|
383
|
+
return { ok: false, reason: 'model-unavailable', failureClass: 'configuration', failureCode: 'dream-model-unavailable' };
|
|
384
|
+
}
|
|
385
|
+
}
|
|
386
|
+
return { ok: true };
|
|
387
|
+
}
|
|
388
|
+
#canReconcilePolicy() {
|
|
389
|
+
const scope = this.#config.scope;
|
|
390
|
+
if (scope === null)
|
|
391
|
+
return false;
|
|
392
|
+
const policy = unwrapService(this.ctx.get('assistantPolicy', false));
|
|
393
|
+
if (policy === undefined || typeof policy.evaluate !== 'function')
|
|
394
|
+
return true;
|
|
395
|
+
if (typeof policy.getEmergencyStop === 'function' && policy.getEmergencyStop().enabled === true)
|
|
396
|
+
return false;
|
|
397
|
+
return policy.evaluate({
|
|
398
|
+
subject: { kind: 'background', id: OWNER, workspace: scope.workspace, principal: scope.principalId },
|
|
399
|
+
action: 'reconcile',
|
|
400
|
+
resource: { kind: 'automation', id: this.#automationId() },
|
|
401
|
+
context: { initiator: 'background' },
|
|
402
|
+
}).effect === 'allow';
|
|
403
|
+
}
|
|
404
|
+
#activateScheduler(ports) {
|
|
405
|
+
this.#unregister = ports.automations.registerHostExecutor(this.#executor(ports));
|
|
406
|
+
ports.automations.reconcileSystem(this.#reconcileInput('active'));
|
|
407
|
+
this.#scheduler = 'active';
|
|
408
|
+
this.#lastSkipReason = null;
|
|
409
|
+
this.#unsubscribeWake?.();
|
|
410
|
+
this.#unsubscribeWake = undefined;
|
|
411
|
+
this.#unsubscribeLlm?.();
|
|
412
|
+
this.#unsubscribeLlm = undefined;
|
|
413
|
+
}
|
|
414
|
+
#tryActivateIfReady(ports) {
|
|
415
|
+
if (!this.#active || this.#config.retired || this.#scheduler === 'active')
|
|
416
|
+
return;
|
|
417
|
+
const prereq = this.#evaluatePrerequisites(ports);
|
|
418
|
+
if (!prereq.ok) {
|
|
419
|
+
this.#lastSkipReason = prereq.reason;
|
|
420
|
+
return;
|
|
421
|
+
}
|
|
422
|
+
try {
|
|
423
|
+
this.#activateScheduler(ports);
|
|
424
|
+
}
|
|
425
|
+
catch {
|
|
426
|
+
try {
|
|
427
|
+
this.#unregister?.();
|
|
428
|
+
}
|
|
429
|
+
catch { /* best-effort rollback */ }
|
|
430
|
+
this.#unregister = undefined;
|
|
431
|
+
this.#scheduler = 'dormant';
|
|
432
|
+
}
|
|
433
|
+
}
|
|
434
|
+
async #runSlot(ports, input) {
|
|
435
|
+
if (!this.#active || this.#store === undefined) {
|
|
436
|
+
return failed('cancelled', 'preflight', 'disposed', 'none');
|
|
437
|
+
}
|
|
438
|
+
const store = this.#store;
|
|
439
|
+
const config = this.#config;
|
|
440
|
+
const scopeConfig = config.scope;
|
|
441
|
+
if (input.executionMode !== 'production') {
|
|
442
|
+
// A dry-run/preview occurrence must never spend money or write ideas.
|
|
443
|
+
this.#lastSkipReason = 'preview';
|
|
444
|
+
return NO_EFFECT;
|
|
445
|
+
}
|
|
446
|
+
if (input.targetScope?.workspace !== scopeConfig.workspace
|
|
447
|
+
|| input.targetScope?.preset !== scopeConfig.preset
|
|
448
|
+
|| input.principal !== scopeConfig.principalId
|
|
449
|
+
|| input.ownerRouteId !== scopeConfig.ownerRouteId) {
|
|
450
|
+
this.#lastRunOutcome = 'failed';
|
|
451
|
+
return failed('configuration', 'preflight', 'dream-scope-mismatch', 'none');
|
|
452
|
+
}
|
|
453
|
+
const prereq = this.#evaluatePrerequisites(ports);
|
|
454
|
+
if (!prereq.ok) {
|
|
455
|
+
this.#lastSkipReason = prereq.reason;
|
|
456
|
+
this.#lastRunOutcome = 'failed';
|
|
457
|
+
return failed(prereq.failureClass, 'preflight', prereq.failureCode, 'none');
|
|
458
|
+
}
|
|
459
|
+
const now = Date.now();
|
|
460
|
+
const timezone = config.activeHours?.timezone ?? 'UTC';
|
|
461
|
+
const dayKey = localDayKey(now, timezone);
|
|
462
|
+
let latestActivityAt = null;
|
|
463
|
+
try {
|
|
464
|
+
latestActivityAt = this.#latestActivity(ports, ports.evaluation.canonicalHostScope({
|
|
465
|
+
workspace: scopeConfig.workspace, preset: scopeConfig.preset
|
|
466
|
+
}));
|
|
467
|
+
}
|
|
468
|
+
catch {
|
|
469
|
+
latestActivityAt = null;
|
|
470
|
+
}
|
|
471
|
+
const occurrence = Number.parseInt(createHash('sha256')
|
|
472
|
+
.update(`${input.definitionHash}\0${input.occurrenceId}`).digest('hex').slice(0, 12), 16);
|
|
473
|
+
const seedDigest = config.seedDigest ?? createHash('sha256').update(`assistant-dreaming\0${this.#lane}`).digest('hex');
|
|
474
|
+
const decision = decideTrigger({
|
|
475
|
+
now,
|
|
476
|
+
occurrence,
|
|
477
|
+
lane: this.#lane,
|
|
478
|
+
seedDigest,
|
|
479
|
+
probabilityPpm: config.runProbabilityPpm,
|
|
480
|
+
activeHours: config.activeHours,
|
|
481
|
+
latestActivityAt,
|
|
482
|
+
coldStartAnchorAt: this.#coldStartAnchorAt,
|
|
483
|
+
idleMinMs: config.idleMinMs,
|
|
484
|
+
dreamsToday: store.countDreams(dayKey),
|
|
485
|
+
maxDreamsPerDay: config.maxDreamsPerDay,
|
|
486
|
+
});
|
|
487
|
+
if (!decision.fire) {
|
|
488
|
+
this.#lastSkipReason = decision.reason;
|
|
489
|
+
return NO_EFFECT;
|
|
490
|
+
}
|
|
491
|
+
// Per-subject lottery ("无事找事"): build material and tickets, then roll
|
|
492
|
+
// one code-generated number. A miss is a normal no-thought slot and skips
|
|
493
|
+
// the model entirely; a hit focuses the wake on the recalled subject.
|
|
494
|
+
const personalMemory = unwrapService(this.ctx.get('personalMemory', false));
|
|
495
|
+
let seedMaterial;
|
|
496
|
+
try {
|
|
497
|
+
seedMaterial = buildDreamMaterial({
|
|
498
|
+
evaluation: ports.evaluation,
|
|
499
|
+
delivery: ports.delivery,
|
|
500
|
+
goals: ports.goals,
|
|
501
|
+
skills: ports.skills,
|
|
502
|
+
...(personalMemory === undefined ? {} : { personalMemory }),
|
|
503
|
+
scope: scopeConfig,
|
|
504
|
+
maxInputBytes: config.maxInputBytes,
|
|
505
|
+
});
|
|
506
|
+
if (seedMaterial.items.length === 0 && store.counts().recorded === 0) {
|
|
507
|
+
this.#lastSkipReason = 'no-recallable-material';
|
|
508
|
+
return NO_EFFECT;
|
|
509
|
+
}
|
|
510
|
+
this.#registerTickets(store, seedMaterial, now, seedDigest);
|
|
511
|
+
}
|
|
512
|
+
catch (error) {
|
|
513
|
+
// A revoked/missing owner route or projection failure is an owner
|
|
514
|
+
// configuration problem, not a dreamed result: fail closed with no
|
|
515
|
+
// model spend and no ledger write.
|
|
516
|
+
this.#lastRunOutcome = 'failed';
|
|
517
|
+
this.ctx.logger.warn(`assistant-dreaming: material unavailable: ${error instanceof Error ? error.message : String(error)}`);
|
|
518
|
+
return failed('configuration', 'preflight', 'dream-material-unavailable', 'none');
|
|
519
|
+
}
|
|
520
|
+
const { draw, hits } = this.#drawRecallHits(store, occurrence, seedDigest);
|
|
521
|
+
if (hits.length === 0) {
|
|
522
|
+
this.#lastSkipReason = 'lottery-no-hit';
|
|
523
|
+
return NO_EFFECT;
|
|
524
|
+
}
|
|
525
|
+
const llm = unwrapService(this.ctx.get('llm', false));
|
|
526
|
+
if (typeof llm?.resolveModelInfo === 'function') {
|
|
527
|
+
try {
|
|
528
|
+
await llm.resolveModelInfo(config.provider, config.model, input.signal);
|
|
529
|
+
}
|
|
530
|
+
catch {
|
|
531
|
+
this.#lastSkipReason = 'model-unavailable';
|
|
532
|
+
this.#lastRunOutcome = 'failed';
|
|
533
|
+
return failed('configuration', 'preflight', 'dream-model-unavailable', 'none');
|
|
534
|
+
}
|
|
535
|
+
}
|
|
536
|
+
for (const hit of hits) {
|
|
537
|
+
store.recordRecall({ occurrence, drawDigest: draw.drawDigest, drawValue: draw.value,
|
|
538
|
+
subjectKind: hit.subject.kind, subjectKey: hit.subject.key, ticketValue: hit.ticketValue,
|
|
539
|
+
distance: hit.distance, at: now });
|
|
540
|
+
}
|
|
541
|
+
this.#lastSkipReason = null;
|
|
542
|
+
const runId = `dream-${input.occurrenceId}`;
|
|
543
|
+
let submitted = false;
|
|
544
|
+
try {
|
|
545
|
+
const model = this.#resolveModel();
|
|
546
|
+
store.beginDream(runId, occurrence, decision.dayKey, now, decision.drawDigest);
|
|
547
|
+
submitted = true;
|
|
548
|
+
this.#lastRunAt = now;
|
|
549
|
+
const result = await runDreamAgent({
|
|
550
|
+
ctx: this.ctx,
|
|
551
|
+
wakeId: input.occurrenceId,
|
|
552
|
+
config,
|
|
553
|
+
model,
|
|
554
|
+
scope: scopeConfig,
|
|
555
|
+
material: seedMaterial,
|
|
556
|
+
recallHits: hits.map(hit => {
|
|
557
|
+
const focus = { kind: hit.subject.kind, key: hit.subject.key,
|
|
558
|
+
ticketValue: hit.ticketValue, distance: hit.distance };
|
|
559
|
+
// Recorded ideas live outside the projection material; carry their
|
|
560
|
+
// own summary so the recalled subject is not just an opaque id.
|
|
561
|
+
if (hit.subject.kind === 'recorded-idea') {
|
|
562
|
+
const idea = store.idea(hit.subject.key);
|
|
563
|
+
if (idea !== undefined)
|
|
564
|
+
return { ...focus, summary: idea.summary };
|
|
565
|
+
}
|
|
566
|
+
return focus;
|
|
567
|
+
}),
|
|
568
|
+
deadlineAt: Math.min(now + config.maxDurationMs, Date.now() + config.maxDurationMs),
|
|
569
|
+
signal: input.signal,
|
|
570
|
+
onSubmit: ideas => {
|
|
571
|
+
let recorded = 0;
|
|
572
|
+
try {
|
|
573
|
+
for (const idea of ideas) {
|
|
574
|
+
store.recordIdea({
|
|
575
|
+
id: createHash('sha256').update(`${runId}\0${recorded}\0${idea.summary}`).digest('hex').slice(0, 32),
|
|
576
|
+
runId, createdAt: Date.now(), dayKey: decision.dayKey,
|
|
577
|
+
summary: idea.summary, detail: idea.detail, evidenceRefs: idea.evidenceRefs,
|
|
578
|
+
});
|
|
579
|
+
recorded += 1;
|
|
580
|
+
}
|
|
581
|
+
}
|
|
582
|
+
finally {
|
|
583
|
+
if (recorded > 0)
|
|
584
|
+
this.#notifyIdeaChange();
|
|
585
|
+
}
|
|
586
|
+
return recorded;
|
|
587
|
+
},
|
|
588
|
+
});
|
|
589
|
+
this.#lastRunOutcome = result.outcome;
|
|
590
|
+
if (result.outcome === 'succeeded') {
|
|
591
|
+
store.completeDream(runId, Date.now(), result.ideaCount);
|
|
592
|
+
this.#pruneStore(Date.now());
|
|
593
|
+
this.#notifyOwner(store, runId, decision.dayKey, result.ideaCount, now);
|
|
594
|
+
return EFFECT_OK;
|
|
595
|
+
}
|
|
596
|
+
store.markInterrupted(runId, Date.now());
|
|
597
|
+
return result.outcome === 'cancelled'
|
|
598
|
+
? failed('cancelled', 'host-execution', 'dream-agent-cancelled', 'possible')
|
|
599
|
+
: failed('execution', 'host-execution', 'dream-agent-failed', 'possible');
|
|
600
|
+
}
|
|
601
|
+
catch (error) {
|
|
602
|
+
if (this.#store !== undefined) {
|
|
603
|
+
try {
|
|
604
|
+
store.markInterrupted(runId, Date.now());
|
|
605
|
+
}
|
|
606
|
+
catch { /* closed */ }
|
|
607
|
+
}
|
|
608
|
+
this.#lastRunOutcome = 'failed';
|
|
609
|
+
this.ctx.logger.warn(`assistant-dreaming: dream wake failed: ${error instanceof Error ? error.message : String(error)}`);
|
|
610
|
+
return submitted
|
|
611
|
+
? failed('execution', 'host-execution', 'dream-execution-failed', 'possible')
|
|
612
|
+
: failed('configuration', 'preflight', 'dream-preflight-failed', 'none');
|
|
613
|
+
}
|
|
614
|
+
}
|
|
615
|
+
#resolveModel() {
|
|
616
|
+
const config = this.#config;
|
|
617
|
+
return { provider: config.provider, model: config.model,
|
|
618
|
+
...(config.reasoningEffort === null ? {} : { reasoningEffort: config.reasoningEffort }) };
|
|
619
|
+
}
|
|
620
|
+
/**
|
|
621
|
+
* L1 owner summary notification. Fails closed at every gate: the
|
|
622
|
+
* notification flag, daily count and minimum interval must all allow it,
|
|
623
|
+
* and the live route is re-validated by the enqueue helper. A failed
|
|
624
|
+
* notification never changes the dream outcome.
|
|
625
|
+
*/
|
|
626
|
+
#notifyOwner(store, runId, dayKey, ideaCount, now) {
|
|
627
|
+
const config = this.#config;
|
|
628
|
+
if (!config.notifyOwner || config.maxNotificationsPerDay === 0 || ideaCount === 0)
|
|
629
|
+
return;
|
|
630
|
+
if (store.countNotifications(dayKey) >= config.maxNotificationsPerDay)
|
|
631
|
+
return;
|
|
632
|
+
const lastAt = store.lastNotificationAt();
|
|
633
|
+
if (lastAt !== null && now - lastAt < config.notifyMinIntervalMs)
|
|
634
|
+
return;
|
|
635
|
+
const scope = config.scope;
|
|
636
|
+
const delivery = this.ctx.get('assistantDelivery', false);
|
|
637
|
+
if (delivery === undefined)
|
|
638
|
+
return;
|
|
639
|
+
const sent = enqueueDreamNotification({
|
|
640
|
+
validateOwnerRoute: input => delivery.validateOwnerRoute({ authorityId: scope.ownerRouteId, principalId: input.principalId,
|
|
641
|
+
workspace: input.workspace, agentPreset: input.preset }),
|
|
642
|
+
resolveOwnerRoute: ownerRouteId => delivery.resolveOwnerRoute(ownerRouteId),
|
|
643
|
+
enqueueOwnerNotification: input => delivery.enqueueOwnerNotification(input),
|
|
644
|
+
}, {
|
|
645
|
+
owner: { ownerRouteId: scope.ownerRouteId, principalId: scope.principalId, workspace: scope.workspace, preset: scope.preset },
|
|
646
|
+
runId,
|
|
647
|
+
summaries: store.listIdeas(ideaCount).map(idea => ({ summary: idea.summary, detail: idea.detail })),
|
|
648
|
+
dayKey, now, expiresAt: now + config.maxDurationMs,
|
|
649
|
+
});
|
|
650
|
+
if (sent)
|
|
651
|
+
store.incrementNotifications(dayKey, now);
|
|
652
|
+
}
|
|
653
|
+
// Public surfaces are bound arrow properties: Cordis serves services through
|
|
654
|
+
// a traceable proxy whose method calls would otherwise lose the private-field
|
|
655
|
+
// receiver (the Loader and owner surfaces always read through that proxy).
|
|
656
|
+
health = () => {
|
|
657
|
+
let counts = { runs: 0, ideas: 0, recorded: 0 };
|
|
658
|
+
if (this.#store !== undefined) {
|
|
659
|
+
try {
|
|
660
|
+
counts = this.#store.counts();
|
|
661
|
+
}
|
|
662
|
+
catch { /* read failure keeps zeros */ }
|
|
663
|
+
}
|
|
664
|
+
return Object.freeze({
|
|
665
|
+
enabled: this.#config.enabled,
|
|
666
|
+
scheduler: this.#scheduler,
|
|
667
|
+
lastRunAt: this.#lastRunAt,
|
|
668
|
+
lastRunOutcome: this.#lastRunOutcome,
|
|
669
|
+
lastSkipReason: this.#lastSkipReason,
|
|
670
|
+
counts,
|
|
671
|
+
});
|
|
672
|
+
};
|
|
673
|
+
/** Read-only access to recorded ideas for the owner-facing surfaces. */
|
|
674
|
+
inspectIdeas = (limit = 50) => {
|
|
675
|
+
if (this.#store === undefined)
|
|
676
|
+
return Object.freeze([]);
|
|
677
|
+
return Object.freeze([...this.#store.listIdeas(normalizeLimit(limit))]);
|
|
678
|
+
};
|
|
679
|
+
/** Read-only access to owner-validated ideas eligible for downstream intake. */
|
|
680
|
+
inspectValidatedIdeas = (limit = 50) => {
|
|
681
|
+
if (this.#store === undefined)
|
|
682
|
+
return Object.freeze([]);
|
|
683
|
+
return Object.freeze([...this.#store.listValidatedIdeas(normalizeLimit(limit))]);
|
|
684
|
+
};
|
|
685
|
+
/** Read-only audit trail for one idea in this lane. */
|
|
686
|
+
inspectIdeaEvents = (ideaId, limit = 50) => {
|
|
687
|
+
if (this.#store === undefined)
|
|
688
|
+
return Object.freeze([]);
|
|
689
|
+
const id = parseIdeaId(ideaId);
|
|
690
|
+
return this.#store.listIdeaEvents(id, normalizeLimit(limit));
|
|
691
|
+
};
|
|
692
|
+
/** Host-only notification when dreaming ideas are created, validated, or transitioned. */
|
|
693
|
+
onIdeaChange = (listener) => {
|
|
694
|
+
if (!this.#active)
|
|
695
|
+
throw new Error('assistant-dreaming: dreaming service is not active');
|
|
696
|
+
if (typeof listener !== 'function')
|
|
697
|
+
throw new TypeError('assistant-dreaming: listener must be a function');
|
|
698
|
+
if (!this.#config.enabled)
|
|
699
|
+
return () => { };
|
|
700
|
+
this.#ideaChangeListeners.add(listener);
|
|
701
|
+
let subscribed = true;
|
|
702
|
+
return () => {
|
|
703
|
+
if (!subscribed)
|
|
704
|
+
return;
|
|
705
|
+
subscribed = false;
|
|
706
|
+
this.#ideaChangeListeners.delete(listener);
|
|
707
|
+
};
|
|
708
|
+
};
|
|
709
|
+
#notifyIdeaChange() {
|
|
710
|
+
if (!this.#active)
|
|
711
|
+
return;
|
|
712
|
+
for (const listener of Array.from(this.#ideaChangeListeners)) {
|
|
713
|
+
try {
|
|
714
|
+
listener();
|
|
715
|
+
}
|
|
716
|
+
catch {
|
|
717
|
+
// Listener errors must never disrupt idea persistence or transitions.
|
|
718
|
+
}
|
|
719
|
+
}
|
|
720
|
+
}
|
|
721
|
+
/** Owner-authorized transition from `recorded` -> `owner-acknowledged`. */
|
|
722
|
+
acknowledgeIdea = (input) => this.#authorizeAndTransition(input, 'acknowledge', 'owner-acknowledged');
|
|
723
|
+
/** Owner-authorized terminal lifecycle transition (`validate`, `reject`, or `retire`). */
|
|
724
|
+
transitionIdea = (input) => {
|
|
725
|
+
if (input === null || typeof input !== 'object')
|
|
726
|
+
throw new Error('assistant-dreaming: transition input must be an object');
|
|
727
|
+
const raw = ownData(input);
|
|
728
|
+
const transitionMap = {
|
|
729
|
+
validate: 'validated',
|
|
730
|
+
reject: 'rejected',
|
|
731
|
+
retire: 'withdrawn',
|
|
732
|
+
};
|
|
733
|
+
if (typeof raw.transition !== 'string' || !Object.hasOwn(transitionMap, raw.transition)) {
|
|
734
|
+
throw new Error('assistant-dreaming: transition must be validate, reject, or retire');
|
|
735
|
+
}
|
|
736
|
+
return this.#authorizeAndTransition(raw, raw.transition, transitionMap[raw.transition]);
|
|
737
|
+
};
|
|
738
|
+
#authorizeAndTransition(input, action, targetState) {
|
|
739
|
+
if (!this.#active || !this.#config.enabled || this.#store === undefined || this.#config.scope === null || this.#ports === undefined) {
|
|
740
|
+
throw new Error('assistant-dreaming: dreaming service is not enabled');
|
|
741
|
+
}
|
|
742
|
+
const raw = ownData(input);
|
|
743
|
+
if (raw === null || typeof raw !== 'object' || Array.isArray(raw)) {
|
|
744
|
+
throw new Error('assistant-dreaming: transition input must be an object');
|
|
745
|
+
}
|
|
746
|
+
const ideaId = parseIdeaId(raw.ideaId);
|
|
747
|
+
const scope = this.#config.scope;
|
|
748
|
+
if (raw.principalId !== undefined) {
|
|
749
|
+
if (typeof raw.principalId !== 'string' || raw.principalId !== scope.principalId) {
|
|
750
|
+
throw new Error('assistant-dreaming: principalId does not match the configured owner scope');
|
|
751
|
+
}
|
|
752
|
+
}
|
|
753
|
+
// Re-validate the live owner route so a revoked owner cannot mutate ideas.
|
|
754
|
+
this.#ports.delivery.validateOwnerRoute({
|
|
755
|
+
authorityId: scope.ownerRouteId,
|
|
756
|
+
principalId: scope.principalId,
|
|
757
|
+
workspace: scope.workspace,
|
|
758
|
+
agentPreset: scope.preset,
|
|
759
|
+
});
|
|
760
|
+
if (typeof this.#ports.delivery.inspectOwnerRouteState === 'function') {
|
|
761
|
+
const state = this.#ports.delivery.inspectOwnerRouteState({
|
|
762
|
+
authorityId: scope.ownerRouteId,
|
|
763
|
+
principalId: scope.principalId,
|
|
764
|
+
workspace: scope.workspace,
|
|
765
|
+
agentPreset: scope.preset,
|
|
766
|
+
});
|
|
767
|
+
if (state.status !== 'active')
|
|
768
|
+
throw new Error('assistant-dreaming: owner route is not active');
|
|
769
|
+
}
|
|
770
|
+
const policy = unwrapService(this.ctx.get('assistantPolicy', false));
|
|
771
|
+
if (policy === undefined || typeof policy.authorize !== 'function') {
|
|
772
|
+
throw new Error('assistant-dreaming: assistantPolicy service is required for owner idea transitions');
|
|
773
|
+
}
|
|
774
|
+
if (typeof policy.getEmergencyStop === 'function' && policy.getEmergencyStop().enabled === true) {
|
|
775
|
+
throw new Error('assistant-dreaming: emergency stop is active');
|
|
776
|
+
}
|
|
777
|
+
const decision = policy.authorize({
|
|
778
|
+
subject: {
|
|
779
|
+
kind: 'external',
|
|
780
|
+
id: scope.principalId,
|
|
781
|
+
workspace: scope.workspace,
|
|
782
|
+
principal: scope.principalId,
|
|
783
|
+
},
|
|
784
|
+
action: `dream.${action}`,
|
|
785
|
+
resource: { kind: 'evolution', id: `assistant-dreaming:idea:${ideaId}` },
|
|
786
|
+
context: { initiator: 'foreground' },
|
|
787
|
+
}, {
|
|
788
|
+
idempotencyKey: `dream-idea:${this.#lane}:${ideaId}:${action}`,
|
|
789
|
+
auditDetails: { lane: this.#lane, ideaId, action, targetState },
|
|
790
|
+
});
|
|
791
|
+
if (decision.effect !== 'allow') {
|
|
792
|
+
throw new Error(`assistant-dreaming: owner authorization denied (${decision.reasonCode})`);
|
|
793
|
+
}
|
|
794
|
+
const result = this.#store.transitionIdea(ideaId, targetState, 'owner', Date.now(), raw.note);
|
|
795
|
+
this.#store.pruneResolvedIdeaTickets();
|
|
796
|
+
this.#notifyIdeaChange();
|
|
797
|
+
return result;
|
|
798
|
+
}
|
|
799
|
+
/**
|
|
800
|
+
* Owner-visible retirement: pause the system automation and unregister the
|
|
801
|
+
* executor, keeping the private ledger (ideas are never deleted here).
|
|
802
|
+
*/
|
|
803
|
+
retire = () => {
|
|
804
|
+
if (!this.#config.enabled || this.#store === undefined)
|
|
805
|
+
return;
|
|
806
|
+
this.#active = false;
|
|
807
|
+
this.#ideaChangeListeners.clear();
|
|
808
|
+
this.#unsubscribeLlm?.();
|
|
809
|
+
this.#unsubscribeLlm = undefined;
|
|
810
|
+
this.#unsubscribeWake?.();
|
|
811
|
+
this.#unsubscribeWake = undefined;
|
|
812
|
+
this.#unregister?.();
|
|
813
|
+
this.#unregister = undefined;
|
|
814
|
+
try {
|
|
815
|
+
this.#ports?.automations.reconcileSystem(this.#reconcileInput('paused'));
|
|
816
|
+
}
|
|
817
|
+
catch { /* ledger stays readable */ }
|
|
818
|
+
this.#scheduler = 'dormant';
|
|
819
|
+
};
|
|
820
|
+
}
|
|
821
|
+
function normalizeLimit(limit) {
|
|
822
|
+
return Number.isSafeInteger(limit) ? Math.min(Math.max(1, limit), 200) : 50;
|
|
823
|
+
}
|
|
824
|
+
function parseIdeaId(value) {
|
|
825
|
+
if (typeof value !== 'string')
|
|
826
|
+
throw new Error('assistant-dreaming: ideaId must be a string');
|
|
827
|
+
const normalized = value.normalize('NFC').trim();
|
|
828
|
+
if (normalized.length === 0 || normalized.length > 128 || !normalized.isWellFormed()
|
|
829
|
+
|| [...normalized].some(char => { const code = char.codePointAt(0); return code <= 0x1f || code === 0x7f; })) {
|
|
830
|
+
throw new Error('assistant-dreaming: invalid ideaId');
|
|
831
|
+
}
|
|
832
|
+
return normalized;
|
|
833
|
+
}
|
|
834
|
+
export { Config };
|
|
835
|
+
//# sourceMappingURL=runtime.js.map
|