Skip to content

Commit 7b84990

Browse files
author
linyuan.yang
committed
整理 agenda
1 parent bc37aff commit 7b84990

10 files changed

Lines changed: 112 additions & 175 deletions

File tree

‎packages/scorpio.ai/src/Agenda/Extractor/AgendaExtractor.ts‎

Lines changed: 8 additions & 59 deletions
Original file line numberDiff line numberDiff line change
@@ -8,47 +8,21 @@ import { TimeUtils } from "../../Utils/TimeUtils";
88
import { T_AgendaExtractorSystemPrompt, T_AgendaSelectorSystemPrompt, formatError } from "../../Core";
99
import {
1010
AgendaPriority,
11-
AgendaTimeUnit,
1211
AgendaTriggerAction,
13-
AgendaTriggerKind,
1412
type AgendaRecord,
1513
} from "../types";
16-
import { AgendaRenderMode, formatAgendaXml } from "../format";
14+
import { AgendaRenderMode, formatAgendaRecordsXml } from "../format";
15+
import { createAgendaTriggerSchemas } from "../triggerSchemas";
1716
import { type AgendaAction, AgendaActionType, IAgendaExtractor } from "./IAgendaExtractor";
1817
import { AgendaOverflowSelector } from "./AgendaOverflowSelector";
1918

20-
const RelativeTimeSchema = z.object({
21-
amount: z.number().int().positive(),
22-
unit: z.enum(AgendaTimeUnit),
23-
});
24-
2519
const ActionSchema = z.enum(AgendaTriggerAction).optional().describe('Per-trigger delivery mode. notify (default), notify_and_record (also records the fire into the conversation history), invoke.');
2620
const MessageSchema = z.string().min(1).describe('REQUIRED per-trigger fire-time text — the exact words delivered WHEN this trigger fires, phrased as a present-moment ping ("Time to drink water"), NOT as a request to set a reminder ("remind me to drink water in 2 min" ✗). No fallback to content; if there is no special wording, restate the content. Recorded fires re-enter the conversation, so request-like wording can make this very sync create a duplicate agenda.');
27-
28-
const TriggerSpecSchema = z.discriminatedUnion('kind', [
29-
z.object({
30-
kind: z.literal(AgendaTriggerKind.Absolute),
31-
at: z.string().describe('ISO datetime of the single fire moment.'),
32-
action: ActionSchema,
33-
message: MessageSchema,
34-
}),
35-
z.object({
36-
kind: z.literal(AgendaTriggerKind.Interval),
37-
every: RelativeTimeSchema.describe('Repeat interval, e.g. {amount:1,unit:"day"} = every day; {amount:90,unit:"minute"} = every 90 minutes.'),
38-
startAt: z.string().optional(),
39-
count: z.number().int().positive().optional(),
40-
action: ActionSchema,
41-
message: MessageSchema,
42-
}),
43-
z.object({
44-
kind: z.literal(AgendaTriggerKind.Cron),
45-
expr: z.string().describe('SIX-field cron: "sec min hour dom month dow". NOT five-field.'),
46-
startAt: z.string().optional(),
47-
count: z.number().int().positive().optional(),
48-
action: ActionSchema,
49-
message: MessageSchema,
50-
}),
51-
]);
21+
const { TriggerSpecSchema, TriggerEditSchema } = createAgendaTriggerSchemas({
22+
action: ActionSchema,
23+
message: MessageSchema,
24+
patchMessage: z.string().min(1).optional(),
25+
});
5226

5327
const CreateArgsSchema = z.object({
5428
content: z.string().describe('Canonical, self-contained title. A clean noun-phrase or imperative ("Submit weekly report", "Drink water", "Build a web matching game (timer / levels / shuffle / hints)"); not a reply or a kickoff phrase like "Start by ...". Do NOT bake relative time or schedule into the title ("remind me to drink water in 2 min" ✗ → "Drink water"); timing belongs in triggers. Match the user\'s language. Note: each trigger carries its own required message — content is not the fire-time fallback.'),
@@ -63,27 +37,6 @@ const SetPatchSchema = z.object({
6337
dueAt: z.string().nullable().optional(),
6438
}).describe('Item-level field changes. Omit when only the schedule changes.');
6539

66-
/**
67-
* op=patch 的载荷。kind 可选(只改 action / message 时不动 kind),所以不能用 discriminatedUnion;
68-
* 与 AgendaToolProvider 的 TriggerPatchSchema 同形,校验在 service.patchTrigger。
69-
*/
70-
const TriggerPatchSchema = z.object({
71-
kind: z.enum(AgendaTriggerKind).optional().describe('Only when switching trigger type; then the matching schedule field (at / every / expr) is mandatory.'),
72-
at: z.string().optional(),
73-
every: RelativeTimeSchema.optional(),
74-
expr: z.string().optional().describe('SIX-field cron.'),
75-
startAt: z.string().optional().describe('Explicitly reset the next fire instant (ISO).'),
76-
count: z.number().int().positive().optional(),
77-
action: ActionSchema,
78-
message: z.string().min(1).optional(),
79-
}).describe('Only the fields to change; everything else keeps its current value AND its fire progress.');
80-
81-
const TriggerEditSchema = z.discriminatedUnion('op', [
82-
z.object({ op: z.literal('add'), spec: TriggerSpecSchema }),
83-
z.object({ op: z.literal('patch'), id: z.number().describe('trigger id from <existing-agenda>.'), patch: TriggerPatchSchema }),
84-
z.object({ op: z.literal('remove'), id: z.number().describe('trigger id from <existing-agenda>.') }),
85-
]);
86-
8740
const AgendaExtractSchema = z.object({
8841
actions: z.array(z.discriminatedUnion("type", [
8942
z.object({ type: z.literal(AgendaActionType.Create), args: CreateArgsSchema }),
@@ -200,7 +153,7 @@ export class AgendaExtractor implements IAgendaExtractor {
200153
): ChatMessage[] {
201154
let human = conversation;
202155
if (existingItems.length > 0) {
203-
human += `\n<existing-agenda>\n${AgendaExtractor.renderRecords(existingItems, mode)}\n</existing-agenda>`;
156+
human += `\n<existing-agenda>\n${formatAgendaRecordsXml(existingItems, mode)}\n</existing-agenda>`;
204157
}
205158
human += `\n<now>${now}</now>`;
206159
return [
@@ -219,8 +172,4 @@ export class AgendaExtractor implements IAgendaExtractor {
219172
];
220173
}
221174

222-
private static renderRecords(records: AgendaRecord[], mode: AgendaRenderMode): string {
223-
return records.map(record => formatAgendaXml(record, mode)).join('\n');
224-
}
225-
226175
}

‎packages/scorpio.ai/src/Agenda/Extractor/AgendaOverflowSelector.ts‎

Lines changed: 7 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@ import {
88
estimateTextTokens,
99
type ChatMessage,
1010
} from "../../Saver";
11-
import { AgendaRenderMode, formatAgendaXml } from "../format";
11+
import { AgendaRenderMode, formatAgendaRecordsXml, formatAgendaXml } from "../format";
1212
import {
1313
AGENDA_SYNC_CANDIDATES_PER_BATCH,
1414
AGENDA_SYNC_FINAL_CANDIDATE_LIMIT,
@@ -151,8 +151,7 @@ export class AgendaOverflowSelector {
151151
this.logger?.warn(`AgendaSync selector batch cap reached; locally ranked ${records.length - scannedCount} lower-relevance item(s) were not sent to the model`);
152152
}
153153

154-
const sourceIndex = new Map(records.map((record, index) => [record.item.id, index] as const));
155-
const localRelevance = new Map(rankedRecords.map(candidate => [candidate.record.item.id, candidate.relevance] as const));
154+
const rankedById = new Map(rankedRecords.map(candidate => [candidate.record.item.id, candidate] as const));
156155
const selected = new Map<number, RankedRecord>();
157156

158157
for (const chunk of activeChunks) {
@@ -174,18 +173,19 @@ export class AgendaOverflowSelector {
174173
selected.set(candidate.id, {
175174
record,
176175
relevance,
177-
sourceIndex: sourceIndex.get(candidate.id) ?? records.length,
176+
sourceIndex: rankedById.get(candidate.id)?.sourceIndex ?? records.length,
178177
});
179178
}
180179
}
181180
} catch (error: any) {
182181
this.logger?.warn(`Agenda selector batch failed; using local ranking: ${formatError(error)}`);
183182
for (const record of chunk.slice(0, AGENDA_SYNC_CANDIDATES_PER_BATCH)) {
184183
if (selected.has(record.item.id)) continue;
184+
const ranked = rankedById.get(record.item.id);
185185
selected.set(record.item.id, {
186186
record,
187-
relevance: Math.min(25, localRelevance.get(record.item.id) ?? 0),
188-
sourceIndex: sourceIndex.get(record.item.id) ?? records.length,
187+
relevance: Math.min(25, ranked?.relevance ?? 0),
188+
sourceIndex: ranked?.sourceIndex ?? records.length,
189189
});
190190
}
191191
}
@@ -231,7 +231,7 @@ export class AgendaOverflowSelector {
231231
intents.map(intent => `- ${intent}`).join('\n'),
232232
`</agenda-intents>`,
233233
`<agenda-cards>`,
234-
AgendaOverflowSelector.renderRecords(records),
234+
formatAgendaRecordsXml(records, AgendaRenderMode.Compact),
235235
`</agenda-cards>`,
236236
`<now>${now}</now>`,
237237
].join('\n'),
@@ -284,10 +284,6 @@ export class AgendaOverflowSelector {
284284
.sort((a, b) => b.relevance - a.relevance || a.sourceIndex - b.sourceIndex);
285285
}
286286

287-
private static renderRecords(records: AgendaRecord[]): string {
288-
return records.map(record => formatAgendaXml(record, AgendaRenderMode.Compact)).join('\n');
289-
}
290-
291287
private static normalize(value: string): string {
292288
return value.toLowerCase().replace(/\s+/g, ' ').trim();
293289
}

‎packages/scorpio.ai/src/Agenda/Service/AgendaService.ts‎

Lines changed: 4 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -37,7 +37,7 @@ import {
3737
IAgendaExtractor,
3838
} from "../Extractor/IAgendaExtractor";
3939
import { IAgendaTriggerEngine } from "../TriggerEngine/IAgendaTriggerEngine";
40-
import { IAgendaStore, type PendingAgendaJobRow, AgendaPendingJobType } from "../Storage/IAgendaStore";
40+
import { IAgendaStore, type PendingAgendaJobRow } from "../Storage/IAgendaStore";
4141
import { TimeUtils } from "../../Utils/TimeUtils";
4242
import { computeInitialNextFire, relativeToMs } from "../time";
4343
import { type AgendaToolDescs, IAgendaService } from "./IAgendaService";
@@ -523,13 +523,13 @@ export class AgendaService implements IAgendaService {
523523
}
524524
if (!next) break;
525525
try {
526-
const applied = await this.runPendingJob(next);
526+
const applied = await this.runExtractJob(next.messages, next.channelSessionId);
527527
this.agendaStore.deletePendingJob(next.id);
528-
this.logger?.info(`agenda pending ${next.type} #${next.id} done: ${applied} action(s) applied`);
528+
this.logger?.info(`agenda pending extract #${next.id} done: ${applied} action(s) applied`);
529529
} catch (e: any) {
530530
const errMsg = formatError(e).slice(0, ERROR_MESSAGE_MAX_LEN);
531531
try { this.agendaStore.markPendingJobFailed(next.id, errMsg, Date.now()); } catch { /* store closed; swallow */ }
532-
this.logger?.warn(`agenda pending ${next.type} #${next.id} failed: ${errMsg}`);
532+
this.logger?.warn(`agenda pending extract #${next.id} failed: ${errMsg}`);
533533
}
534534
}
535535
} finally {
@@ -539,13 +539,6 @@ export class AgendaService implements IAgendaService {
539539
}
540540
}
541541

542-
private async runPendingJob(job: PendingAgendaJobRow): Promise<number> {
543-
switch (job.type) {
544-
case AgendaPendingJobType.Extract:
545-
return this.runExtractJob(job.messages ?? [], job.channelSessionId);
546-
}
547-
}
548-
549542
private async runExtractJob(messages: ChatMessage[], channelSessionId: number): Promise<number> {
550543
if (!this.extractor || messages.length === 0) return 0;
551544
// 只把 Pending 条目喂给 sync extractor:done/cancelled/expired 是只读历史,sync 对它们没有可操作动作,

‎packages/scorpio.ai/src/Agenda/Storage/AgendaStore.ts‎

Lines changed: 2 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,6 @@ import { T_AgendaDbPath } from "../../Core";
88
import type { ChatMessage } from "../../Saver";
99
import { DEFAULT_TRIGGER_FIRES_LIMIT, ERROR_MESSAGE_MAX_LEN, MAX_TRIGGER_FIRES_PER_ITEM, PENDING_JOB_LIST_HARD_CAP } from "../limits";
1010
import {
11-
AgendaPendingJobType,
1211
type AgendaPendingJobStatus,
1312
type PendingAgendaJobRow,
1413
IAgendaStore,
@@ -473,7 +472,7 @@ export class AgendaStore implements IAgendaStore {
473472
@jobType, @channelSessionId, @payloadJson, 'pending', 0, @now, @now
474473
)
475474
`).run({
476-
jobType: AgendaPendingJobType.Extract,
475+
jobType: 'extract',
477476
channelSessionId,
478477
payloadJson: JSON.stringify({ messages }),
479478
now,
@@ -538,13 +537,11 @@ export class AgendaStore implements IAgendaStore {
538537
}
539538

540539
private mapPendingRow(r: any): PendingAgendaJobRow {
541-
const type = this.normalizePendingJobType(r.job_type);
542540
const payload = this.parsePendingPayload(r.payload_json);
543541
return {
544542
id: r.id,
545-
type,
546543
channelSessionId: Number(r.channel_session_id) || 0,
547-
messages: type === AgendaPendingJobType.Extract ? (payload.messages ?? []) : undefined,
544+
messages: payload.messages ?? [],
548545
status: this.normalizePendingStatus(r.status),
549546
attemptCount: r.attempt_count ?? 0,
550547
errorMessage: r.error_message ?? null,
@@ -564,10 +561,6 @@ export class AgendaStore implements IAgendaStore {
564561
}
565562
}
566563

567-
private normalizePendingJobType(type: string | undefined | null): AgendaPendingJobType {
568-
return type === AgendaPendingJobType.Extract ? AgendaPendingJobType.Extract : AgendaPendingJobType.Extract;
569-
}
570-
571564
private normalizePendingStatus(status: string | undefined | null): AgendaPendingJobStatus {
572565
return status === 'failed' ? 'failed' : 'pending';
573566
}

‎packages/scorpio.ai/src/Agenda/Storage/IAgendaStore.ts‎

Lines changed: 1 addition & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -6,21 +6,14 @@ import type {
66
AgendaTriggerFire,
77
} from "../types";
88

9-
// ── 待处理 job 队列 ──
10-
11-
export enum AgendaPendingJobType {
12-
Extract = 'extract',
13-
}
14-
159
export type AgendaPendingJobStatus = 'pending' | 'failed';
1610

1711
export interface PendingAgendaJobRow {
1812
id: number;
19-
type: AgendaPendingJobType;
2013
/** 该 job 来自哪个 channel session;drain 时回填到 createTrigger 的 channelSessionId。 */
2114
channelSessionId: number;
2215
/** Extract 任务的对话快照。 */
23-
messages?: ChatMessage[];
16+
messages: ChatMessage[];
2417
status: AgendaPendingJobStatus;
2518
attemptCount: number;
2619
errorMessage: string | null;

‎packages/scorpio.ai/src/Agenda/Tools/AgendaToolProvider.ts‎

Lines changed: 5 additions & 74 deletions
Original file line numberDiff line numberDiff line change
@@ -5,9 +5,7 @@ import {
55
AgendaCloseOutcome,
66
AgendaPriority,
77
AgendaStatus,
8-
AgendaTimeUnit,
98
AgendaTriggerAction,
10-
AgendaTriggerKind,
119
type AgendaCreateArgs,
1210
type AgendaEditArgs,
1311
type AgendaListFilter,
@@ -16,6 +14,7 @@ import {
1614
import { IAgendaService } from "../Service/IAgendaService";
1715
import { AgendaRenderMode, formatAgendaXml } from "../format";
1816
import { DEFAULT_LIST_LIMIT, DETAIL_FIRES_LIMIT } from "../limits";
17+
import { createAgendaTriggerSchemas } from "../triggerSchemas";
1918

2019
export const AGENDA_CREATE_TOOL_NAME = 'agenda_create' as const;
2120
export const AGENDA_LIST_TOOL_NAME = 'agenda_list' as const;
@@ -30,11 +29,6 @@ const AGENDA_WIKI_TOOL_DESCRIPTION = [
3029
'No parameters.',
3130
].join('\n');
3231

33-
const RelativeTimeSchema = z.object({
34-
amount: z.number().int().positive(),
35-
unit: z.enum(AgendaTimeUnit).describe('minute / hour / day / week.'),
36-
});
37-
3832
const ActionSchema = z.enum(AgendaTriggerAction).optional().describe([
3933
'What happens when this trigger fires:',
4034
'- notify (default) = plain-text reminder',
@@ -62,74 +56,11 @@ const AssigneeSchema = z.enum(AgendaAssignee).optional().describe([
6256
'Orthogonal to trigger.action.',
6357
].join('\n'));
6458
const AssigneeNameSchema = z.string().optional().describe('Third-party name; only meaningful with assignee=other, ignored otherwise.');
65-
66-
const StartAtSchema = z.string().optional().describe('ISO of FIRST fire; omit for default.');
67-
const CountSchema = z.number().int().positive().optional().describe('Total fire count; omit for unlimited.');
68-
69-
const CRON_EXPR_DESC = 'SIX-field cron: "sec min hour dom month dow" (NOT 5-field). Example: "0 0 9 * * 1-5" = 9am weekdays.';
70-
71-
const TriggerSpecSchema = z.discriminatedUnion('kind', [
72-
z.object({
73-
kind: z.literal(AgendaTriggerKind.Absolute),
74-
at: z.string().describe('ISO datetime, e.g. "2026-09-19T09:00:00". Compute relative times yourself.'),
75-
action: ActionSchema,
76-
message: MessageSchema,
77-
}).describe('One-shot trigger.'),
78-
z.object({
79-
kind: z.literal(AgendaTriggerKind.Interval),
80-
every: RelativeTimeSchema.describe('Repeat interval, e.g. {amount:1,unit:"day"}.'),
81-
startAt: StartAtSchema,
82-
count: CountSchema,
83-
action: ActionSchema,
84-
message: MessageSchema,
85-
}).describe('Fixed-cadence recurrence.'),
86-
z.object({
87-
kind: z.literal(AgendaTriggerKind.Cron),
88-
expr: z.string().describe(CRON_EXPR_DESC),
89-
startAt: StartAtSchema,
90-
count: CountSchema,
91-
action: ActionSchema,
92-
message: MessageSchema,
93-
}).describe('Calendar-aligned recurrence.'),
94-
]);
95-
96-
/**
97-
* op=patch 的载荷:全字段可选、只改传入的部分,fireCount / lastFiredAt 保留。
98-
*
99-
* 不能用 discriminatedUnion(kind 本身可选——大多数 patch 就是「只改 action / 只改 message」,
100-
* 不动 kind),所以 schedule 字段平铺 + 用 describe 说清 kind 与 at/every/expr 的配对约束,
101-
* 真正的校验在 AgendaService.patchTrigger 里做。
102-
*/
103-
const TriggerPatchSchema = z.object({
104-
kind: z.enum(AgendaTriggerKind).optional().describe([
105-
'Only when SWITCHING trigger type; you must then also pass the matching schedule field',
106-
'(absolute→at / interval→every / cron→expr), otherwise the call is rejected.',
107-
'Omit to keep the current type — most patches only touch action / message.',
108-
].join('\n')),
109-
at: z.string().describe('New ISO instant; for kind=absolute.').optional(),
110-
every: RelativeTimeSchema.describe('New interval; for kind=interval.').optional(),
111-
expr: z.string().describe(`New cron expression; for kind=cron. ${CRON_EXPR_DESC}`).optional(),
112-
startAt: z.string().optional().describe('Explicitly reset the NEXT fire instant (ISO). Use alone to postpone one occurrence without touching the cadence.'),
113-
count: CountSchema,
59+
const { TriggerSpecSchema, TriggerEditSchema } = createAgendaTriggerSchemas({
11460
action: ActionSchema,
115-
message: z.string().min(1).optional().describe(`Rewrite the fire-time text. ${MESSAGE_DESC}`),
116-
}).describe('Fields to change; anything omitted keeps its current value, and fire progress is preserved.');
117-
118-
const TriggerEditSchema = z.discriminatedUnion('op', [
119-
z.object({
120-
op: z.literal('add'),
121-
spec: TriggerSpecSchema.describe('Same shape as agenda_create.triggers[i].'),
122-
}).describe('Append a new trigger.'),
123-
z.object({
124-
op: z.literal('patch'),
125-
id: z.number().describe('Existing trigger id (from agenda_list / agenda_get / <existing-agenda> XML).'),
126-
patch: TriggerPatchSchema,
127-
}).describe('Partially change one trigger, keeping its fire progress.'),
128-
z.object({
129-
op: z.literal('remove'),
130-
id: z.number().describe('Existing trigger id.'),
131-
}).describe('Disable one trigger. To reschedule, prefer op=patch — remove+add loses fire progress.'),
132-
]);
61+
message: MessageSchema,
62+
patchMessage: z.string().min(1).optional().describe(`Rewrite the fire-time text. ${MESSAGE_DESC}`),
63+
});
13364

13465
export class AgendaToolProvider {
13566
/**

0 commit comments

Comments
 (0)