@hyperwindmill/caretaker-cli 0.30.0 → 0.32.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/email_triage.d.ts +63 -0
- package/dist/cli/web/scheduler/email_triage.d.ts.map +1 -0
- package/dist/cli/web/scheduler/email_triage.js +247 -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 +93 -0
- package/dist/cli/web/scheduler.d.ts.map +1 -1
- package/dist/cli/web/scheduler.js +2 -0
- package/dist/cli/web/voice_backend.d.ts +4 -0
- package/dist/cli/web/voice_backend.d.ts.map +1 -1
- package/dist/cli/web/voice_backend.js +14 -3
- package/dist/cli/web/voice_builtin.d.ts.map +1 -1
- package/dist/cli/web/voice_builtin.js +32 -13
- package/dist/cli/web/voice_proxy.d.ts +3 -0
- package/dist/cli/web/voice_proxy.d.ts.map +1 -1
- package/dist/cli/web/voice_proxy.js +28 -3
- 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/harness/tools/builtin/set_workspace.d.ts.map +1 -1
- package/dist/harness/tools/builtin/set_workspace.js +26 -4
- package/dist/lib/email.d.ts +20 -0
- package/dist/lib/email.d.ts.map +1 -1
- package/dist/lib/email.js +106 -33
- package/dist/session/store.d.ts +2 -2
- package/dist/session/store.d.ts.map +1 -1
- package/dist/session/store.js +5 -2
- package/dist/session/types.d.ts +2 -1
- package/dist/session/types.d.ts.map +1 -1
- package/dist/store/db.d.ts.map +1 -1
- package/dist/store/db.js +3 -1
- package/dist/voice/pocket/install.d.ts +16 -2
- package/dist/voice/pocket/install.d.ts.map +1 -1
- package/dist/voice/pocket/install.js +59 -5
- package/dist/voice/pronunciation.d.ts.map +1 -1
- package/dist/voice/pronunciation.js +3 -0
- package/dist/voice/whisper/catalog.d.ts +15 -0
- package/dist/voice/whisper/catalog.d.ts.map +1 -0
- package/dist/voice/whisper/catalog.js +53 -0
- package/dist/voice/whisper/decoder.d.ts +3 -0
- package/dist/voice/whisper/decoder.d.ts.map +1 -0
- package/dist/voice/whisper/decoder.js +48 -0
- package/dist/voice/whisper/engine.d.ts +8 -0
- package/dist/voice/whisper/engine.d.ts.map +1 -0
- package/dist/voice/whisper/engine.js +77 -0
- package/dist/voice/whisper/features.d.ts +10 -0
- package/dist/voice/whisper/features.d.ts.map +1 -0
- package/dist/voice/whisper/features.js +149 -0
- package/dist/voice/whisper/inference.d.ts +17 -0
- package/dist/voice/whisper/inference.d.ts.map +1 -0
- package/dist/voice/whisper/inference.js +257 -0
- package/dist/voice/whisper/wav.d.ts +5 -0
- package/dist/voice/whisper/wav.d.ts.map +1 -0
- package/dist/voice/whisper/wav.js +48 -0
- package/dist/webview/standalone.js +1114 -689
- 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
|
|
@@ -0,0 +1,63 @@
|
|
|
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
|
+
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.";
|
|
5
|
+
export type TriageStop = 'done' | 'max_turns' | 'aborted';
|
|
6
|
+
export declare function buildTriagePrompt(p: {
|
|
7
|
+
accountName: string;
|
|
8
|
+
extra: string;
|
|
9
|
+
envelopes: TriageEnvelope[];
|
|
10
|
+
}): string;
|
|
11
|
+
/** The report is the last non-empty assistant message, from its `## IMPORTANT`
|
|
12
|
+
* line on. A truncated run (max_turns/aborted) never yields one: its last
|
|
13
|
+
* message may be a half-finished "let me read uid 42". */
|
|
14
|
+
export declare function extractReport(messages: MessageRecord[], stop: TriageStop): string | null;
|
|
15
|
+
export declare function triageSubject(prefix: string, count: number, now: Date): string;
|
|
16
|
+
export declare function parseRecipients(raw: string | undefined): string[];
|
|
17
|
+
/** Preflight: everything that can be checked before touching IMAP. Looks the
|
|
18
|
+
* raw record up first (emailAccounts drops disabled ones) so each failure has
|
|
19
|
+
* its own message. Not `visibleAccounts`: a scoped mailbox is a readable
|
|
20
|
+
* error here, not an invisible one. */
|
|
21
|
+
export declare function resolveTriageAccount(services: ServiceConfig[], service: ServiceConfig, agentId: string): {
|
|
22
|
+
account: EmailAccount;
|
|
23
|
+
} | {
|
|
24
|
+
error: string;
|
|
25
|
+
};
|
|
26
|
+
export type TriageAgentInput = {
|
|
27
|
+
agent: AgentConfig;
|
|
28
|
+
provider: ProviderConfig;
|
|
29
|
+
prompt: string;
|
|
30
|
+
account: EmailAccount;
|
|
31
|
+
workingDir: string;
|
|
32
|
+
signal: AbortSignal;
|
|
33
|
+
};
|
|
34
|
+
export type TriageDeps = {
|
|
35
|
+
load(): Promise<{
|
|
36
|
+
agents: AgentConfig[];
|
|
37
|
+
config: CaretakerConfig;
|
|
38
|
+
}>;
|
|
39
|
+
listEnvelopes(account: EmailAccount, max: number, signal: AbortSignal): ReturnType<typeof listUnseenEnvelopes>;
|
|
40
|
+
runAgent(i: TriageAgentInput): Promise<{
|
|
41
|
+
messages: MessageRecord[];
|
|
42
|
+
stop: TriageStop;
|
|
43
|
+
}>;
|
|
44
|
+
/** No budget signal: a delivery in flight must finish on its own timeout. */
|
|
45
|
+
send(account: EmailAccount, mail: OutgoingMail, signal?: AbortSignal): Promise<string>;
|
|
46
|
+
markSeen(account: EmailAccount, uids: number[], uidValidity: string, signal?: AbortSignal): Promise<'marked' | 'uidvalidity-changed'>;
|
|
47
|
+
saveRun(serviceId: string, run: unknown): Promise<void>;
|
|
48
|
+
now(): Date;
|
|
49
|
+
};
|
|
50
|
+
export type TriageOutcome = {
|
|
51
|
+
kind: 'skipped';
|
|
52
|
+
} | {
|
|
53
|
+
kind: 'failure';
|
|
54
|
+
error: string;
|
|
55
|
+
} | {
|
|
56
|
+
kind: 'success';
|
|
57
|
+
included: number;
|
|
58
|
+
refused: number;
|
|
59
|
+
marked: boolean;
|
|
60
|
+
warning?: string;
|
|
61
|
+
};
|
|
62
|
+
export declare function executeTriageRun(service: ServiceConfig, deps: TriageDeps): Promise<TriageOutcome>;
|
|
63
|
+
//# 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,EASL,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;AAMrG,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,EAA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C;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,GACf,OAAO,CAAC,aAAa,CAAC,CA+IxB"}
|
|
@@ -0,0 +1,247 @@
|
|
|
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_FETCH, MAX_SCAN, clampLimit, emailAccounts, markdownToHtml, parsePatterns, } from '../../../lib/email.js';
|
|
9
|
+
import { runningTasks } from './locks.js';
|
|
10
|
+
import { CLAUDE_CODE_DEFAULT_RUN_SECONDS } from './task_roles.js';
|
|
11
|
+
const DEFAULT_PREFIX = '[Email Triage]';
|
|
12
|
+
export const TRIAGE_INSTRUCTIONS = `You are triaging an inbox. Classify every unread email below into exactly one bucket:
|
|
13
|
+
|
|
14
|
+
- IMPORTANT: needs action soon: outages, blocked users or customers, failures, direct requests with a deadline.
|
|
15
|
+
- INFORMATION: worth knowing, no immediate action.
|
|
16
|
+
- TRASH: noise: automated notifications without a decision, time tracking, routine bot chatter. Count only, never list.
|
|
17
|
+
|
|
18
|
+
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.
|
|
19
|
+
|
|
20
|
+
## IMPORTANT
|
|
21
|
+
| From | Subject | Category | Summary | Suggested Action |
|
|
22
|
+
|
|
23
|
+
## INFORMATION
|
|
24
|
+
| From | Subject | Category | Summary | Suggested Action |
|
|
25
|
+
|
|
26
|
+
## TRASH
|
|
27
|
+
N emails classified as trash (not listed).
|
|
28
|
+
|
|
29
|
+
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.
|
|
30
|
+
|
|
31
|
+
Guidelines:
|
|
32
|
+
- Work from the envelopes (From, Subject, Date). Open a body with email_read only when the subject is not enough.
|
|
33
|
+
- Cluster related notifications into one row.
|
|
34
|
+
- Other tools you have (for example an issue tracker) may be used to understand a reference in an email.
|
|
35
|
+
- Do not send mail: your final message is delivered automatically.`;
|
|
36
|
+
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.`;
|
|
37
|
+
export function buildTriagePrompt(p) {
|
|
38
|
+
const parts = [UNATTENDED_NOTICE, TRIAGE_INSTRUCTIONS];
|
|
39
|
+
if (p.extra.trim())
|
|
40
|
+
parts.push(p.extra.trim());
|
|
41
|
+
parts.push(`Account: ${p.accountName} — pass it as the account argument of email_read.`);
|
|
42
|
+
parts.push('Unread emails (UID | From | Subject | Date):\n' +
|
|
43
|
+
p.envelopes.map((e) => `- ${e.uid} | ${e.from} | ${e.subject} | ${e.date}`).join('\n'));
|
|
44
|
+
return parts.join('\n\n');
|
|
45
|
+
}
|
|
46
|
+
/** The report is the last non-empty assistant message, from its `## IMPORTANT`
|
|
47
|
+
* line on. A truncated run (max_turns/aborted) never yields one: its last
|
|
48
|
+
* message may be a half-finished "let me read uid 42". */
|
|
49
|
+
export function extractReport(messages, stop) {
|
|
50
|
+
if (stop !== 'done')
|
|
51
|
+
return null;
|
|
52
|
+
const last = [...messages].reverse().find((m) => m.role === 'assistant' && m.content?.trim());
|
|
53
|
+
if (!last)
|
|
54
|
+
return null;
|
|
55
|
+
// ACP emits one record per turn with every text part concatenated in
|
|
56
|
+
// `content` (no separator), so prose before a tool call glues onto the
|
|
57
|
+
// report header. Prefer the text after the last tool_use.
|
|
58
|
+
let text = last.content;
|
|
59
|
+
if (last.parts?.length) {
|
|
60
|
+
const lastTool = last.parts.map((p) => p.type).lastIndexOf('tool_use');
|
|
61
|
+
const tail = last.parts
|
|
62
|
+
.slice(lastTool + 1)
|
|
63
|
+
.map((p) => (p.type === 'text' ? p.text : ''))
|
|
64
|
+
.join('');
|
|
65
|
+
if (tail.trim())
|
|
66
|
+
text = tail;
|
|
67
|
+
}
|
|
68
|
+
const m = /^## IMPORTANT\b.*$/m.exec(text);
|
|
69
|
+
return m ? text.slice(m.index).trim() : null;
|
|
70
|
+
}
|
|
71
|
+
export function triageSubject(prefix, count, now) {
|
|
72
|
+
const p = (n) => String(n).padStart(2, '0');
|
|
73
|
+
const stamp = `${now.getFullYear()}-${p(now.getMonth() + 1)}-${p(now.getDate())} ${p(now.getHours())}:${p(now.getMinutes())}`;
|
|
74
|
+
return `${prefix} ${count} emails triaged — ${stamp}`;
|
|
75
|
+
}
|
|
76
|
+
export function parseRecipients(raw) {
|
|
77
|
+
return parsePatterns(raw);
|
|
78
|
+
}
|
|
79
|
+
/** Preflight: everything that can be checked before touching IMAP. Looks the
|
|
80
|
+
* raw record up first (emailAccounts drops disabled ones) so each failure has
|
|
81
|
+
* its own message. Not `visibleAccounts`: a scoped mailbox is a readable
|
|
82
|
+
* error here, not an invisible one. */
|
|
83
|
+
export function resolveTriageAccount(services, service, agentId) {
|
|
84
|
+
const id = service.triageAccountId;
|
|
85
|
+
const rec = services.find((s) => s.id === id);
|
|
86
|
+
if (!rec)
|
|
87
|
+
return { error: `Email account "${id ?? ''}" not found.` };
|
|
88
|
+
if (rec.type !== 'email')
|
|
89
|
+
return { error: `Service "${rec.name}" is not an email account.` };
|
|
90
|
+
if (!rec.enabled)
|
|
91
|
+
return { error: `Email account "${rec.name}" is disabled.` };
|
|
92
|
+
const account = emailAccounts([rec])[0];
|
|
93
|
+
if (account.allowedAgents.length > 0 && !account.allowedAgents.includes(agentId)) {
|
|
94
|
+
return { error: `Email account "${rec.name}" is restricted to other agents, not the triage agent.` };
|
|
95
|
+
}
|
|
96
|
+
if (!canRead(account))
|
|
97
|
+
return { error: `Email account "${rec.name}" has no IMAP host to read from.` };
|
|
98
|
+
if (!canSend(account))
|
|
99
|
+
return { error: `Email account "${rec.name}" has no SMTP host to send the report through.` };
|
|
100
|
+
if (!account.from)
|
|
101
|
+
return { error: `Email account "${rec.name}" has no From address.` };
|
|
102
|
+
return { account };
|
|
103
|
+
}
|
|
104
|
+
const errText = (e) => (e instanceof Error ? e.message : String(e));
|
|
105
|
+
const toChat = (m) => ({
|
|
106
|
+
id: m.id,
|
|
107
|
+
role: m.role,
|
|
108
|
+
content: m.content,
|
|
109
|
+
parts: m.parts,
|
|
110
|
+
toolCallId: m.toolCallId,
|
|
111
|
+
createdAt: m.createdAt,
|
|
112
|
+
});
|
|
113
|
+
const assistantNote = (content) => ({
|
|
114
|
+
id: randomUUID(),
|
|
115
|
+
role: 'assistant',
|
|
116
|
+
content,
|
|
117
|
+
createdAt: new Date().toISOString(),
|
|
118
|
+
});
|
|
119
|
+
export async function executeTriageRun(service, deps) {
|
|
120
|
+
if (runningTasks.has(service.id)) {
|
|
121
|
+
console.log(`[scheduler] Triage "${service.name}" is already running — skipping.`);
|
|
122
|
+
return { kind: 'skipped' };
|
|
123
|
+
}
|
|
124
|
+
runningTasks.add(service.id);
|
|
125
|
+
const runId = `run_${randomUUID().slice(0, 8)}`;
|
|
126
|
+
const ctrl = new AbortController();
|
|
127
|
+
const timer = setTimeout(() => ctrl.abort(), CLAUDE_CODE_DEFAULT_RUN_SECONDS * 1000);
|
|
128
|
+
const messages = [];
|
|
129
|
+
const fail = async (error) => {
|
|
130
|
+
console.error(`[scheduler] Triage run ${runId} for "${service.name}" failed:`, error);
|
|
131
|
+
await deps.saveRun(service.id, {
|
|
132
|
+
runId,
|
|
133
|
+
timestamp: new Date().toISOString(),
|
|
134
|
+
status: 'failure',
|
|
135
|
+
error,
|
|
136
|
+
messages: [
|
|
137
|
+
...messages,
|
|
138
|
+
assistantNote(`⚠️ Triage run failed:\n\n\`\`\`\n${error}\n\`\`\``),
|
|
139
|
+
],
|
|
140
|
+
});
|
|
141
|
+
return { kind: 'failure', error };
|
|
142
|
+
};
|
|
143
|
+
try {
|
|
144
|
+
const { agents, config } = await deps.load();
|
|
145
|
+
const agent = agents.find((a) => a.id === service.agentId);
|
|
146
|
+
if (!agent)
|
|
147
|
+
return await fail(`Agent with ID "${service.agentId}" not found for "${service.name}"`);
|
|
148
|
+
const provider = config.providers.find((p) => p.name === agent.provider);
|
|
149
|
+
if (!provider)
|
|
150
|
+
return await fail(`Provider "${agent.provider}" not found for agent "${agent.name}"`);
|
|
151
|
+
const resolved = resolveTriageAccount(config.scheduler?.tasks ?? [], service, agent.id);
|
|
152
|
+
if ('error' in resolved)
|
|
153
|
+
return await fail(resolved.error);
|
|
154
|
+
const { account } = resolved;
|
|
155
|
+
const recipients = parseRecipients(service.triageRecipients);
|
|
156
|
+
if (recipients.length === 0)
|
|
157
|
+
return await fail(`Triage service "${service.name}" has no report recipients.`);
|
|
158
|
+
let listing;
|
|
159
|
+
try {
|
|
160
|
+
listing = await deps.listEnvelopes(account, service.triageMaxEmails == null ? MAX_FETCH : clampLimit(service.triageMaxEmails), ctrl.signal);
|
|
161
|
+
}
|
|
162
|
+
catch (e) {
|
|
163
|
+
return await fail(`Listing unread mail failed: ${errText(e)}`);
|
|
164
|
+
}
|
|
165
|
+
const { envelopes, refused, uidValidity, scanTruncated } = listing;
|
|
166
|
+
if (envelopes.length === 0) {
|
|
167
|
+
if (scanTruncated) {
|
|
168
|
+
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).`);
|
|
169
|
+
}
|
|
170
|
+
return { kind: 'skipped' };
|
|
171
|
+
}
|
|
172
|
+
const prompt = buildTriagePrompt({
|
|
173
|
+
accountName: account.name,
|
|
174
|
+
extra: service.prompt ?? '',
|
|
175
|
+
envelopes,
|
|
176
|
+
});
|
|
177
|
+
messages.push({
|
|
178
|
+
id: randomUUID(),
|
|
179
|
+
role: 'user',
|
|
180
|
+
content: prompt,
|
|
181
|
+
createdAt: new Date().toISOString(),
|
|
182
|
+
});
|
|
183
|
+
let result;
|
|
184
|
+
try {
|
|
185
|
+
result = await deps.runAgent({
|
|
186
|
+
agent,
|
|
187
|
+
provider,
|
|
188
|
+
prompt,
|
|
189
|
+
account,
|
|
190
|
+
workingDir: service.workingDir || agent.workingDir || process.cwd(),
|
|
191
|
+
signal: ctrl.signal,
|
|
192
|
+
});
|
|
193
|
+
}
|
|
194
|
+
catch (e) {
|
|
195
|
+
return await fail(`Agent run failed: ${errText(e)}`);
|
|
196
|
+
}
|
|
197
|
+
messages.push(...result.messages.map(toChat));
|
|
198
|
+
const report = extractReport(result.messages, result.stop);
|
|
199
|
+
if (report === null) {
|
|
200
|
+
return await fail(result.stop !== 'done'
|
|
201
|
+
? `Agent run ended with stop reason "${result.stop}"; no report to send.`
|
|
202
|
+
: 'Agent did not produce a report starting with "## IMPORTANT".');
|
|
203
|
+
}
|
|
204
|
+
const included = envelopes.length;
|
|
205
|
+
try {
|
|
206
|
+
await deps.send(account, {
|
|
207
|
+
to: recipients,
|
|
208
|
+
subject: triageSubject(service.triageSubjectPrefix || DEFAULT_PREFIX, included, deps.now()),
|
|
209
|
+
body: report,
|
|
210
|
+
html: markdownToHtml(report),
|
|
211
|
+
});
|
|
212
|
+
}
|
|
213
|
+
catch (e) {
|
|
214
|
+
return await fail(`Sending the report failed: ${errText(e)}`);
|
|
215
|
+
}
|
|
216
|
+
// The report is out: from here on a problem is a warning, never a failure.
|
|
217
|
+
let marked = false;
|
|
218
|
+
let warning;
|
|
219
|
+
try {
|
|
220
|
+
const r = await deps.markSeen(account, envelopes.map((e) => e.uid), uidValidity);
|
|
221
|
+
if (r === 'marked')
|
|
222
|
+
marked = true;
|
|
223
|
+
else
|
|
224
|
+
warning = 'mailbox UIDVALIDITY changed since listing; messages left unread';
|
|
225
|
+
}
|
|
226
|
+
catch (e) {
|
|
227
|
+
warning = errText(e);
|
|
228
|
+
}
|
|
229
|
+
messages.push(assistantNote(`Triage: ${included} included, ${refused} refused by sender allowlist, ${marked ? 'marked read' : `not marked read: ${warning}`}${scanTruncated
|
|
230
|
+
? `. Warning: more than ${MAX_SCAN} unread messages; only the oldest ${MAX_SCAN} were scanned, newer mail waits for the next runs.`
|
|
231
|
+
: ''}`));
|
|
232
|
+
await deps.saveRun(service.id, {
|
|
233
|
+
runId,
|
|
234
|
+
timestamp: new Date().toISOString(),
|
|
235
|
+
status: 'success',
|
|
236
|
+
messages,
|
|
237
|
+
});
|
|
238
|
+
return { kind: 'success', included, refused, marked, ...(warning ? { warning } : {}) };
|
|
239
|
+
}
|
|
240
|
+
catch (e) {
|
|
241
|
+
return await fail(errText(e));
|
|
242
|
+
}
|
|
243
|
+
finally {
|
|
244
|
+
clearTimeout(timer);
|
|
245
|
+
runningTasks.delete(service.id);
|
|
246
|
+
}
|
|
247
|
+
}
|
|
@@ -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,CA2ChF;AAED,eAAO,MAAM,cAAc,EAAE,UAW5B,CAAC;AAIF,eAAO,MAAM,mBAAmB,EAAE,iBAWjC,CAAC"}
|
|
@@ -0,0 +1,93 @@
|
|
|
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
|
+
onMessage: async (msg) => {
|
|
56
|
+
messages.push(msg);
|
|
57
|
+
},
|
|
58
|
+
confirmTool: async () => 'once', // unattended
|
|
59
|
+
});
|
|
60
|
+
return { messages, stop: result.stop };
|
|
61
|
+
}
|
|
62
|
+
finally {
|
|
63
|
+
if (bridgeToken)
|
|
64
|
+
revokeBridgeToken(bridgeToken);
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
export const realTriageDeps = {
|
|
68
|
+
load: async () => {
|
|
69
|
+
const [agents, config] = await Promise.all([loadAgents(), loadConfig()]);
|
|
70
|
+
return { agents, config };
|
|
71
|
+
},
|
|
72
|
+
listEnvelopes: listUnseenEnvelopes,
|
|
73
|
+
runAgent: runTriageAgent,
|
|
74
|
+
send: sendEmail,
|
|
75
|
+
markSeen,
|
|
76
|
+
saveRun: saveTaskRun,
|
|
77
|
+
now: () => new Date(),
|
|
78
|
+
};
|
|
79
|
+
const lastCheckedMinutes = new Map();
|
|
80
|
+
export const EmailTriageStrategy = {
|
|
81
|
+
type: 'email_triage',
|
|
82
|
+
async tick(service, now) {
|
|
83
|
+
const minute = `${now.getFullYear()}-${now.getMonth()}-${now.getDate()} ${now.getHours()}:${now.getMinutes()}`;
|
|
84
|
+
if (lastCheckedMinutes.get(service.id) === minute)
|
|
85
|
+
return;
|
|
86
|
+
if (!matchesCron(service.cron, now))
|
|
87
|
+
return;
|
|
88
|
+
lastCheckedMinutes.set(service.id, minute);
|
|
89
|
+
void executeTriageRun(service, realTriageDeps).catch((err) => {
|
|
90
|
+
console.error('[scheduler] Email triage run failed to execute:', err);
|
|
91
|
+
});
|
|
92
|
+
},
|
|
93
|
+
};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"scheduler.d.ts","sourceRoot":"","sources":["../../../src/cli/web/scheduler.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"scheduler.d.ts","sourceRoot":"","sources":["../../../src/cli/web/scheduler.ts"],"names":[],"mappings":"AAQA,OAAO,EACL,gBAAgB,EAChB,gBAAgB,EAChB,sBAAsB,EACtB,YAAY,EACZ,WAAW,GACZ,MAAM,qBAAqB,CAAC;AAC7B,OAAO,EAAE,YAAY,EAAE,MAAM,sBAAsB,CAAC;AAQpD;;GAEG;AACH,wBAAsB,gBAAgB,IAAI,OAAO,CAAC,IAAI,CAAC,CA4BtD;AAKD;;GAEG;AACH,wBAAgB,wBAAwB,IAAI,IAAI,CAQ/C;AAED;;GAEG;AACH,wBAAgB,uBAAuB,IAAI,IAAI,CAM9C"}
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { loadConfig } from '../../store/json.js';
|
|
2
2
|
import { HeartbeatStrategy } from './scheduler/heartbeat.js';
|
|
3
3
|
import { TelegramStrategy } from './scheduler/telegram.js';
|
|
4
|
+
import { EmailTriageStrategy } from './scheduler/email_triage_agent.js';
|
|
4
5
|
import { runTaskHeartbeatTick } from './scheduler/task_strategy.js';
|
|
5
6
|
import { runMemorySweepTick } from './scheduler/memory_sweep.js';
|
|
6
7
|
// Re-exported for backwards compatibility with existing consumers (server.ts, tests).
|
|
@@ -9,6 +10,7 @@ export { runningTasks } from './scheduler/locks.js';
|
|
|
9
10
|
const strategies = new Map([
|
|
10
11
|
[HeartbeatStrategy.type, HeartbeatStrategy],
|
|
11
12
|
[TelegramStrategy.type, TelegramStrategy],
|
|
13
|
+
[EmailTriageStrategy.type, EmailTriageStrategy],
|
|
12
14
|
]);
|
|
13
15
|
/**
|
|
14
16
|
* Evaluates all scheduled tasks and triggers execution loops for matching ones.
|
|
@@ -71,5 +71,9 @@ export declare function registerVoiceBackend(app: Hono): void;
|
|
|
71
71
|
* out of the caller — every failure is logged and otherwise swallowed, and
|
|
72
72
|
* the UI learns the outcome by polling GET /api/voice/backend. */
|
|
73
73
|
export declare function maybeAutoStartBackend(): void;
|
|
74
|
+
/** Containers auto-start should bring up. STT serves endpoint transcription and,
|
|
75
|
+
* absent a separate ttsEndpoint, endpoint synthesis; the TTS container exists only
|
|
76
|
+
* with a separate ttsEndpoint. Built-in engines need neither. */
|
|
77
|
+
export declare function autoStartTargets(voice: VoiceConfig): Array<'stt' | 'tts'>;
|
|
74
78
|
export {};
|
|
75
79
|
//# sourceMappingURL=voice_backend.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"voice_backend.d.ts","sourceRoot":"","sources":["../../../src/cli/web/voice_backend.ts"],"names":[],"mappings":"AAeA,OAAO,KAAK,EAAE,IAAI,EAAE,MAAM,MAAM,CAAC;AAEjC,OAAO,KAAK,E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AAED;6EAC6E;AAC7E,wBAAsB,aAAa,CAAC,MAAM,GAAE,MAAc,GAAG,OAAO,CAAC,IAAI,CAAC,CAEzE;AAaD;+EAC+E;AAC/E,wBAAgB,6BAA6B,CAAC,MAAM,GAAE,MAAc,GAAG,OAAO,CAE7E;AA6BD,wBAAgB,oBAAoB,CAAC,GAAG,EAAE,IAAI,GAAG,IAAI,CA4EpD;AAED;;;mEAGmE;AACnE,wBAAgB,qBAAqB,IAAI,IAAI,CAE5C;AAED;;kEAEkE;AAClE,wBAAgB,gBAAgB,CAAC,KAAK,EAAE,WAAW,GAAG,KAAK,CAAC,KAAK,GAAG,KAAK,CAAC,CAOzE"}
|
|
@@ -531,6 +531,19 @@ export function registerVoiceBackend(app) {
|
|
|
531
531
|
export function maybeAutoStartBackend() {
|
|
532
532
|
void runAutoStart();
|
|
533
533
|
}
|
|
534
|
+
/** Containers auto-start should bring up. STT serves endpoint transcription and,
|
|
535
|
+
* absent a separate ttsEndpoint, endpoint synthesis; the TTS container exists only
|
|
536
|
+
* with a separate ttsEndpoint. Built-in engines need neither. */
|
|
537
|
+
export function autoStartTargets(voice) {
|
|
538
|
+
const endpointTts = voice.ttsEngine !== 'builtin';
|
|
539
|
+
const separateTts = !!voice.ttsEndpoint?.trim();
|
|
540
|
+
const out = [];
|
|
541
|
+
if (voice.sttEngine !== 'builtin' || (endpointTts && !separateTts))
|
|
542
|
+
out.push('stt');
|
|
543
|
+
if (endpointTts && separateTts)
|
|
544
|
+
out.push('tts');
|
|
545
|
+
return out;
|
|
546
|
+
}
|
|
534
547
|
async function runAutoStart() {
|
|
535
548
|
let voice;
|
|
536
549
|
try {
|
|
@@ -554,9 +567,7 @@ async function runAutoStart() {
|
|
|
554
567
|
// target is only auto-started when a *separate* ttsEndpoint is configured —
|
|
555
568
|
// without one, synthesis goes to `endpoint` (the single-server Speaches case)
|
|
556
569
|
// and there is no second container to manage.
|
|
557
|
-
for (const target of
|
|
558
|
-
if (target === 'tts' && !voice.ttsEndpoint?.trim())
|
|
559
|
-
continue;
|
|
570
|
+
for (const target of autoStartTargets(voice)) {
|
|
560
571
|
const endpoint = targetEndpoint(voice, target);
|
|
561
572
|
if (loopbackPort(endpoint) == null)
|
|
562
573
|
continue;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"voice_builtin.d.ts","sourceRoot":"","sources":["../../../src/cli/web/voice_builtin.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,IAAI,EAAE,MAAM,MAAM,CAAC;
|
|
1
|
+
{"version":3,"file":"voice_builtin.d.ts","sourceRoot":"","sources":["../../../src/cli/web/voice_builtin.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,IAAI,EAAE,MAAM,MAAM,CAAC;AAwCjC,wBAAgB,oBAAoB,CAAC,GAAG,EAAE,IAAI,GAAG,IAAI,CAqCpD"}
|
|
@@ -2,11 +2,23 @@
|
|
|
2
2
|
// second install of the same language cannot start a parallel download.
|
|
3
3
|
import { stream } from 'hono/streaming';
|
|
4
4
|
import { POCKET_LANGUAGES } from '../../voice/pocket/catalog.js';
|
|
5
|
-
import {
|
|
5
|
+
import { WHISPER_MODELS } from '../../voice/whisper/catalog.js';
|
|
6
|
+
import { builtinVoiceStatus, deleteBuiltinStt, deleteBuiltinVoice, installBuiltinStt, installBuiltinVoice, } from '../../voice/pocket/install.js';
|
|
6
7
|
import { releasePocketModels, runtimeLoadError, runtimeLoaded, speakBuiltin } from '../../voice/pocket/engine.js';
|
|
7
|
-
import {
|
|
8
|
-
|
|
8
|
+
import { releaseWhisperModels, transcribeBuiltin } from '../../voice/whisper/engine.js';
|
|
9
|
+
import { setBuiltinSpeaker, setBuiltinTranscriber } from './voice_proxy.js';
|
|
10
|
+
// One install or delete at a time: voices and models share the runtime directory.
|
|
9
11
|
let busy = null;
|
|
12
|
+
/** Exactly one of `?language=` / `?stt=`, both known; otherwise a 400 message. */
|
|
13
|
+
function reqTarget(language, stt) {
|
|
14
|
+
if ((language === undefined) === (stt === undefined))
|
|
15
|
+
return 'Pass exactly one of language or stt.';
|
|
16
|
+
if (stt !== undefined) {
|
|
17
|
+
return Object.hasOwn(WHISPER_MODELS, stt) ? { kind: 'stt', size: stt } : 'Unknown model size.';
|
|
18
|
+
}
|
|
19
|
+
const lang = reqLanguage(language);
|
|
20
|
+
return lang ? { kind: 'voice', lang } : 'Unknown language.';
|
|
21
|
+
}
|
|
10
22
|
function reqLanguage(q) {
|
|
11
23
|
return q && Object.hasOwn(POCKET_LANGUAGES, q) ? q : null;
|
|
12
24
|
}
|
|
@@ -17,18 +29,20 @@ async function statusWithLoadError() {
|
|
|
17
29
|
}
|
|
18
30
|
export function registerVoiceBuiltin(app) {
|
|
19
31
|
setBuiltinSpeaker(speakBuiltin);
|
|
32
|
+
setBuiltinTranscriber(transcribeBuiltin);
|
|
20
33
|
app.get('/api/voice/builtin', async (c) => c.json(await statusWithLoadError()));
|
|
21
34
|
app.post('/api/voice/builtin/install', async (c) => {
|
|
22
|
-
const
|
|
23
|
-
if (
|
|
24
|
-
return c.text(
|
|
35
|
+
const t = reqTarget(c.req.query('language'), c.req.query('stt'));
|
|
36
|
+
if (typeof t === 'string')
|
|
37
|
+
return c.text(t, 400);
|
|
38
|
+
const name = t.kind === 'voice' ? t.lang : t.size;
|
|
25
39
|
if (busy)
|
|
26
40
|
return c.text(`An install of ${busy} is already in progress.`, 409);
|
|
27
|
-
busy =
|
|
41
|
+
busy = name;
|
|
28
42
|
c.header('Content-Type', 'application/x-ndjson');
|
|
29
43
|
return stream(c, async (s) => {
|
|
30
44
|
try {
|
|
31
|
-
for await (const p of installBuiltinVoice(lang))
|
|
45
|
+
for await (const p of t.kind === 'voice' ? installBuiltinVoice(t.lang) : installBuiltinStt(t.size))
|
|
32
46
|
await s.writeln(JSON.stringify(p));
|
|
33
47
|
}
|
|
34
48
|
finally {
|
|
@@ -37,15 +51,20 @@ export function registerVoiceBuiltin(app) {
|
|
|
37
51
|
});
|
|
38
52
|
});
|
|
39
53
|
app.post('/api/voice/builtin/delete', async (c) => {
|
|
40
|
-
const
|
|
41
|
-
if (
|
|
42
|
-
return c.text(
|
|
54
|
+
const t = reqTarget(c.req.query('language'), c.req.query('stt'));
|
|
55
|
+
if (typeof t === 'string')
|
|
56
|
+
return c.text(t, 400);
|
|
43
57
|
if (busy)
|
|
44
58
|
return c.text('An install is in progress; wait for it to finish.', 409);
|
|
45
|
-
busy = lang;
|
|
59
|
+
busy = t.kind === 'voice' ? t.lang : t.size;
|
|
46
60
|
try {
|
|
47
61
|
await releasePocketModels();
|
|
48
|
-
await
|
|
62
|
+
await releaseWhisperModels();
|
|
63
|
+
const keepRuntime = runtimeLoaded();
|
|
64
|
+
if (t.kind === 'voice')
|
|
65
|
+
await deleteBuiltinVoice(t.lang, { keepRuntime });
|
|
66
|
+
else
|
|
67
|
+
await deleteBuiltinStt(t.size, { keepRuntime });
|
|
49
68
|
}
|
|
50
69
|
finally {
|
|
51
70
|
busy = null;
|
|
@@ -49,6 +49,9 @@ export declare function formKeyFor(endpoint: string, formKey: string | null | un
|
|
|
49
49
|
* the saved one, so editing the URL can never send the stored key to a new host. */
|
|
50
50
|
export declare function mergePreview(saved: VoiceConfig, s: SynthesisSettings): VoiceConfig;
|
|
51
51
|
export type BuiltinSpeaker = (voice: VoiceConfig, text: string, signal: AbortSignal) => Promise<Response>;
|
|
52
|
+
export type BuiltinTranscriber = (voice: VoiceConfig, audio: Float32Array, signal: AbortSignal) => Promise<Response>;
|
|
53
|
+
/** The built-in transcription engine registers itself here; null unregisters. */
|
|
54
|
+
export declare function setBuiltinTranscriber(fn: BuiltinTranscriber | null): void;
|
|
52
55
|
/** The built-in engine registers itself here; null unregisters. */
|
|
53
56
|
export declare function setBuiltinSpeaker(fn: BuiltinSpeaker | null): void;
|
|
54
57
|
/** Synthesize `text` with the configured engine, dictionary applied, streaming
|