@dsh-ray/assistant-proactive 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.
Files changed (48) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +121 -1
  3. package/cordis.patch.yml +3 -0
  4. package/lib/attention-tuning.d.ts +31 -0
  5. package/lib/attention-tuning.d.ts.map +1 -0
  6. package/lib/attention-tuning.js +45 -0
  7. package/lib/attention-tuning.js.map +1 -0
  8. package/lib/engine.d.ts +56 -0
  9. package/lib/engine.d.ts.map +1 -0
  10. package/lib/engine.js +753 -0
  11. package/lib/engine.js.map +1 -0
  12. package/lib/goal-lifecycle.d.ts +69 -0
  13. package/lib/goal-lifecycle.d.ts.map +1 -0
  14. package/lib/goal-lifecycle.js +27 -0
  15. package/lib/goal-lifecycle.js.map +1 -0
  16. package/lib/index.d.ts +109 -0
  17. package/lib/index.d.ts.map +1 -0
  18. package/lib/index.js +1062 -0
  19. package/lib/index.js.map +1 -0
  20. package/lib/intake-evaluation.d.ts +202 -0
  21. package/lib/intake-evaluation.d.ts.map +1 -0
  22. package/lib/intake-evaluation.js +693 -0
  23. package/lib/intake-evaluation.js.map +1 -0
  24. package/lib/intake-routing.d.ts +99 -0
  25. package/lib/intake-routing.d.ts.map +1 -0
  26. package/lib/intake-routing.js +190 -0
  27. package/lib/intake-routing.js.map +1 -0
  28. package/lib/preparation-store.d.ts +48 -0
  29. package/lib/preparation-store.d.ts.map +1 -0
  30. package/lib/preparation-store.js +120 -0
  31. package/lib/preparation-store.js.map +1 -0
  32. package/lib/preparation.d.ts +16 -0
  33. package/lib/preparation.d.ts.map +1 -0
  34. package/lib/preparation.js +127 -0
  35. package/lib/preparation.js.map +1 -0
  36. package/lib/reminder.d.ts +17 -0
  37. package/lib/reminder.d.ts.map +1 -0
  38. package/lib/reminder.js +46 -0
  39. package/lib/reminder.js.map +1 -0
  40. package/lib/types.d.ts +254 -0
  41. package/lib/types.d.ts.map +1 -0
  42. package/lib/types.js +2 -0
  43. package/lib/types.js.map +1 -0
  44. package/lib/version.d.ts +2 -0
  45. package/lib/version.d.ts.map +1 -0
  46. package/lib/version.js +2 -0
  47. package/lib/version.js.map +1 -0
  48. package/package.json +93 -4
package/lib/index.js ADDED
@@ -0,0 +1,1062 @@
1
+ import { Context, Service } from '@deepseek-ai/cordis';
2
+ import { defineTool } from '@deepseek-ai/dsh-tools';
3
+ import Schema from '@deepseek-ai/schemastery';
4
+ import { acceptanceDigest } from '@dsh-ray/task-acceptance-contract';
5
+ import { homedir } from 'node:os';
6
+ import { join } from 'node:path';
7
+ import { ACTIVE_IDLE_THRESHOLD_MS, computeDynamicUtility, IDLE_DISCOUNT_FULL_MS, IDLE_DISCOUNT_START_MS, MAX_ACCEPTANCE_BONUS, MAX_ACCEPTANCE_PENALTY, MAX_ACTIVITY_PENALTY, MAX_FREQUENCY_PENALTY, MAX_IDLE_DISCOUNT, MAX_URGENCY_BONUS, OpportunityEngine, PENALTY_PER_RECENT_NOTIFICATION, RECENT_NOTIFICATION_WINDOW_MS, URGENCY_WINDOW_MS, validateProfile, validateRuntimeContext, } from './engine.js';
8
+ import { reminderText, reminderExpiresAt } from './reminder.js';
9
+ import { attentionOverlay, proactiveAttentionCohort, tuneProfile } from './attention-tuning.js';
10
+ import { IntakeEvaluationProducer, resolveServiceIntakeEvaluation, } from './intake-evaluation.js';
11
+ import { parseTerminalGoalChanged, } from './goal-lifecycle.js';
12
+ import { planProactiveIntakeRoute, } from './intake-routing.js';
13
+ import { PreparationRuntime } from './preparation.js';
14
+ import { PreparationStore } from './preparation-store.js';
15
+ import { version } from './version.js';
16
+ const MAX_GOAL_UNSUBSCRIBE_HOOKS = 64;
17
+ const MAX_REMEMBERED_GOAL_UNSUBSCRIBES = 4_096;
18
+ const MAX_PENDING_GOAL_CHANGE_SIGNALS = 256;
19
+ const MAX_TRACKED_ACTIVITY_SCOPES = 1_024;
20
+ const ACCEPTANCE_SUMMARY_WINDOW_MS = 30 * 24 * 3_600_000;
21
+ /**
22
+ * Bounded R3 default opportunity profile. Uses `mode: 'execute'` without
23
+ * `preparation` so `assertProfile` and doctor checks succeed cleanly even
24
+ * before `assistantDelivery` or preparation credentials are configured;
25
+ * actual wake execution remains gated by Goals' owner/policy/budget/verifier checks.
26
+ */
27
+ export const DEFAULT_PROACTIVE_PROFILES = Object.freeze([
28
+ validateProfile({
29
+ id: 'default',
30
+ mode: 'execute',
31
+ expectedBenefit: 80,
32
+ successPpm: 850_000,
33
+ executionCost: 10,
34
+ interruptionCost: 10,
35
+ possibleLoss: 5,
36
+ minimumUtility: 10,
37
+ mergeWindowMs: 5_000,
38
+ cooldownMs: 60_000,
39
+ rejectionCooldownMs: 3_600_000,
40
+ maxDecisionsPerGoal: 20,
41
+ maxExecutionsPerGoal: 3,
42
+ maxRemindersPerGoal: 0,
43
+ }),
44
+ ]);
45
+ export const name = 'dsh-ray-assistant-proactive';
46
+ export { version, OpportunityEngine, validateProfile, validateRuntimeContext, computeDynamicUtility, attentionOverlay, tuneProfile, proactiveAttentionCohort, RECENT_NOTIFICATION_WINDOW_MS, URGENCY_WINDOW_MS, ACTIVE_IDLE_THRESHOLD_MS, IDLE_DISCOUNT_START_MS, IDLE_DISCOUNT_FULL_MS, MAX_ACTIVITY_PENALTY, MAX_IDLE_DISCOUNT, PENALTY_PER_RECENT_NOTIFICATION, MAX_FREQUENCY_PENALTY, MAX_URGENCY_BONUS, MAX_ACCEPTANCE_BONUS, MAX_ACCEPTANCE_PENALTY, };
47
+ export { DISABLED_INTAKE_EVALUATION_HEALTH, INTAKE_EVALUATION_LEVELS, INTAKE_EVALUATION_PRESETS, IntakeEvaluationError, IntakeEvaluationProducer, intakeEvaluationPolicy, MAX_INTAKE_EVALUATION_QUOTES, MAX_INTAKE_EVALUATION_RULES, MAX_INTAKE_EVALUATION_QUOTE_CHARS, MAX_INTAKE_SOURCE_TEXT, normalizeIntakeEvaluation, resolveIntakeEvaluationPresetRules, resolveServiceIntakeEvaluation, UNCONFIGURED_INTAKE_EVALUATION_HEALTH, UNCONFIGURED_INTAKE_EVALUATION_LAST_ERROR, unconfiguredIntakeEvaluationHealth, } from './intake-evaluation.js';
48
+ export * from './goal-lifecycle.js';
49
+ export * from './intake-routing.js';
50
+ const integer = (max = 1_000_000_000) => Schema.number().step(1).min(0).max(max).required();
51
+ export const Config = Schema.object({
52
+ databasePath: Schema.string().default(join(homedir(), '.dsh', 'assistant-proactive.sqlite')),
53
+ // WP20 stage 3 / R3 producer: enabled by default. Without a configured
54
+ // provider/model it remains cleanly unavailable without failing startup;
55
+ // assistant-work-items must also enable its own intakeLedger.evaluation.
56
+ intakeEvaluation: Schema.object({
57
+ enabled: Schema.boolean().default(true),
58
+ preset: Schema.union(['conservative', 'balanced']),
59
+ rules: Schema.array(Schema.object({
60
+ ruleId: Schema.string().required(),
61
+ ceiling: Schema.union(['ignore', 'digest', 'notify', 'accept']).required(),
62
+ })).default([]),
63
+ provider: Schema.string(),
64
+ model: Schema.string(),
65
+ maxCallsPerHour: Schema.number().step(1).min(1).max(1_000),
66
+ timeoutMs: Schema.number().step(1).min(1_000).max(600_000),
67
+ maxConsecutiveFailures: Schema.number().step(1).min(1).max(10),
68
+ }),
69
+ profiles: Schema.array(Schema.object({
70
+ preparation: Schema.union([Schema.object({ provider: Schema.string().required(), model: Schema.string().required(), budgetId: Schema.string().required(), maxOutputTokens: Schema.number().step(1).min(1).max(32_768).required(), timeoutMs: Schema.number().step(1).min(1_000).max(300_000).required() })]),
71
+ id: Schema.string().required(), mode: Schema.union(['prepare', 'remind', 'execute']).required(),
72
+ expectedBenefit: integer(), successPpm: integer(1_000_000), executionCost: integer(), interruptionCost: integer(), possibleLoss: integer(),
73
+ minimumUtility: integer(),
74
+ mergeWindowMs: integer(), cooldownMs: integer(), rejectionCooldownMs: integer(),
75
+ quietHours: Schema.union([Schema.object({ timezone: Schema.string().required(), startMinute: integer(1439), endMinute: integer(1439) })]),
76
+ maxDecisionsPerGoal: integer(), maxExecutionsPerGoal: integer(), maxRemindersPerGoal: integer(),
77
+ })).default(DEFAULT_PROACTIVE_PROFILES.map(profile => ({ ...profile }))),
78
+ });
79
+ /** This optional decision gate cannot resume a goal or grant tool/route authority. */
80
+ export class AssistantProactiveService extends Service {
81
+ static Config = Config;
82
+ #preparations;
83
+ #engine;
84
+ #profiles = new Map();
85
+ #intakeEvaluation;
86
+ #intakeEvaluationHealth;
87
+ #lastOwnerActivityByScope = new Map();
88
+ #goalUnsubscribeHooks = new Set();
89
+ #emittedGoalUnsubscribes = new Set();
90
+ #pendingGoalChanges = new Map();
91
+ #goalChangeMicrotaskQueued = false;
92
+ #active = true;
93
+ constructor(ctx, config = {}) {
94
+ super(ctx, 'assistantProactive');
95
+ const resolvedIntake = resolveServiceIntakeEvaluation(config.intakeEvaluation);
96
+ const producer = resolvedIntake.config === undefined ? undefined : new IntakeEvaluationProducer({ config: resolvedIntake.config });
97
+ this.#intakeEvaluation = producer;
98
+ this.#intakeEvaluationHealth = resolvedIntake.health;
99
+ for (const input of config.profiles ?? DEFAULT_PROACTIVE_PROFILES) {
100
+ const profile = validateProfile(input);
101
+ if (this.#profiles.has(profile.id))
102
+ throw new Error('assistant-proactive: duplicate profile');
103
+ this.#profiles.set(profile.id, profile);
104
+ }
105
+ this.#engine = new OpportunityEngine(config.databasePath ?? join(homedir(), '.dsh', 'assistant-proactive.sqlite'), [...this.#profiles.values()]);
106
+ const unsubGoalChanged = ctx.on?.('goal/changed', payload => { this.#onGoalChanged(payload); });
107
+ ctx.effect(() => () => {
108
+ this.#active = false;
109
+ if (typeof unsubGoalChanged === 'function') {
110
+ try {
111
+ unsubGoalChanged();
112
+ }
113
+ catch { }
114
+ }
115
+ this.#pendingGoalChanges.clear();
116
+ this.#goalUnsubscribeHooks.clear();
117
+ this.#emittedGoalUnsubscribes.clear();
118
+ this.#engine.close();
119
+ }, 'assistant-proactive.store');
120
+ const preparationPath = config.databasePath === ':memory:' ? ':memory:' : `${config.databasePath ?? join(homedir(), '.dsh', 'assistant-proactive.sqlite')}.preparations`;
121
+ const hasPrepareProfiles = [...this.#profiles.values()].some(profile => profile.mode === 'prepare' && profile.preparation !== undefined);
122
+ this.#preparations = new PreparationRuntime(ctx, new PreparationStore(preparationPath), { active: hasPrepareProfiles });
123
+ ctx.inject(['tools', 'agents', 'assistantDelivery', 'assistantPolicy'], runtime => {
124
+ const output = {
125
+ schema: { type: 'object', additionalProperties: false, properties: { context: { type: 'string', required: true } } },
126
+ render: (_args, value) => [{ type: 'text', text: value.context }],
127
+ };
128
+ const statusTool = defineTool({
129
+ name: 'proactive_status',
130
+ description: 'Inspect owner-scoped event opportunity decisions and operator utility estimates. Preparation may include a persisted model draft when explicitly configured. Drafts are unverified and do not mean the original goal was executed.',
131
+ parameters: { goal_id: { type: 'string' } }, output,
132
+ execute: async (args, execution) => { return { context: JSON.stringify(this.inspect(execution.agent, args.goal_id)) }; },
133
+ });
134
+ runtime.tools.register(statusTool);
135
+ if (runtime.assistantPolicy.contextToolPreauthorizationVersion?.() === 1) {
136
+ runtime.assistantPolicy.registerPreauthorizedTool?.(runtime, statusTool, execution => this.preauthorizeStatus(execution));
137
+ }
138
+ runtime.tools.register(defineTool({
139
+ name: 'proactive_feedback',
140
+ description: 'Record current authenticated owner feedback on an opportunity. Rejection starts a durable cooldown for subsequent decisions. Feedback grants no execution permission and does not undo an already dispatched goal.',
141
+ parameters: { decision_id: { type: 'string', required: true }, feedback: { type: 'string', enum: ['accepted', 'rejected'], required: true } }, output,
142
+ execute: async (args, execution) => { return { context: JSON.stringify(this.feedback(execution.agent, args.decision_id, args.feedback)) }; },
143
+ }));
144
+ });
145
+ if (producer !== undefined)
146
+ this.#registerIntakeEvaluation(ctx, producer);
147
+ }
148
+ /**
149
+ * WP20 stage 3 production wiring: register the intake evaluator only while
150
+ * the LLM and WorkItems services are both active. Both are optional peers, so
151
+ * a deployment without them (or with WorkItems' evaluation disabled) keeps
152
+ * the plugin loaded and behavior unchanged; the health snapshot reports why.
153
+ */
154
+ #registerIntakeEvaluation(ctx, producer) {
155
+ ctx.inject(['llm', 'assistantWorkItems'], runtime => {
156
+ const llm = runtime.get('llm');
157
+ const workItems = runtime.get('assistantWorkItems');
158
+ if (llm === undefined || typeof workItems?.registerIntakeEvaluator !== 'function')
159
+ return;
160
+ producer.attach(llm);
161
+ runtime.effect(() => () => producer.detach(llm), 'assistant-proactive.intake-evaluation-llm');
162
+ let unregister;
163
+ try {
164
+ unregister = workItems.registerIntakeEvaluator(producer.registration());
165
+ }
166
+ catch (error) {
167
+ // WorkItems refuses when its own intakeLedger.evaluation is disabled or
168
+ // another supplier is registered. Nothing was registered, so nothing changes.
169
+ producer.markUnavailable(error);
170
+ runtime.logger.warn(`assistant-proactive: intake evaluator not registered: ${error instanceof Error ? error.message : String(error)}`);
171
+ return;
172
+ }
173
+ producer.markRegistered(true);
174
+ runtime.effect(() => () => { producer.markRegistered(false); unregister(); }, 'assistant-proactive.intake-evaluation');
175
+ });
176
+ ctx.inject(['assistantEvaluation'], evalCtx => {
177
+ if (!this.#active)
178
+ return;
179
+ const evaluation = evalCtx.get('assistantEvaluation');
180
+ const applyEvent = (event) => {
181
+ if (!this.#active || event === null || typeof event !== 'object')
182
+ return;
183
+ const payload = event;
184
+ const action = payload['action'];
185
+ const rawParams = payload['parameters'];
186
+ const params = rawParams !== null && typeof rawParams === 'object' && !Array.isArray(rawParams)
187
+ ? rawParams
188
+ : undefined;
189
+ const rawCohort = payload['cohort'];
190
+ const cohortLane = rawCohort !== null && typeof rawCohort === 'object' && !Array.isArray(rawCohort)
191
+ ? rawCohort['lane']
192
+ : undefined;
193
+ if (rawCohort !== undefined && cohortLane !== 'intake')
194
+ return;
195
+ if ((action === 'loosening-adopted' || action === 'rolled-back' || action === 'tightened')
196
+ && cohortLane === 'intake'
197
+ && params !== undefined && payload['scope'] !== undefined && rawCohort !== undefined
198
+ && typeof payload['version'] === 'number') {
199
+ const targetRules = Array.isArray(params['intakeRuleUpdates'])
200
+ ? params['intakeRuleUpdates']
201
+ : [];
202
+ try {
203
+ producer.reconcileIntakeRuleUpdates(targetRules);
204
+ }
205
+ catch (error) {
206
+ evalCtx.logger.warn(`assistant-proactive: failed to reconcile intakeRuleUpdates from evaluation: ${error instanceof Error ? error.message : String(error)}`);
207
+ }
208
+ return;
209
+ }
210
+ const updates = payload['intakeRuleUpdates'];
211
+ if (!Array.isArray(updates) || updates.length === 0)
212
+ return;
213
+ try {
214
+ producer.applyIntakeRuleUpdates(updates);
215
+ }
216
+ catch (error) {
217
+ evalCtx.logger.warn(`assistant-proactive: failed to apply intakeRuleUpdates from evaluation: ${error instanceof Error ? error.message : String(error)}`);
218
+ }
219
+ };
220
+ let unsubscribe;
221
+ if (typeof evaluation?.onAttentionTuningChanged === 'function') {
222
+ unsubscribe = evaluation.onAttentionTuningChanged(applyEvent);
223
+ }
224
+ else if (typeof evaluation?.onAttentionLooseningAdopted === 'function') {
225
+ unsubscribe = evaluation.onAttentionLooseningAdopted(applyEvent);
226
+ }
227
+ if (unsubscribe !== undefined) {
228
+ evalCtx.effect(() => unsubscribe, 'assistant-proactive.evaluation-tuning');
229
+ }
230
+ });
231
+ }
232
+ /** Host-only read-only readiness/health for operators and doctor; grants nothing. */
233
+ intakeEvaluationHealth = () => this.#intakeEvaluation?.health() ?? this.#intakeEvaluationHealth;
234
+ /** Host-only live rule overrides (`enabled`, `mode`, thresholds) without bumping `policy().version`. */
235
+ applyIntakeRuleUpdates = (updates) => {
236
+ if (!this.#active)
237
+ throw new Error('assistant-proactive: disposed');
238
+ return this.#intakeEvaluation?.applyIntakeRuleUpdates(updates) ?? Object.freeze([]);
239
+ };
240
+ /** Host-only authoritative rule override reconciliation without bumping `policy().version`. */
241
+ reconcileIntakeRuleUpdates = (updates) => {
242
+ if (!this.#active)
243
+ throw new Error('assistant-proactive: disposed');
244
+ return this.#intakeEvaluation?.reconcileIntakeRuleUpdates(updates) ?? Object.freeze([]);
245
+ };
246
+ intakeRuleOverrides = () => {
247
+ if (!this.#active)
248
+ throw new Error('assistant-proactive: disposed');
249
+ return this.#intakeEvaluation?.intakeRuleOverrides() ?? Object.freeze([]);
250
+ };
251
+ assertProfile = (profileId) => {
252
+ if (!this.#active || !this.#profiles.has(profileId))
253
+ throw new Error('assistant-proactive: configured active opportunity profile required');
254
+ if (this.#profiles.get(profileId).preparation && !this.#preparations.available())
255
+ throw new Error('assistant-proactive: preparation services unavailable');
256
+ if (this.#profiles.get(profileId).mode === 'remind' && !this.#notificationPort())
257
+ throw new Error('assistant-proactive: reminder delivery service unavailable');
258
+ };
259
+ availableProfiles = (agent) => {
260
+ this.#scope(agent, false, false);
261
+ return Object.freeze([...this.#profiles.values()].filter(profile => {
262
+ try {
263
+ this.assertProfile(profile.id);
264
+ return true;
265
+ }
266
+ catch {
267
+ return false;
268
+ }
269
+ }).slice(0, 16).map(profile => Object.freeze({ id: profile.id, mode: profile.mode,
270
+ maxDecisionsPerGoal: profile.maxDecisionsPerGoal, maxExecutionsPerGoal: profile.maxExecutionsPerGoal,
271
+ maxRemindersPerGoal: profile.maxRemindersPerGoal })));
272
+ };
273
+ preauthorizeStatus = (execution) => {
274
+ try {
275
+ if (execution.signal.aborted || !execution.arguments || typeof execution.arguments !== 'object'
276
+ || Array.isArray(execution.arguments) || Object.getPrototypeOf(execution.arguments) !== Object.prototype
277
+ || Object.getOwnPropertySymbols(execution.arguments).length !== 0)
278
+ return false;
279
+ const args = execution.arguments;
280
+ if (Object.getOwnPropertyNames(args).some(key => key !== 'goal_id')
281
+ || Object.values(Object.getOwnPropertyDescriptors(args)).some(value => !value.enumerable || !('value' in value))
282
+ || args.goal_id !== undefined && (typeof args.goal_id !== 'string' || args.goal_id.length === 0 || args.goal_id.length > 4096))
283
+ return false;
284
+ this.#scope(execution.agent, false, false);
285
+ return true;
286
+ }
287
+ catch {
288
+ return false;
289
+ }
290
+ };
291
+ evaluate = (input, runtimeContext) => {
292
+ this.assertProfile(input.profileId);
293
+ const resolvedContext = this.#resolveRuntimeContext(input, runtimeContext);
294
+ const overlay = this.#configuredProfileMode(input.profileId) === 'remind' ? this.#attentionOverlay(input.scope) : undefined;
295
+ const evaluation = this.#engine.evaluate(input, overlay, resolvedContext);
296
+ const decision = evaluation.decision;
297
+ if (evaluation.disposition === 'consume' && decision.mode === 'remind' && decision.state === 'decided') {
298
+ const delivery = this.#notificationPort();
299
+ if (!delivery)
300
+ throw new Error('assistant-proactive: reminder delivery service unavailable');
301
+ const profile = tuneProfile(this.#engine.profileSnapshot(decision.scope, decision.goalId, decision.profileId), overlay);
302
+ const expiresAt = reminderExpiresAt(decision, profile);
303
+ // An informational notice: no WorkItem or structured question exists, so `attention` would not apply.
304
+ if (Date.now() < expiresAt) {
305
+ delivery.enqueueOwnerNotification({ sourceId: 'assistant-proactive/v1', ownerRouteId: decision.ownerRouteId, scope: decision.scope, sessionId: decision.sessionId, idempotencyKey: `proactive-reminder:${decision.id}`, text: reminderText(decision), expiresAt, attention: { purpose: 'result' } });
306
+ this.#engine.confirmReminder(decision);
307
+ }
308
+ else
309
+ this.#engine.releaseReminder(decision); // never queued: a later unchanged event may still remind
310
+ }
311
+ if (evaluation.disposition === 'consume' && decision.mode === 'prepare' && decision.state === 'decided') {
312
+ const profile = this.#engine.profileSnapshot(decision.scope, decision.goalId, decision.profileId);
313
+ if (profile.preparation) {
314
+ this.#preparations.store.enqueue(decision, profile.preparation, reminderExpiresAt(decision, profile));
315
+ void this.#preparations.tick().catch(() => { });
316
+ }
317
+ }
318
+ return evaluation;
319
+ };
320
+ #recordOwnerActivity(workspace, preset, at = Date.now()) {
321
+ if (!Number.isSafeInteger(at) || at < 0)
322
+ return;
323
+ const key = `${workspace}\0${preset}`;
324
+ if (!this.#lastOwnerActivityByScope.has(key) && this.#lastOwnerActivityByScope.size >= MAX_TRACKED_ACTIVITY_SCOPES) {
325
+ const oldest = this.#lastOwnerActivityByScope.keys().next().value;
326
+ if (oldest !== undefined)
327
+ this.#lastOwnerActivityByScope.delete(oldest);
328
+ }
329
+ const previous = this.#lastOwnerActivityByScope.get(key);
330
+ if (previous === undefined || at > previous)
331
+ this.#lastOwnerActivityByScope.set(key, at);
332
+ }
333
+ #resolveRuntimeContext(input, explicit) {
334
+ const checked = validateRuntimeContext(explicit);
335
+ const now = Date.now();
336
+ const scopeKeyParts = { workspace: input.scope.workspace, preset: input.scope.preset };
337
+ let userActive = checked?.userActive;
338
+ let latestActivityAt;
339
+ const noteActivity = (candidate) => {
340
+ if (typeof candidate === 'number' && Number.isSafeInteger(candidate) && candidate >= 0 && candidate <= now) {
341
+ if (latestActivityAt === undefined || candidate > latestActivityAt)
342
+ latestActivityAt = candidate;
343
+ }
344
+ };
345
+ if (userActive === undefined || checked?.idleDurationMs === undefined) {
346
+ noteActivity(this.#lastOwnerActivityByScope.get(`${scopeKeyParts.workspace}\0${scopeKeyParts.preset}`));
347
+ try {
348
+ const agents = this.ctx.get('agents');
349
+ if (agents) {
350
+ const candidates = [];
351
+ try {
352
+ const initiator = agents.currentInitiator?.();
353
+ if (initiator)
354
+ candidates.push(initiator);
355
+ }
356
+ catch { }
357
+ try {
358
+ const bySession = agents.get?.(input.sessionId);
359
+ if (bySession)
360
+ candidates.push(bySession);
361
+ }
362
+ catch { }
363
+ try {
364
+ const listed = agents.list?.();
365
+ if (Array.isArray(listed))
366
+ candidates.push(...listed);
367
+ }
368
+ catch { }
369
+ for (const candidate of candidates) {
370
+ if (!candidate || typeof candidate !== 'object')
371
+ continue;
372
+ const agentObj = candidate;
373
+ const cwd = agentObj.session?.header?.cwd;
374
+ const preset = agentObj.session?.header?.agentPreset;
375
+ const matchesScope = (cwd === undefined || cwd === scopeKeyParts.workspace)
376
+ && (preset === undefined || preset === scopeKeyParts.preset)
377
+ && (cwd !== undefined || preset !== undefined || agentObj.id === input.sessionId);
378
+ if (!matchesScope)
379
+ continue;
380
+ noteActivity(agentObj.lastActivityAt);
381
+ if (userActive === undefined) {
382
+ if (typeof agentObj.status === 'string' && agentObj.status.length > 0
383
+ && !['idle', 'stopped', 'disposed', 'closed'].includes(agentObj.status)) {
384
+ userActive = true;
385
+ }
386
+ else if (agentObj.session && typeof agents.turnBoundaryOf === 'function') {
387
+ try {
388
+ const boundary = agents.turnBoundaryOf(agentObj.session);
389
+ if (typeof boundary?.openTurnStartSeq === 'number' && Number.isSafeInteger(boundary.openTurnStartSeq) && boundary.openTurnStartSeq >= 0) {
390
+ userActive = true;
391
+ }
392
+ }
393
+ catch { }
394
+ }
395
+ }
396
+ }
397
+ }
398
+ }
399
+ catch {
400
+ // Optional agents telemetry failure must never block evaluation.
401
+ }
402
+ }
403
+ let recentNotificationCount = checked?.recentNotificationCount;
404
+ let acceptanceRatePpm = checked?.acceptanceRatePpm;
405
+ let acceptanceSamples = checked?.acceptanceSamples;
406
+ try {
407
+ const evaluation = this.ctx.get('assistantEvaluation');
408
+ if (evaluation) {
409
+ if (checked?.idleDurationMs === undefined && userActive !== true && typeof evaluation.listTrustedTaskLearningProjections === 'function') {
410
+ try {
411
+ const feed = evaluation.listTrustedTaskLearningProjections({ scope: scopeKeyParts, limit: 1 });
412
+ noteActivity(feed?.items?.[0]?.receipt?.objective?.occurredAt);
413
+ }
414
+ catch { }
415
+ }
416
+ if (recentNotificationCount === undefined && typeof evaluation.notificationOutcomeSummary === 'function') {
417
+ try {
418
+ const recent = evaluation.notificationOutcomeSummary({
419
+ scope: scopeKeyParts,
420
+ fromNotifiedAt: Math.max(0, now - RECENT_NOTIFICATION_WINDOW_MS),
421
+ toNotifiedAt: now + 1,
422
+ });
423
+ if (typeof recent?.total === 'number' && Number.isSafeInteger(recent.total) && recent.total >= 0) {
424
+ recentNotificationCount = recent.total;
425
+ }
426
+ }
427
+ catch { }
428
+ }
429
+ if (acceptanceRatePpm === undefined && typeof evaluation.notificationOutcomeSummary === 'function') {
430
+ try {
431
+ const history = evaluation.notificationOutcomeSummary({
432
+ scope: scopeKeyParts,
433
+ fromNotifiedAt: Math.max(0, now - ACCEPTANCE_SUMMARY_WINDOW_MS),
434
+ toNotifiedAt: now + 1,
435
+ });
436
+ const accepted = history?.outcomes?.['accepted'];
437
+ const rejected = history?.outcomes?.['rejected'];
438
+ if (typeof accepted === 'number' && Number.isSafeInteger(accepted) && accepted >= 0
439
+ && typeof rejected === 'number' && Number.isSafeInteger(rejected) && rejected >= 0) {
440
+ const total = accepted + rejected;
441
+ if (total > 0) {
442
+ acceptanceSamples = Math.min(1_000_000, total);
443
+ acceptanceRatePpm = Math.floor((accepted * 1_000_000) / total);
444
+ }
445
+ }
446
+ }
447
+ catch { }
448
+ }
449
+ }
450
+ }
451
+ catch {
452
+ // Optional Evaluation telemetry failure must never block evaluation.
453
+ }
454
+ const idleDurationMs = checked?.idleDurationMs !== undefined
455
+ ? checked.idleDurationMs
456
+ : userActive !== true && latestActivityAt !== undefined
457
+ ? Math.min(Number.MAX_SAFE_INTEGER, Math.max(0, now - latestActivityAt))
458
+ : undefined;
459
+ const urgencyPpm = checked?.urgencyPpm;
460
+ if (userActive === undefined
461
+ && idleDurationMs === undefined
462
+ && recentNotificationCount === undefined
463
+ && urgencyPpm === undefined
464
+ && acceptanceRatePpm === undefined
465
+ && acceptanceSamples === undefined) {
466
+ return undefined;
467
+ }
468
+ return {
469
+ ...(userActive === undefined ? {} : { userActive }),
470
+ ...(idleDurationMs === undefined ? {} : { idleDurationMs }),
471
+ ...(recentNotificationCount === undefined ? {} : { recentNotificationCount }),
472
+ ...(urgencyPpm === undefined ? {} : { urgencyPpm }),
473
+ ...(acceptanceRatePpm === undefined ? {} : { acceptanceRatePpm }),
474
+ ...(acceptanceSamples === undefined ? {} : { acceptanceSamples }),
475
+ };
476
+ }
477
+ #configuredProfileMode(profileId) { return this.#profiles.get(profileId)?.mode; }
478
+ /**
479
+ * WP22: the current verified attention version for proactive reminders, read
480
+ * structurally from Evaluation. Absent service, switch off, errors, version 0
481
+ * or malformed values all mean no overlay (identical untuned behavior).
482
+ */
483
+ #attentionOverlay(scope) {
484
+ const evaluation = this.ctx.get('assistantEvaluation');
485
+ if (typeof evaluation?.currentAttentionTuning !== 'function')
486
+ return undefined;
487
+ try {
488
+ return attentionOverlay(evaluation.currentAttentionTuning({ scope: { workspace: scope.workspace, preset: scope.preset }, cohort: { ...proactiveAttentionCohort } }));
489
+ }
490
+ catch {
491
+ return undefined;
492
+ }
493
+ }
494
+ #notificationPort() {
495
+ const delivery = this.ctx.get('assistantDelivery');
496
+ return typeof delivery?.enqueueOwnerNotification === 'function' ? delivery : undefined;
497
+ }
498
+ closeWait = (waitId, scope, reason) => {
499
+ if (!this.#active)
500
+ throw new Error('assistant-proactive: disposed');
501
+ const links = this.#engine.sourcesForWait(waitId, scope);
502
+ this.#engine.closeWait(waitId, scope, reason);
503
+ this.#preparations.store.cancelWait(waitId, scope);
504
+ this.#cleanupClosedWaitLinks(links, scope, reason);
505
+ };
506
+ /** Host-only hook notified when a linked proactive goal finishes, cancels, expires, or retires. */
507
+ registerGoalUnsubscribeHook = (hook) => {
508
+ if (!this.#active)
509
+ throw new Error('assistant-proactive: disposed');
510
+ if (typeof hook !== 'function')
511
+ throw new Error('assistant-proactive: invalid goal unsubscribe hook');
512
+ if (!this.#goalUnsubscribeHooks.has(hook) && this.#goalUnsubscribeHooks.size >= MAX_GOAL_UNSUBSCRIBE_HOOKS) {
513
+ throw new Error('assistant-proactive: goal unsubscribe hook limit reached');
514
+ }
515
+ this.#goalUnsubscribeHooks.add(hook);
516
+ return () => { this.#goalUnsubscribeHooks.delete(hook); };
517
+ };
518
+ /** Host-only bounded cleanup that retires proactive goal opportunities and unsubscribes linked EventTriggers sources. */
519
+ retireGoalSources = (input) => {
520
+ if (!this.#active)
521
+ throw new Error('assistant-proactive: disposed');
522
+ if (!input || typeof input !== 'object'
523
+ || (input.waitId !== undefined && (typeof input.waitId !== 'string' || input.waitId.trim().length === 0))
524
+ || (input.sourceId !== undefined && (typeof input.sourceId !== 'string' || input.sourceId.trim().length === 0))) {
525
+ throw new Error('assistant-proactive: invalid goal retire input');
526
+ }
527
+ const rawLinks = input.waitId !== undefined
528
+ ? this.#engine.sourcesForWait(input.waitId, input.scope)
529
+ : this.#engine.sourcesForGoal(input.scope, input.goalId);
530
+ const links = input.sourceId === undefined
531
+ ? rawLinks
532
+ : rawLinks.filter(link => link.sourceId === input.sourceId);
533
+ if (input.sourceId === undefined && input.waitId === undefined) {
534
+ this.#engine.closeGoal(input.scope, input.goalId, input.reason);
535
+ this.#preparations.store.cancelGoal(input.goalId, input.scope, `goal-${input.reason}`);
536
+ }
537
+ else if (input.waitId !== undefined) {
538
+ this.#engine.closeWait(input.waitId, input.scope, input.reason === 'expired' ? 'expired' : 'cancelled');
539
+ this.#preparations.store.cancelWait(input.waitId, input.scope);
540
+ }
541
+ const decidedAt = Date.now();
542
+ if (links.length === 0) {
543
+ const detached = this.#callEventTriggersUnsubscribe({
544
+ scope: input.scope,
545
+ goalId: input.goalId,
546
+ reason: input.reason,
547
+ ...(input.sourceId === undefined ? {} : { sourceId: input.sourceId }),
548
+ });
549
+ if (input.sourceId === undefined && detached.length === 0)
550
+ return Object.freeze([]);
551
+ const resolvedSourceId = input.sourceId ?? detached[0];
552
+ const hooksNotified = this.#notifyUnsubscribeHooks({
553
+ scope: input.scope,
554
+ goalId: input.goalId,
555
+ ...(input.waitId === undefined ? {} : { waitId: input.waitId }),
556
+ sourceId: resolvedSourceId,
557
+ reason: input.reason,
558
+ decidedAt,
559
+ });
560
+ return Object.freeze([Object.freeze({
561
+ scope: input.scope,
562
+ goalId: input.goalId,
563
+ sourceId: resolvedSourceId,
564
+ reason: input.reason,
565
+ detachedTriggers: detached,
566
+ hooksNotified,
567
+ })]);
568
+ }
569
+ return Object.freeze(links.map(link => this.#retireLink(link, input.reason, decidedAt)));
570
+ };
571
+ /** Host-only deterministic WP20/WP12 intake routing helper (no model calls, no ledger writes). */
572
+ routeIntakeObservation = (input, options = {}) => {
573
+ if (!this.#active)
574
+ throw new Error('assistant-proactive: disposed');
575
+ return planProactiveIntakeRoute(input, {
576
+ evaluationHealth: this.intakeEvaluationHealth(),
577
+ ...(options.sourcePolicy === undefined ? {} : { sourcePolicy: options.sourcePolicy }),
578
+ });
579
+ };
580
+ #onGoalChanged(payload) {
581
+ if (!this.#active)
582
+ return;
583
+ const signal = parseTerminalGoalChanged(payload);
584
+ if (!signal || !signal.nativeGoalId)
585
+ return;
586
+ const key = `${signal.sessionId ?? ''}\0${signal.nativeGoalId}\0${signal.reason}`;
587
+ if (this.#pendingGoalChanges.size < MAX_PENDING_GOAL_CHANGE_SIGNALS) {
588
+ this.#pendingGoalChanges.set(key, signal);
589
+ }
590
+ if (this.#goalChangeMicrotaskQueued)
591
+ return;
592
+ this.#goalChangeMicrotaskQueued = true;
593
+ queueMicrotask(() => {
594
+ this.#goalChangeMicrotaskQueued = false;
595
+ if (!this.#active) {
596
+ this.#pendingGoalChanges.clear();
597
+ return;
598
+ }
599
+ const batch = Array.from(this.#pendingGoalChanges.values());
600
+ this.#pendingGoalChanges.clear();
601
+ for (const item of batch)
602
+ this.#reconcileTerminalGoalSignal(item);
603
+ });
604
+ }
605
+ #reconcileTerminalGoalSignal(signal) {
606
+ if (!this.#active || !signal.nativeGoalId)
607
+ return;
608
+ let decisions;
609
+ try {
610
+ decisions = this.#engine.listByNativeGoal(signal.nativeGoalId, signal.sessionId);
611
+ }
612
+ catch {
613
+ return;
614
+ }
615
+ if (decisions.length === 0)
616
+ return;
617
+ const assistantGoals = this.ctx.get('assistantGoals');
618
+ const seenGoals = new Map();
619
+ for (const decision of decisions) {
620
+ if (signal.workspace !== undefined && decision.scope.workspace !== signal.workspace)
621
+ continue;
622
+ if (signal.preset !== undefined && decision.scope.preset !== signal.preset)
623
+ continue;
624
+ const goalKey = `${acceptanceDigest(decision.scope)}\0${decision.goalId}`;
625
+ if (!seenGoals.has(goalKey)) {
626
+ seenGoals.set(goalKey, {
627
+ scope: decision.scope,
628
+ goalId: decision.goalId,
629
+ nativeGoalId: decision.nativeGoalId,
630
+ sessionId: decision.sessionId,
631
+ });
632
+ }
633
+ }
634
+ for (const entry of seenGoals.values()) {
635
+ let effectiveReason = signal.reason;
636
+ if (typeof assistantGoals?.inspectGoalLifecycle === 'function') {
637
+ try {
638
+ const current = assistantGoals.inspectGoalLifecycle({ scope: entry.scope, goalId: entry.goalId });
639
+ if (current && current.native.goalId === entry.nativeGoalId && current.native.sessionId === entry.sessionId) {
640
+ if (current.native.phase === 'complete')
641
+ effectiveReason = 'completed';
642
+ else if (current.native.phase === 'cleared' || current.native.phase === 'blocked')
643
+ effectiveReason = 'cancelled';
644
+ else
645
+ continue;
646
+ }
647
+ }
648
+ catch {
649
+ // Proceed with the event-borne terminal signal when inspect is unavailable.
650
+ }
651
+ }
652
+ try {
653
+ this.retireGoalSources({ scope: entry.scope, goalId: entry.goalId, reason: effectiveReason });
654
+ }
655
+ catch {
656
+ // Bounded best-effort reconciliation must not crash the microtask turn.
657
+ }
658
+ }
659
+ }
660
+ #cleanupClosedWaitLinks(links, scope, waitReason) {
661
+ if (links.length === 0)
662
+ return;
663
+ const assistantGoals = this.ctx.get('assistantGoals');
664
+ const reasonByGoal = new Map();
665
+ const decidedAt = Date.now();
666
+ for (const link of links) {
667
+ let effectiveReason = reasonByGoal.get(link.goalId);
668
+ if (!reasonByGoal.has(link.goalId)) {
669
+ effectiveReason = waitReason;
670
+ if (typeof assistantGoals?.inspectGoalLifecycle === 'function') {
671
+ try {
672
+ const goal = assistantGoals.inspectGoalLifecycle({ scope, goalId: link.goalId });
673
+ if (goal?.native.phase === 'complete') {
674
+ effectiveReason = 'completed';
675
+ }
676
+ else if (goal?.native.phase === 'cleared' || goal?.native.phase === 'blocked') {
677
+ effectiveReason = 'cancelled';
678
+ }
679
+ else if (goal?.native.phase === 'paused' || goal?.native.phase === 'active') {
680
+ effectiveReason = waitReason === 'expired' ? 'expired' : undefined;
681
+ }
682
+ }
683
+ catch {
684
+ effectiveReason = waitReason;
685
+ }
686
+ }
687
+ reasonByGoal.set(link.goalId, effectiveReason);
688
+ }
689
+ if (effectiveReason === undefined)
690
+ continue;
691
+ if (effectiveReason !== waitReason || waitReason === 'expired') {
692
+ try {
693
+ this.#preparations.store.cancelGoal(link.goalId, scope, `goal-${effectiveReason}`);
694
+ }
695
+ catch {
696
+ // Non-fatal if wait cancellation already updated matching preparations.
697
+ }
698
+ }
699
+ this.#retireLink(link, effectiveReason, decidedAt);
700
+ }
701
+ }
702
+ #retireLink(link, reason, decidedAt) {
703
+ const detachedTriggers = this.#callEventTriggersUnsubscribe({
704
+ scope: link.scope,
705
+ goalId: link.goalId,
706
+ reason,
707
+ sourceId: link.sourceId,
708
+ ...(link.sourceDigest === undefined ? {} : { sourceDigest: link.sourceDigest }),
709
+ ...(link.definitionDigest === undefined ? {} : { definitionDigest: link.definitionDigest }),
710
+ });
711
+ const hooksNotified = this.#notifyUnsubscribeHooks({ ...link, reason, decidedAt });
712
+ return Object.freeze({
713
+ scope: link.scope,
714
+ goalId: link.goalId,
715
+ sourceId: link.sourceId,
716
+ reason,
717
+ detachedTriggers,
718
+ hooksNotified,
719
+ });
720
+ }
721
+ #callEventTriggersUnsubscribe(input) {
722
+ const eventTriggers = this.ctx.get('eventTriggers');
723
+ if (typeof eventTriggers?.unsubscribeGoalSources !== 'function')
724
+ return Object.freeze([]);
725
+ try {
726
+ const detached = eventTriggers.unsubscribeGoalSources(input);
727
+ const unique = [];
728
+ const seen = new Set();
729
+ for (const triggerId of detached) {
730
+ if (typeof triggerId === 'string' && triggerId.length > 0 && !seen.has(triggerId) && unique.length < 64) {
731
+ seen.add(triggerId);
732
+ unique.push(triggerId);
733
+ }
734
+ }
735
+ return Object.freeze(unique);
736
+ }
737
+ catch {
738
+ return Object.freeze([]);
739
+ }
740
+ }
741
+ #notifyUnsubscribeHooks(event) {
742
+ const dedupeKey = [
743
+ acceptanceDigest(event.scope),
744
+ event.goalId,
745
+ event.waitId ?? '',
746
+ event.sourceId,
747
+ event.sourceDigest ?? '',
748
+ event.definitionDigest ?? '',
749
+ event.reason,
750
+ ].join('\0');
751
+ if (this.#emittedGoalUnsubscribes.has(dedupeKey))
752
+ return 0;
753
+ this.#rememberGoalUnsubscribe(dedupeKey);
754
+ const frozen = Object.freeze({ ...event });
755
+ let notified = 0;
756
+ for (const hook of Array.from(this.#goalUnsubscribeHooks)) {
757
+ try {
758
+ hook(frozen);
759
+ notified += 1;
760
+ }
761
+ catch {
762
+ // Hook errors must never prevent subsequent cleanup listeners.
763
+ }
764
+ }
765
+ return notified;
766
+ }
767
+ #rememberGoalUnsubscribe(key) {
768
+ if (this.#emittedGoalUnsubscribes.has(key))
769
+ return;
770
+ if (this.#emittedGoalUnsubscribes.size >= MAX_REMEMBERED_GOAL_UNSUBSCRIBES) {
771
+ const oldest = this.#emittedGoalUnsubscribes.values().next().value;
772
+ if (oldest !== undefined)
773
+ this.#emittedGoalUnsubscribes.delete(oldest);
774
+ }
775
+ this.#emittedGoalUnsubscribes.add(key);
776
+ }
777
+ #scope(agent, feedback, consume = true) {
778
+ if (!this.#active)
779
+ throw new Error('assistant-proactive: disposed');
780
+ if (!agent || this.ctx.get('agents')?.get(agent.id) !== agent)
781
+ throw new Error('assistant-proactive: exact live agent required');
782
+ const delivery = this.ctx.get('assistantDelivery');
783
+ const owner = delivery?.preferencePrincipalForAgent(agent);
784
+ if (!owner || owner.scope.workspace !== agent.session.header.cwd || owner.scope.preset !== agent.session.header.agentPreset)
785
+ throw new Error('assistant-proactive: authenticated owner required');
786
+ const scope = { principalId: owner.principalId, ...owner.principalLineage, workspace: owner.scope.workspace, preset: owner.scope.preset };
787
+ if (feedback) {
788
+ const turn = delivery?.currentPreferenceTurn(agent);
789
+ if (!turn || acceptanceDigest({ principalId: turn.principalId, ...turn.principalLineage, workspace: turn.scope.workspace, preset: turn.scope.preset }) !== acceptanceDigest(scope))
790
+ throw new Error('assistant-proactive: current authenticated owner turn required');
791
+ }
792
+ const policy = this.ctx.get('assistantPolicy');
793
+ const decision = consume ? policy?.authorizeAgent(agent, feedback ? 'feedback' : 'inspect', { kind: 'goal', id: 'proactive-opportunities' })
794
+ : policy?.evaluateAgent(agent, feedback ? 'feedback' : 'inspect', { kind: 'goal', id: 'proactive-opportunities' });
795
+ if (decision?.effect !== 'allow')
796
+ throw new Error('assistant-proactive: policy denied');
797
+ return scope;
798
+ }
799
+ #formatOpportunity = (decision) => {
800
+ const preparation = this.#preparations.store.get(decision.id);
801
+ if (!preparation)
802
+ return decision;
803
+ return Object.freeze({
804
+ ...decision,
805
+ preparation: Object.freeze({
806
+ state: preparation.state,
807
+ reason: preparation.reason,
808
+ updatedAt: preparation.updatedAt,
809
+ ...(preparation.result ? {
810
+ output: preparation.result.output,
811
+ sessionId: preparation.result.sessionId,
812
+ usage: preparation.result.usage,
813
+ diagnostic: preparation.result.diagnostic,
814
+ verified: false,
815
+ } : {}),
816
+ }),
817
+ });
818
+ };
819
+ #attentionScopes(requested) {
820
+ if (requested !== undefined) {
821
+ if (!requested || typeof requested.workspace !== 'string' || !requested.workspace.startsWith('/') || typeof requested.preset !== 'string' || requested.preset.length === 0) {
822
+ throw new Error('assistant-proactive: invalid attention question scope');
823
+ }
824
+ return [{ workspace: requested.workspace, preset: requested.preset }];
825
+ }
826
+ const unique = new Map();
827
+ const addScope = (workspace, preset) => {
828
+ if (typeof workspace !== 'string' || !workspace.startsWith('/') || typeof preset !== 'string' || preset.length === 0)
829
+ return;
830
+ const key = `${workspace}\0${preset}`;
831
+ if (!unique.has(key))
832
+ unique.set(key, { workspace, preset });
833
+ };
834
+ for (const scope of this.#engine.listScopes())
835
+ addScope(scope.workspace, scope.preset);
836
+ try {
837
+ const delivery = this.ctx.get('assistantDelivery');
838
+ if (typeof delivery?.listOwnerRoutes === 'function') {
839
+ for (const route of delivery.listOwnerRoutes())
840
+ addScope(route.workspace, route.agentPreset);
841
+ }
842
+ }
843
+ catch { /* Optional Delivery discovery failed; continue with recorded proactive scopes. */ }
844
+ return [...unique.values()];
845
+ }
846
+ inspect = (agent, goalId) => {
847
+ const scope = this.#scope(agent, false);
848
+ this.#recordOwnerActivity(scope.workspace, scope.preset);
849
+ return this.#engine.list(scope, goalId).map(this.#formatOpportunity);
850
+ };
851
+ /** Host-only read-only draft inspection for owner operator surfaces (zero execution authority). */
852
+ inspectDrafts = (filter = {}) => {
853
+ if (!this.#active)
854
+ throw new Error('assistant-proactive: disposed');
855
+ if (filter.onlyDrafts && filter.state !== undefined && filter.state !== 'draft') {
856
+ return Object.freeze([]);
857
+ }
858
+ const effectiveState = filter.onlyDrafts ? 'draft' : filter.state;
859
+ const hasScopeParts = filter.workspace !== undefined || filter.preset !== undefined;
860
+ const records = this.#preparations.store.list({
861
+ ...(filter.scope !== undefined ? { scope: filter.scope } : {}),
862
+ ...(filter.goalId !== undefined ? { goalId: filter.goalId } : {}),
863
+ ...(effectiveState !== undefined ? { state: effectiveState } : {}),
864
+ ...(hasScopeParts ? { limit: 500 } : filter.limit === undefined ? {} : { limit: filter.limit }),
865
+ }).filter(record => (filter.workspace === undefined || record.decision.scope.workspace === filter.workspace)
866
+ && (filter.preset === undefined || record.decision.scope.preset === filter.preset));
867
+ const limit = typeof filter.limit === 'number' && Number.isSafeInteger(filter.limit) && filter.limit > 0
868
+ ? Math.min(filter.limit, 500) : 100;
869
+ return Object.freeze(records.slice(0, limit).map(record => {
870
+ const decision = this.#engine.get(record.id);
871
+ return Object.freeze({
872
+ id: record.id,
873
+ goalId: record.decision.goalId,
874
+ profileId: record.decision.profileId,
875
+ scope: record.decision.scope,
876
+ objective: record.decision.objective,
877
+ state: record.state,
878
+ ...(record.reason === undefined ? {} : { reason: record.reason }),
879
+ ...(decision?.feedback === undefined ? {} : { feedback: decision.feedback }),
880
+ decisionState: decision?.state ?? record.decision.state,
881
+ createdAt: record.createdAt,
882
+ updatedAt: record.updatedAt,
883
+ deadlineAt: record.deadlineAt,
884
+ ...(record.result === undefined ? {} : {
885
+ output: record.result.output,
886
+ ...(record.result.sessionId === undefined ? {} : { sessionId: record.result.sessionId }),
887
+ usage: record.result.usage,
888
+ ...(record.result.diagnostic === undefined ? {} : { diagnostic: record.result.diagnostic }),
889
+ }),
890
+ verified: false,
891
+ });
892
+ }));
893
+ };
894
+ /** Host-only opportunity decision inspection across owner scopes. */
895
+ inspectOpportunities = (filter = {}) => {
896
+ if (!this.#active)
897
+ throw new Error('assistant-proactive: disposed');
898
+ return Object.freeze(this.#engine.listAll(filter).map(this.#formatOpportunity));
899
+ };
900
+ /** Host-only action to accept or reject/dismiss an existing opportunity draft. */
901
+ resolveDraft = (input) => {
902
+ if (!this.#active)
903
+ throw new Error('assistant-proactive: disposed');
904
+ if (!input || typeof input.id !== 'string' || input.id.length === 0) {
905
+ throw new Error('assistant-proactive: invalid draft resolution input');
906
+ }
907
+ let mappedDecision = input.decision;
908
+ if (input.action !== undefined) {
909
+ if (input.action !== 'accept' && input.action !== 'reject' && input.action !== 'cancel') {
910
+ throw new Error('assistant-proactive: invalid draft resolution input');
911
+ }
912
+ const fromAction = input.action === 'accept' ? 'accepted' : 'rejected';
913
+ if (mappedDecision !== undefined && mappedDecision !== fromAction) {
914
+ throw new Error('assistant-proactive: invalid draft resolution input');
915
+ }
916
+ mappedDecision = fromAction;
917
+ }
918
+ if (mappedDecision !== 'accepted' && mappedDecision !== 'rejected') {
919
+ throw new Error('assistant-proactive: invalid draft resolution input');
920
+ }
921
+ const existing = this.#engine.get(input.id);
922
+ if (!existing)
923
+ return undefined;
924
+ if ((input.workspace !== undefined && existing.scope.workspace !== input.workspace)
925
+ || (input.preset !== undefined && existing.scope.preset !== input.preset)) {
926
+ throw new Error('assistant-proactive: draft scope mismatch');
927
+ }
928
+ if (input.action === 'accept') {
929
+ const preparation = this.#preparations.store.get(existing.id);
930
+ if (!preparation || preparation.state !== 'draft') {
931
+ throw new Error('assistant-proactive: draft is not ready to accept');
932
+ }
933
+ }
934
+ if (existing.state === 'closed' && existing.feedback === mappedDecision) {
935
+ this.#recordOwnerActivity(existing.scope.workspace, existing.scope.preset);
936
+ if (mappedDecision === 'rejected')
937
+ this.#preparations.store.cancel(existing.id);
938
+ return existing;
939
+ }
940
+ const resolved = this.#engine.feedback(existing.id, existing.scope, mappedDecision);
941
+ this.#recordOwnerActivity(existing.scope.workspace, existing.scope.preset);
942
+ if (mappedDecision === 'rejected')
943
+ this.#preparations.store.cancel(existing.id);
944
+ return resolved;
945
+ };
946
+ /** Host-only read-only view of WP22 proactive attention-loosening owner questions. */
947
+ inspectAttentionQuestions = (filter = {}) => {
948
+ if (!this.#active)
949
+ throw new Error('assistant-proactive: disposed');
950
+ const evaluation = this.ctx.get('assistantEvaluation');
951
+ if (!evaluation || typeof evaluation.attentionLooseningStatus !== 'function')
952
+ return Object.freeze([]);
953
+ const requestedScope = filter.scope ?? (filter.workspace !== undefined && filter.preset !== undefined
954
+ ? { workspace: filter.workspace, preset: filter.preset }
955
+ : undefined);
956
+ const scopes = this.#attentionScopes(requestedScope);
957
+ const items = [];
958
+ for (const scope of scopes) {
959
+ let status;
960
+ try {
961
+ status = evaluation.attentionLooseningStatus({ scope, cohort: { ...proactiveAttentionCohort } });
962
+ }
963
+ catch {
964
+ continue;
965
+ }
966
+ let questionStatus;
967
+ if (typeof evaluation.attentionOwnerQuestionStatus === 'function') {
968
+ try {
969
+ questionStatus = evaluation.attentionOwnerQuestionStatus({ scope, cohort: { ...proactiveAttentionCohort } });
970
+ }
971
+ catch {
972
+ questionStatus = undefined;
973
+ }
974
+ }
975
+ const proposalDecisions = new Map(status.proposals.map(entry => [entry.proposalId, entry.decision]));
976
+ const deliveries = new Map((questionStatus?.deliveries ?? []).map(entry => [entry.questionId, entry]));
977
+ const replies = new Map((questionStatus?.replies ?? []).map(entry => [entry.questionId, entry]));
978
+ const activeGrantId = status.grant?.grant.grantId;
979
+ for (const entry of status.questions) {
980
+ const question = entry.question;
981
+ const proposalDecision = proposalDecisions.get(question.proposalId) ?? null;
982
+ const delivery = deliveries.get(entry.questionId) ?? null;
983
+ const reply = replies.get(entry.questionId) ?? null;
984
+ const open = reply === null
985
+ && delivery?.status !== 'closed'
986
+ && delivery?.status !== 'expired'
987
+ && proposalDecision === null
988
+ && (activeGrantId === undefined || activeGrantId === question.grantId);
989
+ if (filter.includeResolved === false && !open)
990
+ continue;
991
+ items.push(Object.freeze({
992
+ questionId: entry.questionId,
993
+ scope: Object.freeze({ workspace: scope.workspace, preset: scope.preset }),
994
+ proposalId: question.proposalId,
995
+ parameter: question.change.parameter,
996
+ parentValue: question.change.parentValue,
997
+ candidateValue: question.change.candidateValue,
998
+ delta: question.change.delta,
999
+ exceeded: Object.freeze([...question.exceeded]),
1000
+ choices: question.choices,
1001
+ delivery: delivery === null ? null : Object.freeze({
1002
+ status: delivery.status,
1003
+ outboxId: delivery.outboxId,
1004
+ recordedAt: delivery.recordedAt,
1005
+ }),
1006
+ reply: reply === null ? null : Object.freeze({
1007
+ choice: reply.choice,
1008
+ repliedAt: reply.repliedAt,
1009
+ }),
1010
+ decision: proposalDecision === null ? null : Object.freeze({
1011
+ decision: proposalDecision.decision,
1012
+ reason: proposalDecision.reason,
1013
+ decidedAt: proposalDecision.decidedAt,
1014
+ }),
1015
+ open,
1016
+ createdAt: question.createdAt,
1017
+ }));
1018
+ }
1019
+ }
1020
+ items.sort((left, right) => right.createdAt - left.createdAt || left.questionId.localeCompare(right.questionId));
1021
+ const limit = typeof filter.limit === 'number' && Number.isSafeInteger(filter.limit) && filter.limit > 0
1022
+ ? Math.min(filter.limit, 500) : 50;
1023
+ return Object.freeze(items.slice(0, limit));
1024
+ };
1025
+ /** Host-only action delegating an owner attention reply to Evaluation's verified apply path. */
1026
+ resolveAttentionQuestion = (input) => {
1027
+ if (!this.#active)
1028
+ throw new Error('assistant-proactive: disposed');
1029
+ const scope = input?.scope ?? (input?.workspace !== undefined && input?.preset !== undefined
1030
+ ? { workspace: input.workspace, preset: input.preset }
1031
+ : undefined);
1032
+ if (!input || !scope || typeof scope.workspace !== 'string' || !scope.workspace.startsWith('/')
1033
+ || typeof scope.preset !== 'string' || scope.preset.length === 0
1034
+ || typeof input.questionId !== 'string' || input.questionId.length === 0
1035
+ || (input.choice !== 'authorize-once' && input.choice !== 'decline')) {
1036
+ throw new Error('assistant-proactive: invalid attention question reply input');
1037
+ }
1038
+ const evaluation = this.ctx.get('assistantEvaluation');
1039
+ if (!evaluation || typeof evaluation.applyAttentionOwnerQuestionReply !== 'function') {
1040
+ return Object.freeze({ status: 'rejected', reason: 'evaluation-unavailable' });
1041
+ }
1042
+ this.#recordOwnerActivity(scope.workspace, scope.preset);
1043
+ return Object.freeze(evaluation.applyAttentionOwnerQuestionReply({
1044
+ scope: { workspace: scope.workspace, preset: scope.preset },
1045
+ cohort: { ...proactiveAttentionCohort },
1046
+ questionId: input.questionId,
1047
+ choice: input.choice,
1048
+ }));
1049
+ };
1050
+ reconcilePreparations = () => this.#preparations.tick();
1051
+ feedback = (agent, id, feedback) => {
1052
+ const scope = this.#scope(agent, true);
1053
+ const decision = this.#engine.feedback(id, scope, feedback);
1054
+ this.#recordOwnerActivity(scope.workspace, scope.preset);
1055
+ if (feedback === 'rejected')
1056
+ this.#preparations.store.cancel(id);
1057
+ return decision;
1058
+ };
1059
+ }
1060
+ export function apply(ctx, config = {}) { new AssistantProactiveService(ctx, config); }
1061
+ export default { name, Config, apply };
1062
+ //# sourceMappingURL=index.js.map