@hyperwindmill/caretaker-cli 0.31.0 → 0.33.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/dist/cli/web/mcp_bridge.d.ts +1 -0
- package/dist/cli/web/mcp_bridge.d.ts.map +1 -1
- package/dist/cli/web/mcp_bridge.js +11 -2
- package/dist/cli/web/scheduler/cycle_events.d.ts +8 -3
- package/dist/cli/web/scheduler/cycle_events.d.ts.map +1 -1
- package/dist/cli/web/scheduler/cycle_events.js +2 -0
- package/dist/cli/web/scheduler/email_triage.d.ts +70 -0
- package/dist/cli/web/scheduler/email_triage.d.ts.map +1 -0
- package/dist/cli/web/scheduler/email_triage.js +262 -0
- package/dist/cli/web/scheduler/email_triage_agent.d.ts +16 -0
- package/dist/cli/web/scheduler/email_triage_agent.d.ts.map +1 -0
- package/dist/cli/web/scheduler/email_triage_agent.js +94 -0
- package/dist/cli/web/scheduler/heartbeat.d.ts +1 -1
- package/dist/cli/web/scheduler/heartbeat.d.ts.map +1 -1
- package/dist/cli/web/scheduler/heartbeat.js +9 -5
- package/dist/cli/web/scheduler/service_runs.d.ts +12 -0
- package/dist/cli/web/scheduler/service_runs.d.ts.map +1 -0
- package/dist/cli/web/scheduler/service_runs.js +39 -0
- package/dist/cli/web/scheduler.d.ts +9 -0
- package/dist/cli/web/scheduler.d.ts.map +1 -1
- package/dist/cli/web/scheduler.js +25 -1
- package/dist/cli/web/server.d.ts.map +1 -1
- package/dist/cli/web/server.js +34 -1
- package/dist/harness/tools/builtin/email_tools.d.ts +1 -0
- package/dist/harness/tools/builtin/email_tools.d.ts.map +1 -1
- package/dist/harness/tools/builtin/email_tools.js +41 -1
- package/dist/harness/tools/builtin/index.d.ts +2 -2
- package/dist/harness/tools/builtin/index.d.ts.map +1 -1
- package/dist/harness/tools/builtin/index.js +3 -2
- package/dist/lib/email.d.ts +20 -0
- package/dist/lib/email.d.ts.map +1 -1
- package/dist/lib/email.js +107 -33
- package/dist/webview/standalone.js +644 -333
- package/dist/webview/standalone.js.map +4 -4
- package/package.json +3 -3
|
@@ -5,6 +5,7 @@ export declare function issueBridgeToken(agentId?: string, opts?: {
|
|
|
5
5
|
workdir: string;
|
|
6
6
|
};
|
|
7
7
|
execOnly?: boolean;
|
|
8
|
+
only?: string[];
|
|
8
9
|
}): string;
|
|
9
10
|
export declare function revokeBridgeToken(token: string): void;
|
|
10
11
|
export declare function setTaskBridgeUrl(url: string): void;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"mcp_bridge.d.ts","sourceRoot":"","sources":["../../../src/cli/web/mcp_bridge.ts"],"names":[],"mappings":"AAeA,OAAO,KAAK,EAAE,IAAI,EAAE,MAAM,MAAM,CAAC;
|
|
1
|
+
{"version":3,"file":"mcp_bridge.d.ts","sourceRoot":"","sources":["../../../src/cli/web/mcp_bridge.ts"],"names":[],"mappings":"AAeA,OAAO,KAAK,EAAE,IAAI,EAAE,MAAM,MAAM,CAAC;AAmBjC,wBAAgB,gBAAgB,CAC9B,OAAO,SAAK,EACZ,IAAI,GAAE;IACJ,IAAI,CAAC,EAAE;QAAE,SAAS,EAAE,MAAM,CAAC;QAAC,OAAO,EAAE,MAAM,CAAA;KAAE,CAAC;IAC9C,QAAQ,CAAC,EAAE,OAAO,CAAC;IACnB,IAAI,CAAC,EAAE,MAAM,EAAE,CAAC;CACZ,GACL,MAAM,CASR;AACD,wBAAgB,iBAAiB,CAAC,KAAK,EAAE,MAAM,GAAG,IAAI,CAErD;AAGD,wBAAgB,gBAAgB,CAAC,GAAG,EAAE,MAAM,GAAG,IAAI,CAElD;AACD,wBAAgB,gBAAgB,IAAI,MAAM,GAAG,IAAI,CAEhD;AAED,wBAAgB,kBAAkB,CAAC,GAAG,EAAE,IAAI,GAAG,IAAI,CA8BlD"}
|
|
@@ -21,7 +21,12 @@ import { loadAgents } from '../../store/json.js';
|
|
|
21
21
|
const activeTokens = new Map();
|
|
22
22
|
export function issueBridgeToken(agentId = '', opts = {}) {
|
|
23
23
|
const token = randomBytes(24).toString('hex');
|
|
24
|
-
activeTokens.set(token, {
|
|
24
|
+
activeTokens.set(token, {
|
|
25
|
+
agentId,
|
|
26
|
+
exec: opts.exec,
|
|
27
|
+
execOnly: opts.execOnly,
|
|
28
|
+
only: opts.only,
|
|
29
|
+
});
|
|
25
30
|
return token;
|
|
26
31
|
}
|
|
27
32
|
export function revokeBridgeToken(token) {
|
|
@@ -50,7 +55,11 @@ export function registerTaskBridge(app) {
|
|
|
50
55
|
? (await loadAgents().catch(() => [])).find((a) => a.id === agentId)
|
|
51
56
|
: undefined;
|
|
52
57
|
const extraTools = tokenInfo.exec ? [makeRunCommandTool(tokenInfo.exec)] : [];
|
|
53
|
-
const tools = tokenInfo.
|
|
58
|
+
const tools = tokenInfo.only
|
|
59
|
+
? builtinMcpTools().filter((t) => tokenInfo.only.includes(t.name))
|
|
60
|
+
: tokenInfo.execOnly
|
|
61
|
+
? extraTools
|
|
62
|
+
: [...builtinMcpTools(), ...extraTools];
|
|
54
63
|
const server = buildBuiltinMcpServer(undefined, { callerAgent, tools });
|
|
55
64
|
const transport = new StreamableHTTPServerTransport({
|
|
56
65
|
sessionIdGenerator: undefined, // stateless
|
|
@@ -1,5 +1,10 @@
|
|
|
1
1
|
import type { MessageRecord } from '../../../session/types.js';
|
|
2
|
-
export type CycleEvent =
|
|
2
|
+
export type CycleEvent =
|
|
3
|
+
/** A user turn known only mid-run (the triage prompt is built after listing mail). */
|
|
4
|
+
{
|
|
5
|
+
type: 'user';
|
|
6
|
+
text: string;
|
|
7
|
+
} | {
|
|
3
8
|
type: 'chunk';
|
|
4
9
|
text: string;
|
|
5
10
|
} | {
|
|
@@ -20,12 +25,12 @@ export type CycleEvent = {
|
|
|
20
25
|
type: 'error';
|
|
21
26
|
message: string;
|
|
22
27
|
};
|
|
23
|
-
export declare function beginCycleStream(sessionId: string, prompt: MessageRecord): void;
|
|
28
|
+
export declare function beginCycleStream(sessionId: string, prompt: MessageRecord | null): void;
|
|
24
29
|
export declare function emitCycleEvent(sessionId: string, ev: CycleEvent): void;
|
|
25
30
|
/** Attach to a running cycle. Snapshot and attach happen synchronously, so no
|
|
26
31
|
* event can fall between them. `null` when the cycle is not running. */
|
|
27
32
|
export declare function watchCycleStream(sessionId: string, listener: (ev: CycleEvent) => void): {
|
|
28
|
-
prompt: MessageRecord;
|
|
33
|
+
prompt: MessageRecord | null;
|
|
29
34
|
events: CycleEvent[];
|
|
30
35
|
unwatch: () => void;
|
|
31
36
|
} | null;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"cycle_events.d.ts","sourceRoot":"","sources":["../../../../src/cli/web/scheduler/cycle_events.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"cycle_events.d.ts","sourceRoot":"","sources":["../../../../src/cli/web/scheduler/cycle_events.ts"],"names":[],"mappings":"AAOA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,2BAA2B,CAAC;AAE/D,MAAM,MAAM,UAAU;AACpB,sFAAsF;AACpF;IAAE,IAAI,EAAE,MAAM,CAAC;IAAC,IAAI,EAAE,MAAM,CAAA;CAAE,GAC9B;IAAE,IAAI,EAAE,OAAO,CAAC;IAAC,IAAI,EAAE,MAAM,CAAA;CAAE,GAC/B;IAAE,IAAI,EAAE,UAAU,CAAC;IAAC,IAAI,EAAE,MAAM,CAAA;CAAE,GAClC;IAAE,IAAI,EAAE,WAAW,CAAC;IAAC,EAAE,EAAE,MAAM,CAAC;IAAC,IAAI,EAAE,MAAM,CAAC;IAAC,IAAI,EAAE,OAAO,CAAA;CAAE,GAC9D;IAAE,IAAI,EAAE,aAAa,CAAC;IAAC,EAAE,EAAE,MAAM,CAAC;IAAC,OAAO,EAAE,MAAM,CAAA;CAAE,GACpD;IAAE,IAAI,EAAE,MAAM,CAAA;CAAE,GAChB;IAAE,IAAI,EAAE,OAAO,CAAC;IAAC,OAAO,EAAE,MAAM,CAAA;CAAE,CAAC;AAWvC,wBAAgB,gBAAgB,CAAC,SAAS,EAAE,MAAM,EAAE,MAAM,EAAE,aAAa,GAAG,IAAI,GAAG,IAAI,CAEtF;AAED,wBAAgB,cAAc,CAAC,SAAS,EAAE,MAAM,EAAE,EAAE,EAAE,UAAU,GAAG,IAAI,CAgBtE;AAED;yEACyE;AACzE,wBAAgB,gBAAgB,CAC9B,SAAS,EAAE,MAAM,EACjB,QAAQ,EAAE,CAAC,EAAE,EAAE,UAAU,KAAK,IAAI,GACjC;IAAE,MAAM,EAAE,aAAa,GAAG,IAAI,CAAC;IAAC,MAAM,EAAE,UAAU,EAAE,CAAC;IAAC,OAAO,EAAE,MAAM,IAAI,CAAA;CAAE,GAAG,IAAI,CAWpF"}
|
|
@@ -2,6 +2,8 @@
|
|
|
2
2
|
// the chat's own stream events keyed by session id; WebSocket watchers attach
|
|
3
3
|
// to a running cycle and replay what has happened so far, then follow it.
|
|
4
4
|
// Finished cycles are dropped from the map — watchers then load from disk.
|
|
5
|
+
// Service runs (heartbeat, email triage) use the same channel keyed by run id;
|
|
6
|
+
// see service_runs.ts.
|
|
5
7
|
const running = new Map();
|
|
6
8
|
export function beginCycleStream(sessionId, prompt) {
|
|
7
9
|
running.set(sessionId, { prompt, events: [], listeners: new Set() });
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
import { type EmailAccount, type OutgoingMail, type TriageEnvelope, type listUnseenEnvelopes } from '../../../lib/email.js';
|
|
2
|
+
import type { MessageRecord } from '../../../session/types.js';
|
|
3
|
+
import type { AgentConfig, CaretakerConfig, ProviderConfig, ServiceConfig } from '../../../types.js';
|
|
4
|
+
import { serviceRunCallbacks } from './service_runs.js';
|
|
5
|
+
export declare const TRIAGE_INSTRUCTIONS = "You are triaging an inbox. Classify every unread email below into exactly one bucket:\n\n- IMPORTANT: needs action soon: outages, blocked users or customers, failures, direct requests with a deadline.\n- INFORMATION: worth knowing, no immediate action.\n- TRASH: noise: automated notifications without a decision, time tracking, routine bot chatter. Count only, never list.\n\nYour final message must contain only the report, in exactly this shape, starting with \"## IMPORTANT\". Every bucket header is always present; when a table would be empty, write \"_No important emails._\" or \"_No information emails._\" instead of it.\n\n## IMPORTANT\n| From | Subject | Category | Summary | Suggested Action |\n\n## INFORMATION\n| From | Subject | Category | Summary | Suggested Action |\n\n## TRASH\nN emails classified as trash (not listed).\n\nHeaders, bucket names and the table header row are literal and must never be translated, whatever language the rest of the report is written in.\n\nGuidelines:\n- Work from the envelopes (From, Subject, Date). Open a body with email_read only when the subject is not enough.\n- Cluster related notifications into one row.\n- Other tools you have (for example an issue tracker) may be used to understand a reference in an email.\n- Do not send mail: your final message is delivered automatically.";
|
|
6
|
+
export type TriageStop = 'done' | 'max_turns' | 'aborted';
|
|
7
|
+
export declare function buildTriagePrompt(p: {
|
|
8
|
+
accountName: string;
|
|
9
|
+
extra: string;
|
|
10
|
+
envelopes: TriageEnvelope[];
|
|
11
|
+
}): string;
|
|
12
|
+
/** The report is the last non-empty assistant message, from its `## IMPORTANT`
|
|
13
|
+
* line on. A truncated run (max_turns/aborted) never yields one: its last
|
|
14
|
+
* message may be a half-finished "let me read uid 42". */
|
|
15
|
+
export declare function extractReport(messages: MessageRecord[], stop: TriageStop): string | null;
|
|
16
|
+
/** Envelopes per run: unset → 50; otherwise 1..MAX_SCAN. Only envelopes reach
|
|
17
|
+
* the prompt (one line each), so the cap is the scan window, not email_fetch's
|
|
18
|
+
* MAX_FETCH, which bounds full bodies. */
|
|
19
|
+
export declare function triageLimit(max: number | undefined): number;
|
|
20
|
+
export declare function triageSubject(prefix: string, count: number, now: Date): string;
|
|
21
|
+
export declare function parseRecipients(raw: string | undefined): string[];
|
|
22
|
+
/** Preflight: everything that can be checked before touching IMAP. Looks the
|
|
23
|
+
* raw record up first (emailAccounts drops disabled ones) so each failure has
|
|
24
|
+
* its own message. Not `visibleAccounts`: a scoped mailbox is a readable
|
|
25
|
+
* error here, not an invisible one. */
|
|
26
|
+
export declare function resolveTriageAccount(services: ServiceConfig[], service: ServiceConfig, agentId: string): {
|
|
27
|
+
account: EmailAccount;
|
|
28
|
+
} | {
|
|
29
|
+
error: string;
|
|
30
|
+
};
|
|
31
|
+
export type TriageAgentInput = {
|
|
32
|
+
agent: AgentConfig;
|
|
33
|
+
provider: ProviderConfig;
|
|
34
|
+
prompt: string;
|
|
35
|
+
account: EmailAccount;
|
|
36
|
+
workingDir: string;
|
|
37
|
+
signal: AbortSignal;
|
|
38
|
+
/** Live-stream hooks for the log viewer; spread into the run's callbacks. */
|
|
39
|
+
stream: ReturnType<typeof serviceRunCallbacks>;
|
|
40
|
+
};
|
|
41
|
+
export type TriageDeps = {
|
|
42
|
+
load(): Promise<{
|
|
43
|
+
agents: AgentConfig[];
|
|
44
|
+
config: CaretakerConfig;
|
|
45
|
+
}>;
|
|
46
|
+
listEnvelopes(account: EmailAccount, max: number, signal: AbortSignal): ReturnType<typeof listUnseenEnvelopes>;
|
|
47
|
+
runAgent(i: TriageAgentInput): Promise<{
|
|
48
|
+
messages: MessageRecord[];
|
|
49
|
+
stop: TriageStop;
|
|
50
|
+
}>;
|
|
51
|
+
/** No budget signal: a delivery in flight must finish on its own timeout. */
|
|
52
|
+
send(account: EmailAccount, mail: OutgoingMail, signal?: AbortSignal): Promise<string>;
|
|
53
|
+
markSeen(account: EmailAccount, uids: number[], uidValidity: string, signal?: AbortSignal): Promise<'marked' | 'uidvalidity-changed'>;
|
|
54
|
+
saveRun(serviceId: string, run: unknown): Promise<void>;
|
|
55
|
+
now(): Date;
|
|
56
|
+
};
|
|
57
|
+
export type TriageOutcome = {
|
|
58
|
+
kind: 'skipped';
|
|
59
|
+
} | {
|
|
60
|
+
kind: 'failure';
|
|
61
|
+
error: string;
|
|
62
|
+
} | {
|
|
63
|
+
kind: 'success';
|
|
64
|
+
included: number;
|
|
65
|
+
refused: number;
|
|
66
|
+
marked: boolean;
|
|
67
|
+
warning?: string;
|
|
68
|
+
};
|
|
69
|
+
export declare function executeTriageRun(service: ServiceConfig, deps: TriageDeps, runId?: string): Promise<TriageOutcome>;
|
|
70
|
+
//# sourceMappingURL=email_triage.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"email_triage.d.ts","sourceRoot":"","sources":["../../../../src/cli/web/scheduler/email_triage.ts"],"names":[],"mappings":"AAQA,OAAO,EAOL,KAAK,YAAY,EACjB,KAAK,YAAY,EACjB,KAAK,cAAc,EACnB,KAAK,mBAAmB,EACzB,MAAM,uBAAuB,CAAC;AAC/B,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,2BAA2B,CAAC;AAC/D,OAAO,KAAK,EAAE,WAAW,EAAE,eAAe,EAAE,cAAc,EAAE,aAAa,EAAE,MAAM,mBAAmB,CAAC;AAErG,OAAO,EAKL,mBAAmB,EACpB,MAAM,mBAAmB,CAAC;AAK3B,eAAO,MAAM,mBAAmB,8zCAuBmC,CAAC;AAIpE,MAAM,MAAM,UAAU,GAAG,MAAM,GAAG,WAAW,GAAG,SAAS,CAAC;AAE1D,wBAAgB,iBAAiB,CAAC,CAAC,EAAE;IACnC,WAAW,EAAE,MAAM,CAAC;IACpB,KAAK,EAAE,MAAM,CAAC;IACd,SAAS,EAAE,cAAc,EAAE,CAAC;CAC7B,GAAG,MAAM,CAST;AAED;;2DAE2D;AAC3D,wBAAgB,aAAa,CAAC,QAAQ,EAAE,aAAa,EAAE,EAAE,IAAI,EAAE,UAAU,GAAG,MAAM,GAAG,IAAI,CAkBxF;AAED;;2CAE2C;AAC3C,wBAAgB,WAAW,CAAC,GAAG,EAAE,MAAM,GAAG,SAAS,GAAG,MAAM,CAI3D;AAED,wBAAgB,aAAa,CAAC,MAAM,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,EAAE,GAAG,EAAE,IAAI,GAAG,MAAM,CAI9E;AAED,wBAAgB,eAAe,CAAC,GAAG,EAAE,MAAM,GAAG,SAAS,GAAG,MAAM,EAAE,CAEjE;AAED;;;wCAGwC;AACxC,wBAAgB,oBAAoB,CAClC,QAAQ,EAAE,aAAa,EAAE,EACzB,OAAO,EAAE,aAAa,EACtB,OAAO,EAAE,MAAM,GACd;IAAE,OAAO,EAAE,YAAY,CAAA;CAAE,GAAG;IAAE,KAAK,EAAE,MAAM,CAAA;CAAE,CAc/C;AAED,MAAM,MAAM,gBAAgB,GAAG;IAC7B,KAAK,EAAE,WAAW,CAAC;IACnB,QAAQ,EAAE,cAAc,CAAC;IACzB,MAAM,EAAE,MAAM,CAAC;IACf,OAAO,EAAE,YAAY,CAAC;IACtB,UAAU,EAAE,MAAM,CAAC;IACnB,MAAM,EAAE,WAAW,CAAC;IACpB,6EAA6E;IAC7E,MAAM,EAAE,UAAU,CAAC,OAAO,mBAAmB,CAAC,CAAC;CAChD,CAAC;AAEF,MAAM,MAAM,UAAU,GAAG;IACvB,IAAI,IAAI,OAAO,CAAC;QAAE,MAAM,EAAE,WAAW,EAAE,CAAC;QAAC,MAAM,EAAE,eAAe,CAAA;KAAE,CAAC,CAAC;IACpE,aAAa,CACX,OAAO,EAAE,YAAY,EACrB,GAAG,EAAE,MAAM,EACX,MAAM,EAAE,WAAW,GAClB,UAAU,CAAC,OAAO,mBAAmB,CAAC,CAAC;IAC1C,QAAQ,CAAC,CAAC,EAAE,gBAAgB,GAAG,OAAO,CAAC;QAAE,QAAQ,EAAE,aAAa,EAAE,CAAC;QAAC,IAAI,EAAE,UAAU,CAAA;KAAE,CAAC,CAAC;IACxF,6EAA6E;IAC7E,IAAI,CAAC,OAAO,EAAE,YAAY,EAAE,IAAI,EAAE,YAAY,EAAE,MAAM,CAAC,EAAE,WAAW,GAAG,OAAO,CAAC,MAAM,CAAC,CAAC;IACvF,QAAQ,CACN,OAAO,EAAE,YAAY,EACrB,IAAI,EAAE,MAAM,EAAE,EACd,WAAW,EAAE,MAAM,EACnB,MAAM,CAAC,EAAE,WAAW,GACnB,OAAO,CAAC,QAAQ,GAAG,qBAAqB,CAAC,CAAC;IAC7C,OAAO,CAAC,SAAS,EAAE,MAAM,EAAE,GAAG,EAAE,OAAO,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;IACxD,GAAG,IAAI,IAAI,CAAC;CACb,CAAC;AAEF,MAAM,MAAM,aAAa,GACrB;IAAE,IAAI,EAAE,SAAS,CAAA;CAAE,GACnB;IAAE,IAAI,EAAE,SAAS,CAAC;IAAC,KAAK,EAAE,MAAM,CAAA;CAAE,GAClC;IAAE,IAAI,EAAE,SAAS,CAAC;IAAC,QAAQ,EAAE,MAAM,CAAC;IAAC,OAAO,EAAE,MAAM,CAAC;IAAC,MAAM,EAAE,OAAO,CAAC;IAAC,OAAO,CAAC,EAAE,MAAM,CAAA;CAAE,CAAC;AAoB9F,wBAAsB,gBAAgB,CACpC,OAAO,EAAE,aAAa,EACtB,IAAI,EAAE,UAAU,EAChB,KAAK,GAAE,MAAmB,GACzB,OAAO,CAAC,aAAa,CAAC,CAoJxB"}
|
|
@@ -0,0 +1,262 @@
|
|
|
1
|
+
// Email triage orchestrator: list unread envelopes, run one agent over them,
|
|
2
|
+
// mail the report, then mark exactly the triaged messages read.
|
|
3
|
+
//
|
|
4
|
+
// Deliberately free of any `harness` import: the real deps (agent runner,
|
|
5
|
+
// store, IMAP/SMTP wiring) and the scheduler strategy live in
|
|
6
|
+
// email_triage_agent.ts, so this file is testable with plain fakes.
|
|
7
|
+
import { randomUUID } from 'node:crypto';
|
|
8
|
+
import { canRead, canSend, MAX_SCAN, emailAccounts, markdownToHtml, parsePatterns, } from '../../../lib/email.js';
|
|
9
|
+
import { runningTasks } from './locks.js';
|
|
10
|
+
import { beginServiceRun, emitServiceRunEvent, endServiceRun, newRunId, serviceRunCallbacks, } from './service_runs.js';
|
|
11
|
+
import { CLAUDE_CODE_DEFAULT_RUN_SECONDS } from './task_roles.js';
|
|
12
|
+
const DEFAULT_PREFIX = '[Email Triage]';
|
|
13
|
+
export const TRIAGE_INSTRUCTIONS = `You are triaging an inbox. Classify every unread email below into exactly one bucket:
|
|
14
|
+
|
|
15
|
+
- IMPORTANT: needs action soon: outages, blocked users or customers, failures, direct requests with a deadline.
|
|
16
|
+
- INFORMATION: worth knowing, no immediate action.
|
|
17
|
+
- TRASH: noise: automated notifications without a decision, time tracking, routine bot chatter. Count only, never list.
|
|
18
|
+
|
|
19
|
+
Your final message must contain only the report, in exactly this shape, starting with "## IMPORTANT". Every bucket header is always present; when a table would be empty, write "_No important emails._" or "_No information emails._" instead of it.
|
|
20
|
+
|
|
21
|
+
## IMPORTANT
|
|
22
|
+
| From | Subject | Category | Summary | Suggested Action |
|
|
23
|
+
|
|
24
|
+
## INFORMATION
|
|
25
|
+
| From | Subject | Category | Summary | Suggested Action |
|
|
26
|
+
|
|
27
|
+
## TRASH
|
|
28
|
+
N emails classified as trash (not listed).
|
|
29
|
+
|
|
30
|
+
Headers, bucket names and the table header row are literal and must never be translated, whatever language the rest of the report is written in.
|
|
31
|
+
|
|
32
|
+
Guidelines:
|
|
33
|
+
- Work from the envelopes (From, Subject, Date). Open a body with email_read only when the subject is not enough.
|
|
34
|
+
- Cluster related notifications into one row.
|
|
35
|
+
- Other tools you have (for example an issue tracker) may be used to understand a reference in an email.
|
|
36
|
+
- Do not send mail: your final message is delivered automatically.`;
|
|
37
|
+
const UNATTENDED_NOTICE = `[UNATTENDED RUN] Note: You are running as an unattended scheduled task. No human is supervising this execution. Act autonomously and complete the task to the best of your ability.`;
|
|
38
|
+
export function buildTriagePrompt(p) {
|
|
39
|
+
const parts = [UNATTENDED_NOTICE, TRIAGE_INSTRUCTIONS];
|
|
40
|
+
if (p.extra.trim())
|
|
41
|
+
parts.push(p.extra.trim());
|
|
42
|
+
parts.push(`Account: ${p.accountName} — pass it as the account argument of email_read.`);
|
|
43
|
+
parts.push('Unread emails (UID | From | Subject | Date):\n' +
|
|
44
|
+
p.envelopes.map((e) => `- ${e.uid} | ${e.from} | ${e.subject} | ${e.date}`).join('\n'));
|
|
45
|
+
return parts.join('\n\n');
|
|
46
|
+
}
|
|
47
|
+
/** The report is the last non-empty assistant message, from its `## IMPORTANT`
|
|
48
|
+
* line on. A truncated run (max_turns/aborted) never yields one: its last
|
|
49
|
+
* message may be a half-finished "let me read uid 42". */
|
|
50
|
+
export function extractReport(messages, stop) {
|
|
51
|
+
if (stop !== 'done')
|
|
52
|
+
return null;
|
|
53
|
+
const last = [...messages].reverse().find((m) => m.role === 'assistant' && m.content?.trim());
|
|
54
|
+
if (!last)
|
|
55
|
+
return null;
|
|
56
|
+
// ACP emits one record per turn with every text part concatenated in
|
|
57
|
+
// `content` (no separator), so prose before a tool call glues onto the
|
|
58
|
+
// report header. Prefer the text after the last tool_use.
|
|
59
|
+
let text = last.content;
|
|
60
|
+
if (last.parts?.length) {
|
|
61
|
+
const lastTool = last.parts.map((p) => p.type).lastIndexOf('tool_use');
|
|
62
|
+
const tail = last.parts
|
|
63
|
+
.slice(lastTool + 1)
|
|
64
|
+
.map((p) => (p.type === 'text' ? p.text : ''))
|
|
65
|
+
.join('');
|
|
66
|
+
if (tail.trim())
|
|
67
|
+
text = tail;
|
|
68
|
+
}
|
|
69
|
+
const m = /^## IMPORTANT\b.*$/m.exec(text);
|
|
70
|
+
return m ? text.slice(m.index).trim() : null;
|
|
71
|
+
}
|
|
72
|
+
/** Envelopes per run: unset → 50; otherwise 1..MAX_SCAN. Only envelopes reach
|
|
73
|
+
* the prompt (one line each), so the cap is the scan window, not email_fetch's
|
|
74
|
+
* MAX_FETCH, which bounds full bodies. */
|
|
75
|
+
export function triageLimit(max) {
|
|
76
|
+
if (max == null)
|
|
77
|
+
return 50;
|
|
78
|
+
const n = Math.trunc(Number(max));
|
|
79
|
+
return Number.isFinite(n) && n >= 1 ? Math.min(n, MAX_SCAN) : 50;
|
|
80
|
+
}
|
|
81
|
+
export function triageSubject(prefix, count, now) {
|
|
82
|
+
const p = (n) => String(n).padStart(2, '0');
|
|
83
|
+
const stamp = `${now.getFullYear()}-${p(now.getMonth() + 1)}-${p(now.getDate())} ${p(now.getHours())}:${p(now.getMinutes())}`;
|
|
84
|
+
return `${prefix} ${count} emails triaged — ${stamp}`;
|
|
85
|
+
}
|
|
86
|
+
export function parseRecipients(raw) {
|
|
87
|
+
return parsePatterns(raw);
|
|
88
|
+
}
|
|
89
|
+
/** Preflight: everything that can be checked before touching IMAP. Looks the
|
|
90
|
+
* raw record up first (emailAccounts drops disabled ones) so each failure has
|
|
91
|
+
* its own message. Not `visibleAccounts`: a scoped mailbox is a readable
|
|
92
|
+
* error here, not an invisible one. */
|
|
93
|
+
export function resolveTriageAccount(services, service, agentId) {
|
|
94
|
+
const id = service.triageAccountId;
|
|
95
|
+
const rec = services.find((s) => s.id === id);
|
|
96
|
+
if (!rec)
|
|
97
|
+
return { error: `Email account "${id ?? ''}" not found.` };
|
|
98
|
+
if (rec.type !== 'email')
|
|
99
|
+
return { error: `Service "${rec.name}" is not an email account.` };
|
|
100
|
+
if (!rec.enabled)
|
|
101
|
+
return { error: `Email account "${rec.name}" is disabled.` };
|
|
102
|
+
const account = emailAccounts([rec])[0];
|
|
103
|
+
if (account.allowedAgents.length > 0 && !account.allowedAgents.includes(agentId)) {
|
|
104
|
+
return { error: `Email account "${rec.name}" is restricted to other agents, not the triage agent.` };
|
|
105
|
+
}
|
|
106
|
+
if (!canRead(account))
|
|
107
|
+
return { error: `Email account "${rec.name}" has no IMAP host to read from.` };
|
|
108
|
+
if (!canSend(account))
|
|
109
|
+
return { error: `Email account "${rec.name}" has no SMTP host to send the report through.` };
|
|
110
|
+
if (!account.from)
|
|
111
|
+
return { error: `Email account "${rec.name}" has no From address.` };
|
|
112
|
+
return { account };
|
|
113
|
+
}
|
|
114
|
+
const errText = (e) => (e instanceof Error ? e.message : String(e));
|
|
115
|
+
const toChat = (m) => ({
|
|
116
|
+
id: m.id,
|
|
117
|
+
role: m.role,
|
|
118
|
+
content: m.content,
|
|
119
|
+
parts: m.parts,
|
|
120
|
+
toolCallId: m.toolCallId,
|
|
121
|
+
createdAt: m.createdAt,
|
|
122
|
+
});
|
|
123
|
+
const assistantNote = (content) => ({
|
|
124
|
+
id: randomUUID(),
|
|
125
|
+
role: 'assistant',
|
|
126
|
+
content,
|
|
127
|
+
createdAt: new Date().toISOString(),
|
|
128
|
+
});
|
|
129
|
+
export async function executeTriageRun(service, deps, runId = newRunId()) {
|
|
130
|
+
if (runningTasks.has(service.id)) {
|
|
131
|
+
console.log(`[scheduler] Triage "${service.name}" is already running — skipping.`);
|
|
132
|
+
return { kind: 'skipped' };
|
|
133
|
+
}
|
|
134
|
+
runningTasks.add(service.id);
|
|
135
|
+
// Same synchronous block as the lock. No prompt yet: it needs the mail listing.
|
|
136
|
+
beginServiceRun(service.id, runId, null);
|
|
137
|
+
const ctrl = new AbortController();
|
|
138
|
+
const timer = setTimeout(() => ctrl.abort(), CLAUDE_CODE_DEFAULT_RUN_SECONDS * 1000);
|
|
139
|
+
const messages = [];
|
|
140
|
+
const fail = async (error) => {
|
|
141
|
+
console.error(`[scheduler] Triage run ${runId} for "${service.name}" failed:`, error);
|
|
142
|
+
await deps.saveRun(service.id, {
|
|
143
|
+
runId,
|
|
144
|
+
timestamp: new Date().toISOString(),
|
|
145
|
+
status: 'failure',
|
|
146
|
+
error,
|
|
147
|
+
messages: [
|
|
148
|
+
...messages,
|
|
149
|
+
assistantNote(`⚠️ Triage run failed:\n\n\`\`\`\n${error}\n\`\`\``),
|
|
150
|
+
],
|
|
151
|
+
});
|
|
152
|
+
return { kind: 'failure', error };
|
|
153
|
+
};
|
|
154
|
+
try {
|
|
155
|
+
const { agents, config } = await deps.load();
|
|
156
|
+
const agent = agents.find((a) => a.id === service.agentId);
|
|
157
|
+
if (!agent)
|
|
158
|
+
return await fail(`Agent with ID "${service.agentId}" not found for "${service.name}"`);
|
|
159
|
+
const provider = config.providers.find((p) => p.name === agent.provider);
|
|
160
|
+
if (!provider)
|
|
161
|
+
return await fail(`Provider "${agent.provider}" not found for agent "${agent.name}"`);
|
|
162
|
+
const resolved = resolveTriageAccount(config.scheduler?.tasks ?? [], service, agent.id);
|
|
163
|
+
if ('error' in resolved)
|
|
164
|
+
return await fail(resolved.error);
|
|
165
|
+
const { account } = resolved;
|
|
166
|
+
const recipients = parseRecipients(service.triageRecipients);
|
|
167
|
+
if (recipients.length === 0)
|
|
168
|
+
return await fail(`Triage service "${service.name}" has no report recipients.`);
|
|
169
|
+
let listing;
|
|
170
|
+
try {
|
|
171
|
+
listing = await deps.listEnvelopes(account, triageLimit(service.triageMaxEmails), ctrl.signal);
|
|
172
|
+
}
|
|
173
|
+
catch (e) {
|
|
174
|
+
return await fail(`Listing unread mail failed: ${errText(e)}`);
|
|
175
|
+
}
|
|
176
|
+
const { envelopes, refused, uidValidity, scanTruncated } = listing;
|
|
177
|
+
if (envelopes.length === 0) {
|
|
178
|
+
if (scanTruncated) {
|
|
179
|
+
return await fail(`The oldest ${MAX_SCAN} unread messages are all from senders outside the account's allowedSenders, so triage cannot see newer mail. Read, move or delete them (or widen the allowlist).`);
|
|
180
|
+
}
|
|
181
|
+
emitServiceRunEvent(runId, 'No unread mail to triage.', 'chunk');
|
|
182
|
+
return { kind: 'skipped' };
|
|
183
|
+
}
|
|
184
|
+
const prompt = buildTriagePrompt({
|
|
185
|
+
accountName: account.name,
|
|
186
|
+
extra: service.prompt ?? '',
|
|
187
|
+
envelopes,
|
|
188
|
+
});
|
|
189
|
+
messages.push({
|
|
190
|
+
id: randomUUID(),
|
|
191
|
+
role: 'user',
|
|
192
|
+
content: prompt,
|
|
193
|
+
createdAt: new Date().toISOString(),
|
|
194
|
+
});
|
|
195
|
+
emitServiceRunEvent(runId, prompt, 'user');
|
|
196
|
+
let result;
|
|
197
|
+
try {
|
|
198
|
+
result = await deps.runAgent({
|
|
199
|
+
agent,
|
|
200
|
+
provider,
|
|
201
|
+
prompt,
|
|
202
|
+
account,
|
|
203
|
+
workingDir: service.workingDir || agent.workingDir || process.cwd(),
|
|
204
|
+
signal: ctrl.signal,
|
|
205
|
+
stream: serviceRunCallbacks(runId),
|
|
206
|
+
});
|
|
207
|
+
}
|
|
208
|
+
catch (e) {
|
|
209
|
+
return await fail(`Agent run failed: ${errText(e)}`);
|
|
210
|
+
}
|
|
211
|
+
messages.push(...result.messages.map(toChat));
|
|
212
|
+
const report = extractReport(result.messages, result.stop);
|
|
213
|
+
if (report === null) {
|
|
214
|
+
return await fail(result.stop !== 'done'
|
|
215
|
+
? `Agent run ended with stop reason "${result.stop}"; no report to send.`
|
|
216
|
+
: 'Agent did not produce a report starting with "## IMPORTANT".');
|
|
217
|
+
}
|
|
218
|
+
const included = envelopes.length;
|
|
219
|
+
try {
|
|
220
|
+
await deps.send(account, {
|
|
221
|
+
to: recipients,
|
|
222
|
+
subject: triageSubject(service.triageSubjectPrefix || DEFAULT_PREFIX, included, deps.now()),
|
|
223
|
+
body: report,
|
|
224
|
+
html: markdownToHtml(report),
|
|
225
|
+
});
|
|
226
|
+
}
|
|
227
|
+
catch (e) {
|
|
228
|
+
return await fail(`Sending the report failed: ${errText(e)}`);
|
|
229
|
+
}
|
|
230
|
+
// The report is out: from here on a problem is a warning, never a failure.
|
|
231
|
+
let marked = false;
|
|
232
|
+
let warning;
|
|
233
|
+
try {
|
|
234
|
+
const r = await deps.markSeen(account, envelopes.map((e) => e.uid), uidValidity);
|
|
235
|
+
if (r === 'marked')
|
|
236
|
+
marked = true;
|
|
237
|
+
else
|
|
238
|
+
warning = 'mailbox UIDVALIDITY changed since listing; messages left unread';
|
|
239
|
+
}
|
|
240
|
+
catch (e) {
|
|
241
|
+
warning = errText(e);
|
|
242
|
+
}
|
|
243
|
+
messages.push(assistantNote(`Triage: ${included} included, ${refused} refused by sender allowlist, ${marked ? 'marked read' : `not marked read: ${warning}`}${scanTruncated
|
|
244
|
+
? `. Warning: more than ${MAX_SCAN} unread messages; only the oldest ${MAX_SCAN} were scanned, newer mail waits for the next runs.`
|
|
245
|
+
: ''}`));
|
|
246
|
+
await deps.saveRun(service.id, {
|
|
247
|
+
runId,
|
|
248
|
+
timestamp: new Date().toISOString(),
|
|
249
|
+
status: 'success',
|
|
250
|
+
messages,
|
|
251
|
+
});
|
|
252
|
+
return { kind: 'success', included, refused, marked, ...(warning ? { warning } : {}) };
|
|
253
|
+
}
|
|
254
|
+
catch (e) {
|
|
255
|
+
return await fail(errText(e));
|
|
256
|
+
}
|
|
257
|
+
finally {
|
|
258
|
+
clearTimeout(timer);
|
|
259
|
+
runningTasks.delete(service.id);
|
|
260
|
+
endServiceRun(service.id, runId);
|
|
261
|
+
}
|
|
262
|
+
}
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import type { Tool } from '../../../harness/tools/types.js';
|
|
2
|
+
import type { ToolRegistry } from '../../../harness/tools/registry.js';
|
|
3
|
+
import type { MessageRecord } from '../../../session/types.js';
|
|
4
|
+
import type { AgentConfig } from '../../../types.js';
|
|
5
|
+
import { type TriageAgentInput, type TriageDeps } from './email_triage.js';
|
|
6
|
+
import type { SchedulerStrategy } from './strategy.js';
|
|
7
|
+
/** The agent's own tools plus email_read, which the triage prompt relies on.
|
|
8
|
+
* Nothing is removed: the agent keeps whatever the user gave it. */
|
|
9
|
+
export declare function triageTools(agent: AgentConfig, registry: ToolRegistry): Promise<Tool[]>;
|
|
10
|
+
export declare function runTriageAgent(i: TriageAgentInput): Promise<{
|
|
11
|
+
messages: MessageRecord[];
|
|
12
|
+
stop: 'done' | 'max_turns' | 'aborted';
|
|
13
|
+
}>;
|
|
14
|
+
export declare const realTriageDeps: TriageDeps;
|
|
15
|
+
export declare const EmailTriageStrategy: SchedulerStrategy;
|
|
16
|
+
//# sourceMappingURL=email_triage_agent.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"email_triage_agent.d.ts","sourceRoot":"","sources":["../../../../src/cli/web/scheduler/email_triage_agent.ts"],"names":[],"mappings":"AAOA,OAAO,KAAK,EAAE,IAAI,EAAE,MAAM,iCAAiC,CAAC;AAC5D,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,oCAAoC,CAAC;AAEvE,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,2BAA2B,CAAC;AAE/D,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;AAErD,OAAO,EAAoB,KAAK,gBAAgB,EAAE,KAAK,UAAU,EAAE,MAAM,mBAAmB,CAAC;AAG7F,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,eAAe,CAAC;AAIvD;qEACqE;AACrE,wBAAsB,WAAW,CAAC,KAAK,EAAE,WAAW,EAAE,QAAQ,EAAE,YAAY,GAAG,OAAO,CAAC,IAAI,EAAE,CAAC,CAK7F;AAED,wBAAsB,cAAc,CAClC,CAAC,EAAE,gBAAgB,GAClB,OAAO,CAAC;IAAE,QAAQ,EAAE,aAAa,EAAE,CAAC;IAAC,IAAI,EAAE,MAAM,GAAG,WAAW,GAAG,SAAS,CAAA;CAAE,CAAC,CA4ChF;AAED,eAAO,MAAM,cAAc,EAAE,UAW5B,CAAC;AAIF,eAAO,MAAM,mBAAmB,EAAE,iBAWjC,CAAC"}
|
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
// Harness-facing half of the email triage service: the agent runner, the real
|
|
2
|
+
// TriageDeps and the scheduler strategy. Kept apart from email_triage.ts so
|
|
3
|
+
// the orchestrator stays testable with plain fakes.
|
|
4
|
+
import * as harness from '../../../harness/index.js';
|
|
5
|
+
import { claudeCodeTaskExtras } from '../../../harness/claude_code_runner.js';
|
|
6
|
+
import { acpTaskExtras } from '../../../harness/acp_policy.js';
|
|
7
|
+
import { listUnseenEnvelopes, markSeen, sendEmail } from '../../../lib/email.js';
|
|
8
|
+
import { loadAgents, loadConfig } from '../../../store/json.js';
|
|
9
|
+
import { getTaskBridgeUrl, issueBridgeToken, revokeBridgeToken } from '../mcp_bridge.js';
|
|
10
|
+
import { executeTriageRun } from './email_triage.js';
|
|
11
|
+
import { matchesCron } from './heartbeat.js';
|
|
12
|
+
import { saveTaskRun } from './logs.js';
|
|
13
|
+
const EMAIL_READ = 'mcp__email__email_read';
|
|
14
|
+
/** The agent's own tools plus email_read, which the triage prompt relies on.
|
|
15
|
+
* Nothing is removed: the agent keeps whatever the user gave it. */
|
|
16
|
+
export async function triageTools(agent, registry) {
|
|
17
|
+
const tools = await harness.resolveAgentTools(agent, registry);
|
|
18
|
+
const read = registry.get(EMAIL_READ);
|
|
19
|
+
if (read && !tools.some((t) => t.name === EMAIL_READ))
|
|
20
|
+
tools.push(read);
|
|
21
|
+
return tools;
|
|
22
|
+
}
|
|
23
|
+
export async function runTriageAgent(i) {
|
|
24
|
+
const tools = await triageTools(i.agent, harness.tools);
|
|
25
|
+
const messages = [];
|
|
26
|
+
let bridgeToken;
|
|
27
|
+
let claudeCode;
|
|
28
|
+
let acp;
|
|
29
|
+
const isClaudeCode = i.provider.type === 'claude-code';
|
|
30
|
+
const isAcp = i.provider.type === 'acp';
|
|
31
|
+
if (isClaudeCode || isAcp) {
|
|
32
|
+
const bridgeUrl = getTaskBridgeUrl();
|
|
33
|
+
// Only email_read is served: the bridge exposes no task state or send tool.
|
|
34
|
+
bridgeToken = bridgeUrl ? issueBridgeToken(i.agent.id, { only: [EMAIL_READ] }) : undefined;
|
|
35
|
+
const bridge = bridgeUrl && bridgeToken ? { url: bridgeUrl, token: bridgeToken } : undefined;
|
|
36
|
+
if (!bridge)
|
|
37
|
+
console.warn('[email-triage] external agent without bridge URL — email_read unavailable this run');
|
|
38
|
+
if (isClaudeCode)
|
|
39
|
+
claudeCode = claudeCodeTaskExtras({ planning: false, sdd: false, bridge });
|
|
40
|
+
else
|
|
41
|
+
acp = acpTaskExtras({ planning: false, sdd: false, bridge });
|
|
42
|
+
}
|
|
43
|
+
try {
|
|
44
|
+
const result = await harness.run({
|
|
45
|
+
agent: { ...i.agent, permissionMode: 'bypassPermissions' },
|
|
46
|
+
provider: i.provider,
|
|
47
|
+
tools,
|
|
48
|
+
prompt: i.prompt,
|
|
49
|
+
history: [],
|
|
50
|
+
workingDir: i.workingDir,
|
|
51
|
+
claudeCode,
|
|
52
|
+
acp,
|
|
53
|
+
signal: i.signal,
|
|
54
|
+
}, {
|
|
55
|
+
...i.stream,
|
|
56
|
+
onMessage: async (msg) => {
|
|
57
|
+
messages.push(msg);
|
|
58
|
+
},
|
|
59
|
+
confirmTool: async () => 'once', // unattended
|
|
60
|
+
});
|
|
61
|
+
return { messages, stop: result.stop };
|
|
62
|
+
}
|
|
63
|
+
finally {
|
|
64
|
+
if (bridgeToken)
|
|
65
|
+
revokeBridgeToken(bridgeToken);
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
export const realTriageDeps = {
|
|
69
|
+
load: async () => {
|
|
70
|
+
const [agents, config] = await Promise.all([loadAgents(), loadConfig()]);
|
|
71
|
+
return { agents, config };
|
|
72
|
+
},
|
|
73
|
+
listEnvelopes: listUnseenEnvelopes,
|
|
74
|
+
runAgent: runTriageAgent,
|
|
75
|
+
send: sendEmail,
|
|
76
|
+
markSeen,
|
|
77
|
+
saveRun: saveTaskRun,
|
|
78
|
+
now: () => new Date(),
|
|
79
|
+
};
|
|
80
|
+
const lastCheckedMinutes = new Map();
|
|
81
|
+
export const EmailTriageStrategy = {
|
|
82
|
+
type: 'email_triage',
|
|
83
|
+
async tick(service, now) {
|
|
84
|
+
const minute = `${now.getFullYear()}-${now.getMonth()}-${now.getDate()} ${now.getHours()}:${now.getMinutes()}`;
|
|
85
|
+
if (lastCheckedMinutes.get(service.id) === minute)
|
|
86
|
+
return;
|
|
87
|
+
if (!matchesCron(service.cron, now))
|
|
88
|
+
return;
|
|
89
|
+
lastCheckedMinutes.set(service.id, minute);
|
|
90
|
+
void executeTriageRun(service, realTriageDeps).catch((err) => {
|
|
91
|
+
console.error('[scheduler] Email triage run failed to execute:', err);
|
|
92
|
+
});
|
|
93
|
+
},
|
|
94
|
+
};
|
|
@@ -11,6 +11,6 @@ export declare function matchesCron(cronStr: string, date: Date): boolean;
|
|
|
11
11
|
* Runs completely in background, automatically approving tool runs.
|
|
12
12
|
* Guards against concurrent execution: if the task is already running, skips.
|
|
13
13
|
*/
|
|
14
|
-
export declare function executeTaskRun(task: ServiceConfig): Promise<void>;
|
|
14
|
+
export declare function executeTaskRun(task: ServiceConfig, runId?: string): Promise<void>;
|
|
15
15
|
export declare const HeartbeatStrategy: SchedulerStrategy;
|
|
16
16
|
//# sourceMappingURL=heartbeat.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"heartbeat.d.ts","sourceRoot":"","sources":["../../../../src/cli/web/scheduler/heartbeat.ts"],"names":[],"mappings":"AAMA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,mBAAmB,CAAC;
|
|
1
|
+
{"version":3,"file":"heartbeat.d.ts","sourceRoot":"","sources":["../../../../src/cli/web/scheduler/heartbeat.ts"],"names":[],"mappings":"AAMA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,mBAAmB,CAAC;AAIvD,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,eAAe,CAAC;AAEvD;;;;GAIG;AACH,wBAAgB,WAAW,CAAC,OAAO,EAAE,MAAM,EAAE,IAAI,EAAE,IAAI,GAAG,OAAO,CA2DhE;AAED;;;;GAIG;AACH,wBAAsB,cAAc,CAAC,IAAI,EAAE,aAAa,EAAE,KAAK,GAAE,MAAmB,GAAG,OAAO,CAAC,IAAI,CAAC,CAkHnG;AAID,eAAO,MAAM,iBAAiB,EAAE,iBAgB/B,CAAC"}
|
|
@@ -4,6 +4,7 @@ import { loadAgents, loadConfig } from '../../../store/json.js';
|
|
|
4
4
|
import { userMessage } from '../../../session/store.js';
|
|
5
5
|
import { saveTaskRun } from './logs.js';
|
|
6
6
|
import { runningTasks } from './locks.js';
|
|
7
|
+
import { beginServiceRun, endServiceRun, newRunId, serviceRunCallbacks } from './service_runs.js';
|
|
7
8
|
/**
|
|
8
9
|
* Parses and evaluates a cron expression string against a given Date.
|
|
9
10
|
* Supports standard syntax fields: minute, hour, day of month, month, day of week.
|
|
@@ -66,13 +67,17 @@ export function matchesCron(cronStr, date) {
|
|
|
66
67
|
* Runs completely in background, automatically approving tool runs.
|
|
67
68
|
* Guards against concurrent execution: if the task is already running, skips.
|
|
68
69
|
*/
|
|
69
|
-
export async function executeTaskRun(task) {
|
|
70
|
+
export async function executeTaskRun(task, runId = newRunId()) {
|
|
70
71
|
if (runningTasks.has(task.id)) {
|
|
71
72
|
console.log(`[scheduler] Task "${task.name}" is already running — skipping.`);
|
|
72
73
|
return;
|
|
73
74
|
}
|
|
74
75
|
runningTasks.add(task.id);
|
|
75
|
-
const
|
|
76
|
+
const unattendedNotice = `[UNATTENDED RUN] Note: You are running as an unattended scheduled task. No human is supervising this execution. Act autonomously and complete the task to the best of your ability.`;
|
|
77
|
+
const effectivePrompt = `${unattendedNotice}\n\n${task.prompt}`;
|
|
78
|
+
const startMsg = userMessage(effectivePrompt);
|
|
79
|
+
// Same synchronous block as the lock: the live stream exists as soon as the run does.
|
|
80
|
+
beginServiceRun(task.id, runId, startMsg);
|
|
76
81
|
console.log(`[scheduler] Starting execution run ${runId} for task: "${task.name}"`);
|
|
77
82
|
const runMessages = [];
|
|
78
83
|
try {
|
|
@@ -87,10 +92,7 @@ export async function executeTaskRun(task) {
|
|
|
87
92
|
}
|
|
88
93
|
const tools = await harness.resolveAgentTools(agent, harness.tools);
|
|
89
94
|
const workingDir = task.workingDir || agent.workingDir || process.cwd();
|
|
90
|
-
const unattendedNotice = `[UNATTENDED RUN] Note: You are running as an unattended scheduled task. No human is supervising this execution. Act autonomously and complete the task to the best of your ability.`;
|
|
91
|
-
const effectivePrompt = `${unattendedNotice}\n\n${task.prompt}`;
|
|
92
95
|
// Track the initial user prompt inside run history
|
|
93
|
-
const startMsg = userMessage(effectivePrompt);
|
|
94
96
|
runMessages.push(startMsg);
|
|
95
97
|
// Invoke headless loop run
|
|
96
98
|
await harness.run({
|
|
@@ -101,6 +103,7 @@ export async function executeTaskRun(task) {
|
|
|
101
103
|
history: [],
|
|
102
104
|
workingDir,
|
|
103
105
|
}, {
|
|
106
|
+
...serviceRunCallbacks(runId),
|
|
104
107
|
onMessage: async (msg) => {
|
|
105
108
|
runMessages.push(msg);
|
|
106
109
|
},
|
|
@@ -161,6 +164,7 @@ export async function executeTaskRun(task) {
|
|
|
161
164
|
finally {
|
|
162
165
|
// Always release the lock so future ticks can re-schedule this task
|
|
163
166
|
runningTasks.delete(task.id);
|
|
167
|
+
endServiceRun(task.id, runId);
|
|
164
168
|
}
|
|
165
169
|
}
|
|
166
170
|
const lastCheckedMinutes = new Map();
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import type { RunCallbacks } from '../../../harness/loop.js';
|
|
2
|
+
import type { MessageRecord } from '../../../session/types.js';
|
|
3
|
+
export declare function newRunId(): string;
|
|
4
|
+
/** Must be called in the same synchronous block that takes the service's
|
|
5
|
+
* `runningTasks` lock, so the two can never disagree. */
|
|
6
|
+
export declare function beginServiceRun(serviceId: string, runId: string, prompt: MessageRecord | null): void;
|
|
7
|
+
/** Call only after the run's log is persisted: a watcher reloads the run list on `done`. */
|
|
8
|
+
export declare function endServiceRun(serviceId: string, runId: string): void;
|
|
9
|
+
export declare function activeServiceRun(serviceId: string): string | undefined;
|
|
10
|
+
export declare function emitServiceRunEvent(runId: string, text: string, type: 'user' | 'chunk'): void;
|
|
11
|
+
export declare function serviceRunCallbacks(runId: string): Pick<RunCallbacks, 'onChunk' | 'onThinking' | 'onToolCall' | 'onToolResult'>;
|
|
12
|
+
//# sourceMappingURL=service_runs.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"service_runs.d.ts","sourceRoot":"","sources":["../../../../src/cli/web/scheduler/service_runs.ts"],"names":[],"mappings":"AAQA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,0BAA0B,CAAC;AAC7D,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,2BAA2B,CAAC;AAM/D,wBAAgB,QAAQ,IAAI,MAAM,CAEjC;AAED;0DAC0D;AAC1D,wBAAgB,eAAe,CAAC,SAAS,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,EAAE,MAAM,EAAE,aAAa,GAAG,IAAI,GAAG,IAAI,CAGpG;AAED,4FAA4F;AAC5F,wBAAgB,aAAa,CAAC,SAAS,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,GAAG,IAAI,CAGpE;AAED,wBAAgB,gBAAgB,CAAC,SAAS,EAAE,MAAM,GAAG,MAAM,GAAG,SAAS,CAEtE;AAED,wBAAgB,mBAAmB,CAAC,KAAK,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,GAAG,OAAO,GAAG,IAAI,CAE7F;AAED,wBAAgB,mBAAmB,CACjC,KAAK,EAAE,MAAM,GACZ,IAAI,CAAC,YAAY,EAAE,SAAS,GAAG,YAAY,GAAG,YAAY,GAAG,cAAc,CAAC,CAO9E"}
|