@wirecat/cli-core 0.708.0 → 0.709.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/CHANGELOG.md +25 -0
- package/dist/cli/messenger/conversation-answers.d.ts +4 -0
- package/dist/cli/messenger/message-answers.d.ts +4 -0
- package/dist/cli/messenger/message-writes.d.ts +8 -0
- package/dist/entities/contact-context.d.ts +8 -0
- package/dist/entities/conversation-results.d.ts +8 -0
- package/dist/entities/evidence.d.ts +32 -0
- package/dist/entities/index.d.ts +73 -88
- package/dist/entities/index.js +1 -0
- package/dist/entities/listener.d.ts +16 -0
- package/dist/entities/message-change.d.ts +4 -0
- package/dist/entities/message-context.d.ts +12 -0
- package/dist/entities/message-write.d.ts +16 -0
- package/dist/entities/message.d.ts +5 -0
- package/dist/entities/message.js +2 -0
- package/dist/entities/store-records.d.ts +4 -0
- package/dist/errors/reasons.js +2 -0
- package/dist/mail/cli/inbox.d.ts +15 -0
- package/dist/mail/cli/inbox.js +208 -0
- package/dist/mail/cli/index.d.ts +1 -0
- package/dist/mail/cli/index.js +1 -0
- package/dist/mail/cli/review.js +12 -8
- package/dist/mail/inbox.d.ts +108 -0
- package/dist/mail/inbox.js +215 -0
- package/dist/mail/index.d.ts +1 -0
- package/dist/mail/index.js +1 -0
- package/dist/ports/wirecat-tools.js +7 -0
- package/package.json +1 -1
- package/parity.json +23 -0
|
@@ -221,6 +221,10 @@ export declare const messageWrite: v.StrictObjectSchema<{
|
|
|
221
221
|
readonly fingerprint: v.OptionalSchema<v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.RegexAction<string, undefined>]>, undefined>;
|
|
222
222
|
readonly new_sender: v.OptionalSchema<v.BooleanSchema<undefined>, undefined>;
|
|
223
223
|
readonly sender_identities: v.OptionalSchema<v.NumberSchema<undefined>, undefined>;
|
|
224
|
+
readonly inbox: v.OptionalSchema<v.StrictObjectSchema<{
|
|
225
|
+
readonly bucket: v.PicklistSchema<["answer", "read", "later"], undefined>;
|
|
226
|
+
readonly reason: v.StringSchema<undefined>;
|
|
227
|
+
}, undefined>, undefined>;
|
|
224
228
|
}, undefined>, undefined>;
|
|
225
229
|
readonly provider_metadata: v.OptionalSchema<v.RecordSchema<v.StringSchema<undefined>, v.UnknownSchema, undefined>, undefined>;
|
|
226
230
|
}, undefined>;
|
|
@@ -445,6 +449,10 @@ export declare const messageWrite: v.StrictObjectSchema<{
|
|
|
445
449
|
readonly fingerprint: v.OptionalSchema<v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.RegexAction<string, undefined>]>, undefined>;
|
|
446
450
|
readonly new_sender: v.OptionalSchema<v.BooleanSchema<undefined>, undefined>;
|
|
447
451
|
readonly sender_identities: v.OptionalSchema<v.NumberSchema<undefined>, undefined>;
|
|
452
|
+
readonly inbox: v.OptionalSchema<v.StrictObjectSchema<{
|
|
453
|
+
readonly bucket: v.PicklistSchema<["answer", "read", "later"], undefined>;
|
|
454
|
+
readonly reason: v.StringSchema<undefined>;
|
|
455
|
+
}, undefined>, undefined>;
|
|
448
456
|
}, undefined>, undefined>;
|
|
449
457
|
readonly provider_metadata: v.OptionalSchema<v.RecordSchema<v.StringSchema<undefined>, v.UnknownSchema, undefined>, undefined>;
|
|
450
458
|
}, undefined>, undefined>, undefined>;
|
|
@@ -677,6 +685,10 @@ export declare const messageSend: v.UnionSchema<[v.StrictObjectSchema<{
|
|
|
677
685
|
readonly fingerprint: v.OptionalSchema<v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.RegexAction<string, undefined>]>, undefined>;
|
|
678
686
|
readonly new_sender: v.OptionalSchema<v.BooleanSchema<undefined>, undefined>;
|
|
679
687
|
readonly sender_identities: v.OptionalSchema<v.NumberSchema<undefined>, undefined>;
|
|
688
|
+
readonly inbox: v.OptionalSchema<v.StrictObjectSchema<{
|
|
689
|
+
readonly bucket: v.PicklistSchema<["answer", "read", "later"], undefined>;
|
|
690
|
+
readonly reason: v.StringSchema<undefined>;
|
|
691
|
+
}, undefined>, undefined>;
|
|
680
692
|
}, undefined>, undefined>;
|
|
681
693
|
readonly provider_metadata: v.OptionalSchema<v.RecordSchema<v.StringSchema<undefined>, v.UnknownSchema, undefined>, undefined>;
|
|
682
694
|
}, undefined>;
|
|
@@ -901,6 +913,10 @@ export declare const messageSend: v.UnionSchema<[v.StrictObjectSchema<{
|
|
|
901
913
|
readonly fingerprint: v.OptionalSchema<v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.RegexAction<string, undefined>]>, undefined>;
|
|
902
914
|
readonly new_sender: v.OptionalSchema<v.BooleanSchema<undefined>, undefined>;
|
|
903
915
|
readonly sender_identities: v.OptionalSchema<v.NumberSchema<undefined>, undefined>;
|
|
916
|
+
readonly inbox: v.OptionalSchema<v.StrictObjectSchema<{
|
|
917
|
+
readonly bucket: v.PicklistSchema<["answer", "read", "later"], undefined>;
|
|
918
|
+
readonly reason: v.StringSchema<undefined>;
|
|
919
|
+
}, undefined>, undefined>;
|
|
904
920
|
}, undefined>, undefined>;
|
|
905
921
|
readonly provider_metadata: v.OptionalSchema<v.RecordSchema<v.StringSchema<undefined>, v.UnknownSchema, undefined>, undefined>;
|
|
906
922
|
}, undefined>, undefined>, undefined>;
|
|
@@ -250,6 +250,11 @@ export declare const message: v.StrictObjectSchema<{
|
|
|
250
250
|
readonly new_sender: v.OptionalSchema<v.BooleanSchema<undefined>, undefined>;
|
|
251
251
|
/** Mail `review`: how many identities the sender's person has; 1 is this address alone. */
|
|
252
252
|
readonly sender_identities: v.OptionalSchema<v.NumberSchema<undefined>, undefined>;
|
|
253
|
+
/** Mail `review`: how `inbox` sorted the thread, by the AI model; the reason is untrusted. */
|
|
254
|
+
readonly inbox: v.OptionalSchema<v.StrictObjectSchema<{
|
|
255
|
+
readonly bucket: v.PicklistSchema<["answer", "read", "later"], undefined>;
|
|
256
|
+
readonly reason: v.StringSchema<undefined>;
|
|
257
|
+
}, undefined>, undefined>;
|
|
253
258
|
}, undefined>, undefined>;
|
|
254
259
|
readonly provider_metadata: v.OptionalSchema<v.RecordSchema<v.StringSchema<undefined>, v.UnknownSchema, undefined>, undefined>;
|
|
255
260
|
}, undefined>;
|
package/dist/entities/message.js
CHANGED
|
@@ -115,6 +115,8 @@ export const message = v.strictObject({
|
|
|
115
115
|
new_sender: v.optional(v.boolean()),
|
|
116
116
|
/** Mail `review`: how many identities the sender's person has; 1 is this address alone. */
|
|
117
117
|
sender_identities: v.optional(v.number()),
|
|
118
|
+
/** Mail `review`: how `inbox` sorted the thread, by the AI model; the reason is untrusted. */
|
|
119
|
+
inbox: v.optional(v.strictObject({ bucket: v.picklist(["answer", "read", "later"]), reason: text })),
|
|
118
120
|
})),
|
|
119
121
|
provider_metadata: providerMetadata,
|
|
120
122
|
});
|
|
@@ -252,6 +252,10 @@ export declare const storeExport: v.UnionSchema<[v.StrictObjectSchema<{
|
|
|
252
252
|
readonly fingerprint: v.OptionalSchema<v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.RegexAction<string, undefined>]>, undefined>;
|
|
253
253
|
readonly new_sender: v.OptionalSchema<v.BooleanSchema<undefined>, undefined>;
|
|
254
254
|
readonly sender_identities: v.OptionalSchema<v.NumberSchema<undefined>, undefined>;
|
|
255
|
+
readonly inbox: v.OptionalSchema<v.StrictObjectSchema<{
|
|
256
|
+
readonly bucket: v.PicklistSchema<["answer", "read", "later"], undefined>;
|
|
257
|
+
readonly reason: v.StringSchema<undefined>;
|
|
258
|
+
}, undefined>, undefined>;
|
|
255
259
|
}, undefined>, undefined>;
|
|
256
260
|
readonly provider_metadata: v.OptionalSchema<v.RecordSchema<v.StringSchema<undefined>, v.UnknownSchema, undefined>, undefined>;
|
|
257
261
|
}, undefined>, v.StrictObjectSchema<{
|
package/dist/errors/reasons.js
CHANGED
|
@@ -208,6 +208,8 @@ const OTHERS = [
|
|
|
208
208
|
validation("mail.cursor-ahead", "an acknowledge cursor is past the newest stored email"),
|
|
209
209
|
["mail.holder-not-yours", "permission_error", "a run moves only the mark of the holder its schedule names"],
|
|
210
210
|
["mail.no-mark", "not_found", "the holder has no mark in the mailbox yet; its first review starts it"],
|
|
211
|
+
["mail.inbox-agent", "permission_error", "an agent sorts mail itself from review; inbox --offline lists"],
|
|
212
|
+
["mail.inbox-answer-invalid", "invalid_response", "the AI model's answer to inbox is not the JSON it asks for"],
|
|
211
213
|
["mail.reset-owner-only", "permission_error", "only the owner moves a holder's mark back"],
|
|
212
214
|
["mail.source-failed", "provider_error", "the mail server refused or did not complete a request"],
|
|
213
215
|
["mail.search-refused", "provider_error", "the mail server refused to search a folder"],
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import { type KeyringStore } from "@wirecat/cli-base";
|
|
2
|
+
import { Command } from "commander";
|
|
3
|
+
import type { MailReads } from "./index.js";
|
|
4
|
+
export interface MailInboxOptions {
|
|
5
|
+
/** Where the owner chooses the shared AI model and the `models chats` setting; mail has no `models` of its own. */
|
|
6
|
+
modelsCommand?: string;
|
|
7
|
+
keyring?: KeyringStore;
|
|
8
|
+
fetch?: typeof globalThis.fetch;
|
|
9
|
+
}
|
|
10
|
+
/**
|
|
11
|
+
* `inbox`: the threads that changed since its last run, sorted by the shared AI model into those that need an answer,
|
|
12
|
+
* those to read and those that can wait, each with a one-line reason; then every sorted thread still open. It runs
|
|
13
|
+
* the model through its API, with no agent: an agent reads `review` and sorts the mail itself.
|
|
14
|
+
*/
|
|
15
|
+
export declare const mailInboxCommand: (mail: MailReads, options?: MailInboxOptions | undefined) => Command;
|
|
@@ -0,0 +1,208 @@
|
|
|
1
|
+
import { CliError } from "@wirecat/cli-base";
|
|
2
|
+
import { annotate, sharedCommand } from "@wirecat/cli-base/commands";
|
|
3
|
+
import { Command } from "commander";
|
|
4
|
+
import * as v from "valibot";
|
|
5
|
+
import { answerEntity } from "../../cli/answer-entity.js";
|
|
6
|
+
import { environmentOf, outputFor } from "../../cli/context.js";
|
|
7
|
+
import { FETCH, reachesOtherService, refuseUnderReadOnly } from "../../cli/effects.js";
|
|
8
|
+
import { listOf } from "../../cli/envelope.js";
|
|
9
|
+
import { answerLocally } from "../../cli/local-times.js";
|
|
10
|
+
import { answerOf as askOwner } from "../../cli/messenger/ask.js";
|
|
11
|
+
import { positiveCount } from "../../cli/paging.js";
|
|
12
|
+
import { formatReference } from "../../domain/references.js";
|
|
13
|
+
import { reference, text, time, untrusted } from "../../entities/fields.js";
|
|
14
|
+
import { aiBaseUrl, aiSettingPath, aiTextReader, readAiSetting } from "../../models/ai.js";
|
|
15
|
+
import { chatSendingAllowed, chatSendingAskRefusal } from "../../models/chat-sending.js";
|
|
16
|
+
import { localOnly, localOnlyRefusal } from "../../models/local-only.js";
|
|
17
|
+
import { agentOf } from "../../runs/run-context.js";
|
|
18
|
+
import { INBOX_BUCKETS, INBOX_LIMITS, INBOX_SYSTEM, inboxDue, inboxPrompt, inboxVerdicts, parseInboxAnswer, planInbox, saveInbox, } from "../inbox.js";
|
|
19
|
+
const BUCKET_WORDS = { answer: "needs an answer", read: "to read", later: "can wait" };
|
|
20
|
+
const inboxThread = v.strictObject({
|
|
21
|
+
ref: reference,
|
|
22
|
+
title: v.nullable(text),
|
|
23
|
+
bucket: v.picklist(INBOX_BUCKETS),
|
|
24
|
+
reason: text,
|
|
25
|
+
last_email_at: time,
|
|
26
|
+
sorted_at: time,
|
|
27
|
+
by: text,
|
|
28
|
+
untrusted,
|
|
29
|
+
});
|
|
30
|
+
const itemOf = (mailbox) => (one) => ({
|
|
31
|
+
ref: formatReference({ type: "chat", ...mailbox, chat: one.thread }),
|
|
32
|
+
title: one.title,
|
|
33
|
+
bucket: one.bucket,
|
|
34
|
+
reason: one.reason,
|
|
35
|
+
last_email_at: one.lastEmailAt,
|
|
36
|
+
sorted_at: one.sortedAt,
|
|
37
|
+
by: one.by,
|
|
38
|
+
// The reason is the model's reading of mail other people wrote.
|
|
39
|
+
untrusted: ["title", "reason"],
|
|
40
|
+
});
|
|
41
|
+
const missingOf = (run, command) => {
|
|
42
|
+
if (!run)
|
|
43
|
+
return [];
|
|
44
|
+
return [
|
|
45
|
+
...(run.left > 0
|
|
46
|
+
? [
|
|
47
|
+
{
|
|
48
|
+
field: "items",
|
|
49
|
+
why: `${run.left} threads wait for the next run: --max-${run.stopped === "tokens" ? "tokens" : "messages"} ` +
|
|
50
|
+
`was reached; \`${command} inbox\` again sorts them`,
|
|
51
|
+
},
|
|
52
|
+
]
|
|
53
|
+
: []),
|
|
54
|
+
...(run.overflow > 0
|
|
55
|
+
? [{ field: "items", why: `${run.overflow} more threads changed; the next run reads them` }]
|
|
56
|
+
: []),
|
|
57
|
+
...(run.skipped.length > 0
|
|
58
|
+
? [
|
|
59
|
+
{
|
|
60
|
+
field: "items",
|
|
61
|
+
why: `the model gave no usable answer for ${run.skipped.filter(({ why }) => why === "not-answered").length} ` +
|
|
62
|
+
`threads (${[...new Set(run.skipped.map(({ why }) => why))].join(", ")}); the next run asks again`,
|
|
63
|
+
},
|
|
64
|
+
]
|
|
65
|
+
: []),
|
|
66
|
+
...(run.failed ? [{ field: "items", why: `the AI model failed after ${run.sorted} threads: ${run.failed}` }] : []),
|
|
67
|
+
...(run.quiet > 0 ? [{ field: "items", why: `${run.quiet} threads of mail sent to many were not sorted` }] : []),
|
|
68
|
+
];
|
|
69
|
+
};
|
|
70
|
+
/**
|
|
71
|
+
* `inbox`: the threads that changed since its last run, sorted by the shared AI model into those that need an answer,
|
|
72
|
+
* those to read and those that can wait, each with a one-line reason; then every sorted thread still open. It runs
|
|
73
|
+
* the model through its API, with no agent: an agent reads `review` and sorts the mail itself.
|
|
74
|
+
*/
|
|
75
|
+
export const mailInboxCommand = sharedCommand((mail, options = {}) => answerEntity(reachesOtherService(annotate(new Command("inbox"), {
|
|
76
|
+
effects: FETCH,
|
|
77
|
+
partial: true,
|
|
78
|
+
examples: [
|
|
79
|
+
`${mail.app.command} personal inbox`,
|
|
80
|
+
`${mail.app.command} personal inbox --max-messages 20`,
|
|
81
|
+
`${mail.app.command} personal inbox --offline --json`,
|
|
82
|
+
],
|
|
83
|
+
})), "mail_inbox_thread", inboxThread)
|
|
84
|
+
.summary("new mail sorted by the AI model: needs an answer, to read, can wait")
|
|
85
|
+
.description("send the threads that changed since the last run to the AI model the owner chose (`models ai`), which sorts " +
|
|
86
|
+
"each into needs an answer, to read or can wait with a one-line reason; then list every sorted thread, " +
|
|
87
|
+
"those that need an answer first. Mail sent to many is not sent. A model outside this computer follows " +
|
|
88
|
+
"`models chats` and local only. --offline lists what is sorted and sends nothing")
|
|
89
|
+
.option("--max-messages <n>", `send at most this many emails in this run; the rest wait for the next (default: ${INBOX_LIMITS.emails})`, positiveCount("--max-messages"))
|
|
90
|
+
.option("--max-tokens <n>", `stop before a request that would make the run send more tokens than this (default: ${INBOX_LIMITS.tokens})`, positiveCount("--max-tokens"))
|
|
91
|
+
.option("--yes", "send the mail to a model outside this computer when `models chats` is ask")
|
|
92
|
+
.action(async function () {
|
|
93
|
+
const flags = {
|
|
94
|
+
...this.opts(),
|
|
95
|
+
offline: this.optsWithGlobals().offline,
|
|
96
|
+
};
|
|
97
|
+
const environment = environmentOf(this);
|
|
98
|
+
const env = environment.env ?? process.env;
|
|
99
|
+
const models = options.modelsCommand ?? mail.app.command;
|
|
100
|
+
const offline = flags.offline === true;
|
|
101
|
+
if (!offline && (environment.agent || agentOf(env)))
|
|
102
|
+
throw new CliError("permission_error", `an agent sorts mail itself: read \`${mail.app.command} review --new\`; ` +
|
|
103
|
+
`\`${mail.app.command} inbox --offline\` lists what the AI model sorted`, { reason: "mail.inbox-agent" });
|
|
104
|
+
const now = Date.now();
|
|
105
|
+
const { verdicts, mailbox, run } = await mail.read(this, async (store, mailbox) => {
|
|
106
|
+
if (offline)
|
|
107
|
+
return { verdicts: await inboxVerdicts(store, mailbox), mailbox, run: undefined };
|
|
108
|
+
const run = await sortNew(this, store, mailbox, { ...options, app: mail.app, models, env, now, flags });
|
|
109
|
+
return { verdicts: await inboxVerdicts(store, mailbox), mailbox, run };
|
|
110
|
+
});
|
|
111
|
+
const output = outputFor(this);
|
|
112
|
+
const body = listOf("inbox", {
|
|
113
|
+
items: verdicts.map(itemOf(mailbox)),
|
|
114
|
+
limit: Math.max(1, verdicts.length),
|
|
115
|
+
has_more: false,
|
|
116
|
+
missing: missingOf(run, `${mail.app.command}`),
|
|
117
|
+
...(run && (run.left > 0 || run.overflow > 0 || run.skipped.length > 0 || run.failed)
|
|
118
|
+
? { meta: { complete: false } }
|
|
119
|
+
: {}),
|
|
120
|
+
});
|
|
121
|
+
answerLocally(this, output, body, (local) => {
|
|
122
|
+
if (run)
|
|
123
|
+
output.renderer.note(`sorted ${run.sorted} threads${run.answered ? `, ${run.answered} answered by you` : ""}` +
|
|
124
|
+
(run.left ? `, ${run.left} wait for the next run` : ""));
|
|
125
|
+
if (verdicts.length === 0) {
|
|
126
|
+
output.renderer.note("nothing sorted yet");
|
|
127
|
+
return "";
|
|
128
|
+
}
|
|
129
|
+
return verdicts
|
|
130
|
+
.map((one) => `[${BUCKET_WORDS[one.bucket]}] ${one.title ?? "(no subject)"} · ${local(one.lastEmailAt)}\n ${one.reason}\n`)
|
|
131
|
+
.join("");
|
|
132
|
+
});
|
|
133
|
+
}));
|
|
134
|
+
const sortNew = async (command, store, mailbox, given) => {
|
|
135
|
+
const { models, env, now, flags } = given;
|
|
136
|
+
const due = await inboxDue(store, mailbox, now);
|
|
137
|
+
const plan = planInbox(due, {
|
|
138
|
+
emails: flags.maxMessages ?? INBOX_LIMITS.emails,
|
|
139
|
+
tokens: flags.maxTokens ?? INBOX_LIMITS.tokens,
|
|
140
|
+
});
|
|
141
|
+
const run = {
|
|
142
|
+
sorted: 0,
|
|
143
|
+
answered: due.answered.length,
|
|
144
|
+
left: plan.left,
|
|
145
|
+
skipped: [],
|
|
146
|
+
quiet: due.quiet,
|
|
147
|
+
overflow: due.skipped,
|
|
148
|
+
...(plan.stopped ? { stopped: plan.stopped } : {}),
|
|
149
|
+
};
|
|
150
|
+
if (plan.batches.length === 0) {
|
|
151
|
+
await saveInbox(store, mailbox, due, [], { by: "none", now, complete: due.complete && plan.left === 0 });
|
|
152
|
+
return run;
|
|
153
|
+
}
|
|
154
|
+
const reader = aiTextReader({ app: given.app, env, keyring: given.keyring, fetch: given.fetch });
|
|
155
|
+
if ("refused" in reader)
|
|
156
|
+
throw new CliError("configuration_error", reader.refused === "ai.not-set"
|
|
157
|
+
? `no AI model is chosen: choose one with \`${models} models ai set <provider> --model <model>\` or in ` +
|
|
158
|
+
"WireCat Desktop; nothing was sent"
|
|
159
|
+
: `no API key is stored for the AI model: store it with \`${models} models ai set … --secret-stdin\`; ` +
|
|
160
|
+
"nothing was sent", { reason: reader.refused });
|
|
161
|
+
if (reader.leavesComputer) {
|
|
162
|
+
const setting = readAiSetting(aiSettingPath(env));
|
|
163
|
+
const host = setting ? new URL(aiBaseUrl(setting)).host : reader.by;
|
|
164
|
+
if (localOnly(env))
|
|
165
|
+
throw localOnlyRefusal("the text of your new mail", host);
|
|
166
|
+
refuseUnderReadOnly(command, `send mail to ${host}`);
|
|
167
|
+
if (!chatSendingAllowed(env, host, models) && flags.yes !== true) {
|
|
168
|
+
const what = `${plan.emails} emails of ${plan.batches.flat().length} threads (about ${plan.tokens} tokens) go to ` +
|
|
169
|
+
`${reader.by} at ${host}`;
|
|
170
|
+
const answer = await askOwner(command, `${what}. Send them? [y/N] `);
|
|
171
|
+
if (answer === null)
|
|
172
|
+
throw chatSendingAskRefusal(what, models);
|
|
173
|
+
if (!/^y(es)?$/i.test(answer.trim()))
|
|
174
|
+
throw new CliError("cancelled", "cancelled — nothing was sent");
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
const sorted = [];
|
|
178
|
+
for (const batch of plan.batches) {
|
|
179
|
+
let answer;
|
|
180
|
+
try {
|
|
181
|
+
const text = await reader.complete({
|
|
182
|
+
purpose: "mail-inbox",
|
|
183
|
+
system: INBOX_SYSTEM,
|
|
184
|
+
prompt: inboxPrompt(batch),
|
|
185
|
+
maxTokens: 4096,
|
|
186
|
+
});
|
|
187
|
+
answer = parseInboxAnswer(text, batch);
|
|
188
|
+
}
|
|
189
|
+
catch (error) {
|
|
190
|
+
// What is sorted so far is kept; the rest comes with the next run.
|
|
191
|
+
if (sorted.length === 0)
|
|
192
|
+
throw error;
|
|
193
|
+
run.failed = error instanceof CliError ? (error.details.reason ?? error.code) : "failed";
|
|
194
|
+
run.left += plan.batches.slice(plan.batches.indexOf(batch)).flat().length;
|
|
195
|
+
break;
|
|
196
|
+
}
|
|
197
|
+
run.skipped = run.skipped.concat(answer.skipped);
|
|
198
|
+
for (const thread of batch) {
|
|
199
|
+
const verdict = answer.verdicts.get(thread.thread);
|
|
200
|
+
if (verdict)
|
|
201
|
+
sorted.push({ ...thread, ...verdict });
|
|
202
|
+
}
|
|
203
|
+
}
|
|
204
|
+
run.sorted = sorted.length;
|
|
205
|
+
const complete = due.complete && run.left === 0 && run.skipped.length === 0 && run.failed === undefined;
|
|
206
|
+
await saveInbox(store, mailbox, due, sorted, { by: reader.by, now, complete });
|
|
207
|
+
return run;
|
|
208
|
+
};
|
package/dist/mail/cli/index.d.ts
CHANGED
|
@@ -4,6 +4,7 @@ import { type MailServerAccess } from "../../mail/server-search.js";
|
|
|
4
4
|
import type { AppIdentity } from "../../ports/app.js";
|
|
5
5
|
import { type AccountKey, type MessageStore } from "../../store/store.js";
|
|
6
6
|
export { bulkTriageOf, MAIL_BULK_SETTINGS } from "./bulk-settings.js";
|
|
7
|
+
export { type MailInboxOptions, mailInboxCommand } from "./inbox.js";
|
|
7
8
|
export { mailMark, markItem, markText } from "./marks.js";
|
|
8
9
|
export { MAIL_REVIEW_QUERY, MAIL_REVIEW_STEPS, mailReviewSteps } from "./review.js";
|
|
9
10
|
/**
|
package/dist/mail/cli/index.js
CHANGED
|
@@ -24,6 +24,7 @@ import { queryFilter, THREAD_COLUMNS } from "../../store/store.js";
|
|
|
24
24
|
import { acknowledgeCommand, resetMarkCommand } from "./marks.js";
|
|
25
25
|
import { mailReviewCommand } from "./review.js";
|
|
26
26
|
export { bulkTriageOf, MAIL_BULK_SETTINGS } from "./bulk-settings.js";
|
|
27
|
+
export { mailInboxCommand } from "./inbox.js";
|
|
27
28
|
export { mailMark, markItem, markText } from "./marks.js";
|
|
28
29
|
export { MAIL_REVIEW_QUERY, MAIL_REVIEW_STEPS, mailReviewSteps } from "./review.js";
|
|
29
30
|
/** A locked or broken store must fail the command, not read as "nothing stored yet". */
|
package/dist/mail/cli/review.js
CHANGED
|
@@ -19,6 +19,7 @@ import { parseDuration } from "../../domain/duration.js";
|
|
|
19
19
|
import { formatReference } from "../../domain/references.js";
|
|
20
20
|
import { AGENDA_DEFAULTS } from "../../services/agenda.js";
|
|
21
21
|
import { REVIEW_DAYS, reviewStart } from "../../services/inbox.js";
|
|
22
|
+
import { inboxVerdicts } from "../inbox.js";
|
|
22
23
|
import { cursorOf, findingsKeyOf, readPastMark } from "../marks.js";
|
|
23
24
|
import { BULK_TRIAGE_DEFAULTS } from "../newsletter.js";
|
|
24
25
|
import { hitText } from "../read.js";
|
|
@@ -98,7 +99,7 @@ const markText = (marks, excerptOnly = false, partial = false) => {
|
|
|
98
99
|
const shown = said.filter(Boolean).join(" · ");
|
|
99
100
|
return shown ? `\n [${shown}]` : "";
|
|
100
101
|
};
|
|
101
|
-
const reviewAnswer = (found, mailbox, fresh, step) => {
|
|
102
|
+
const reviewAnswer = (found, mailbox, fresh, step, sorted = new Map()) => {
|
|
102
103
|
// Excerpts come after the mail written to the owner, so an agent with a budget reads that first.
|
|
103
104
|
const read = found.chats
|
|
104
105
|
.flatMap((chat) => chat.messages.map((message) => ({ ...message, chatTitle: chat.title })))
|
|
@@ -149,6 +150,7 @@ const reviewAnswer = (found, mailbox, fresh, step) => {
|
|
|
149
150
|
...(message.through ? { cursor: message.through.cursor, findings_key: message.through.findingsKey } : {}),
|
|
150
151
|
list_id: message.marks?.listId ?? null,
|
|
151
152
|
rule_id: message.marks?.ruleId ?? null,
|
|
153
|
+
...inboxOf(sorted.get(message.chatId)),
|
|
152
154
|
...(message.marks
|
|
153
155
|
? {
|
|
154
156
|
fingerprint: message.marks.fingerprint,
|
|
@@ -157,7 +159,7 @@ const reviewAnswer = (found, mailbox, fresh, step) => {
|
|
|
157
159
|
}
|
|
158
160
|
: {}),
|
|
159
161
|
},
|
|
160
|
-
untrusted: REVIEW_UNTRUSTED,
|
|
162
|
+
untrusted: sorted.has(message.chatId) ? [...REVIEW_UNTRUSTED, "email.inbox.reason"] : REVIEW_UNTRUSTED,
|
|
161
163
|
})),
|
|
162
164
|
limit: Math.max(1, read.length),
|
|
163
165
|
has_more: false,
|
|
@@ -166,18 +168,20 @@ const reviewAnswer = (found, mailbox, fresh, step) => {
|
|
|
166
168
|
meta: found.complete ? {} : { complete: false },
|
|
167
169
|
});
|
|
168
170
|
};
|
|
171
|
+
const inboxOf = (verdict) => verdict ? { inbox: { bucket: verdict.bucket, reason: verdict.reason } } : {};
|
|
172
|
+
const sortedOf = async (store, mailbox) => new Map((await inboxVerdicts(store, mailbox)).map((one) => [one.thread, one]));
|
|
169
173
|
const holderReview = async (command, mail, holder, query) => {
|
|
170
174
|
const { unanswered, waiting } = command.opts();
|
|
171
175
|
if (typedQuery(query).trim() || unanswered !== undefined || waiting !== undefined)
|
|
172
176
|
throw new CliError("validation_error", "--holder reads past its own mark — not with a query, --unanswered or --waiting");
|
|
173
177
|
const triage = mail.bulkTriage?.(command) ?? BULK_TRIAGE_DEFAULTS;
|
|
174
178
|
const now = Date.now();
|
|
175
|
-
const { read, mailbox, marks } = await mail.read(command, async (store, mailbox) => {
|
|
179
|
+
const { read, mailbox, marks, sorted } = await mail.read(command, async (store, mailbox) => {
|
|
176
180
|
const read = await readPastMark(store, mailbox, holder, { triage, now });
|
|
177
181
|
const ids = [...read.emails, ...read.excerpts.map(({ email }) => email)].map((one) => one.id);
|
|
178
182
|
const account = ids.length ? await store.accounts.storedAccount(mailbox) : undefined;
|
|
179
183
|
const marks = account ? await store.mail.emailMarks(account.id, ids) : new Map();
|
|
180
|
-
return { read, mailbox, marks };
|
|
184
|
+
return { read, mailbox, marks, sorted: await sortedOf(store, mailbox) };
|
|
181
185
|
});
|
|
182
186
|
const markedThrough = read.mark?.throughId ?? 0;
|
|
183
187
|
const heldThrough = [...read.emails, ...read.excerpts.map(({ email }) => email)].reduce((most, { storeId }) => (storeId <= markedThrough ? Math.max(most, storeId) : most), 0);
|
|
@@ -228,7 +232,7 @@ const holderReview = async (command, mail, holder, query) => {
|
|
|
228
232
|
quiet: 0,
|
|
229
233
|
};
|
|
230
234
|
const step = stepsFor(mail.mount, mailbox);
|
|
231
|
-
const answer = reviewAnswer(found, mailbox, true, step);
|
|
235
|
+
const answer = reviewAnswer(found, mailbox, true, step, sorted);
|
|
232
236
|
const skipped = Object.entries(read.skipped).filter(([, count]) => count > 0);
|
|
233
237
|
const stage = read.findingsKey === undefined || emails.length === 0 ? [] : step("mail-findings.add", { key: read.findingsKey });
|
|
234
238
|
answer.next = [
|
|
@@ -311,7 +315,7 @@ an agent over MCP, and each scheduled run.`)
|
|
|
311
315
|
const waiting = options.waiting === undefined ? undefined : waitingHours(options.waiting);
|
|
312
316
|
const env = environmentOf(this).env ?? process.env;
|
|
313
317
|
const now = Date.now();
|
|
314
|
-
const { found, mailbox, saved } = await mail.read(this, async (store, mailbox) => {
|
|
318
|
+
const { found, mailbox, saved, sorted } = await mail.read(this, async (store, mailbox) => {
|
|
315
319
|
const saved = options.new
|
|
316
320
|
? checkPoints(mail.app, {
|
|
317
321
|
command: pointsOf(this, "review", mail.app),
|
|
@@ -329,10 +333,10 @@ an agent over MCP, and each scheduled run.`)
|
|
|
329
333
|
...(unanswered === undefined ? {} : { unansweredAfterHours: unanswered }),
|
|
330
334
|
...(waiting === undefined ? {} : { waitingAfterHours: waiting }),
|
|
331
335
|
});
|
|
332
|
-
return { found, mailbox, saved };
|
|
336
|
+
return { found, mailbox, saved, sorted: await sortedOf(store, mailbox) };
|
|
333
337
|
});
|
|
334
338
|
const output = outputFor(this);
|
|
335
|
-
const answer = reviewAnswer(found, mailbox, saved !== undefined, stepsFor(mail.mount, mailbox));
|
|
339
|
+
const answer = reviewAnswer(found, mailbox, saved !== undefined, stepsFor(mail.mount, mailbox), sorted);
|
|
336
340
|
if (meta)
|
|
337
341
|
answer.meta = { ...meta, ...answer.meta };
|
|
338
342
|
answerLocally(this, output, answer, (local) => {
|
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
import type { AccountKey, MessageStore } from "../store/store.js";
|
|
2
|
+
export declare const INBOX_BUCKETS: readonly ["answer", "read", "later"];
|
|
3
|
+
export type InboxBucket = (typeof INBOX_BUCKETS)[number];
|
|
4
|
+
/** What one run may send: emails in all, tokens estimated before each request, and how each thread is cut. */
|
|
5
|
+
export declare const INBOX_LIMITS: {
|
|
6
|
+
emails: number;
|
|
7
|
+
tokens: number;
|
|
8
|
+
perThread: number;
|
|
9
|
+
chars: number;
|
|
10
|
+
batch: number;
|
|
11
|
+
reason: number;
|
|
12
|
+
};
|
|
13
|
+
export interface InboxVerdict {
|
|
14
|
+
thread: string;
|
|
15
|
+
title: string | null;
|
|
16
|
+
bucket: InboxBucket;
|
|
17
|
+
reason: string;
|
|
18
|
+
/** ISO: the newest email of the thread the model read. */
|
|
19
|
+
lastEmailAt: string;
|
|
20
|
+
/** ISO: the next run reads the thread's mail after this. */
|
|
21
|
+
through: string;
|
|
22
|
+
sortedAt: string;
|
|
23
|
+
/** `provider/model`. */
|
|
24
|
+
by: string;
|
|
25
|
+
}
|
|
26
|
+
/** Every sorted thread of the mailbox, those that need an answer first, then the newest. */
|
|
27
|
+
export declare const inboxVerdicts: (store: MessageStore, mailbox: AccountKey) => Promise<InboxVerdict[]>;
|
|
28
|
+
/** One thread as the model reads it: its newest emails, each without quoted mail or the signature. */
|
|
29
|
+
export interface InboxThread {
|
|
30
|
+
thread: string;
|
|
31
|
+
title: string | null;
|
|
32
|
+
lastEmailAt: string;
|
|
33
|
+
through: string;
|
|
34
|
+
emails: {
|
|
35
|
+
from: string;
|
|
36
|
+
at: string;
|
|
37
|
+
text: string;
|
|
38
|
+
}[];
|
|
39
|
+
/** Characters of what is sent for it, for the estimate. */
|
|
40
|
+
chars: number;
|
|
41
|
+
}
|
|
42
|
+
export interface InboxDue {
|
|
43
|
+
/** Newest first. */
|
|
44
|
+
threads: InboxThread[];
|
|
45
|
+
/** The owner wrote last in these: they need nothing, and their verdicts go. */
|
|
46
|
+
answered: {
|
|
47
|
+
thread: string;
|
|
48
|
+
through: string;
|
|
49
|
+
}[];
|
|
50
|
+
/** Threads of mail sent to many, lists or envelopes: never sent to the model. */
|
|
51
|
+
quiet: number;
|
|
52
|
+
/** Threads past what one review reads; the next run reads them. */
|
|
53
|
+
skipped: number;
|
|
54
|
+
until: string;
|
|
55
|
+
complete: boolean;
|
|
56
|
+
}
|
|
57
|
+
/** The threads that changed since each one's last sort, from what sync stored; reads only. */
|
|
58
|
+
export declare const inboxDue: (store: MessageStore, mailbox: AccountKey, now?: number) => Promise<InboxDue>;
|
|
59
|
+
/** About four characters a token: an estimate made before anything is sent, never billed. */
|
|
60
|
+
export declare const tokensOf: (chars: number) => number;
|
|
61
|
+
export declare const INBOX_ANSWER_SHAPE = "{\"threads\": [{\"ref\": \"1\", \"bucket\": \"answer\" | \"read\" | \"later\", \"reason\": \"one short line\"}]}";
|
|
62
|
+
export declare const INBOX_SYSTEM: string;
|
|
63
|
+
export type InboxSkip = "not-asked" | "repeated" | "bucket-unknown" | "no-reason" | "not-answered";
|
|
64
|
+
/** The model's answer to one batch: each verdict by the thread it names, and what was not usable. */
|
|
65
|
+
export declare const parseInboxAnswer: (text: string, batch: readonly InboxThread[]) => {
|
|
66
|
+
verdicts: Map<string, {
|
|
67
|
+
bucket: InboxBucket;
|
|
68
|
+
reason: string;
|
|
69
|
+
}>;
|
|
70
|
+
skipped: {
|
|
71
|
+
ref: string;
|
|
72
|
+
why: InboxSkip;
|
|
73
|
+
}[];
|
|
74
|
+
};
|
|
75
|
+
/** The text one request sends: each thread by its ref in the batch, its subject and its newest emails. */
|
|
76
|
+
export declare const inboxPrompt: (batch: readonly InboxThread[]) => string;
|
|
77
|
+
export interface InboxPlan {
|
|
78
|
+
/** What the run sends, in batches, within the limits. */
|
|
79
|
+
batches: InboxThread[][];
|
|
80
|
+
emails: number;
|
|
81
|
+
tokens: number;
|
|
82
|
+
/** Threads the limits leave for the next run. */
|
|
83
|
+
left: number;
|
|
84
|
+
stopped?: "messages" | "tokens";
|
|
85
|
+
}
|
|
86
|
+
/** Which of the due threads one run sends, newest first, without passing either limit. */
|
|
87
|
+
export declare const planInbox: (due: InboxDue, limits: {
|
|
88
|
+
emails: number;
|
|
89
|
+
tokens: number;
|
|
90
|
+
}) => InboxPlan;
|
|
91
|
+
export interface InboxSaved {
|
|
92
|
+
sorted: number;
|
|
93
|
+
answered: number;
|
|
94
|
+
/** The run read every due thread: the next one starts where this one ended. */
|
|
95
|
+
complete: boolean;
|
|
96
|
+
}
|
|
97
|
+
/**
|
|
98
|
+
* Keeps each verdict and drops those of threads the owner answered; moves where the next run starts only when
|
|
99
|
+
* nothing due was left out, so a thread the limits or a bad answer skipped comes again.
|
|
100
|
+
*/
|
|
101
|
+
export declare const saveInbox: (store: MessageStore, mailbox: AccountKey, due: InboxDue, sorted: readonly (InboxThread & {
|
|
102
|
+
bucket: InboxBucket;
|
|
103
|
+
reason: string;
|
|
104
|
+
})[], { by, now, complete }: {
|
|
105
|
+
by: string;
|
|
106
|
+
now?: number;
|
|
107
|
+
complete: boolean;
|
|
108
|
+
}) => Promise<InboxSaved>;
|