apple-tools-mcp 3.3.0 → 3.3.2
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/README.md +8 -1
- package/docs/mail-send-reconciliation.md +264 -0
- package/lib/mailIdempotency.js +79 -50
- package/lib/mailReconciliation.js +341 -0
- package/lib/noDashes.js +108 -0
- package/lib/writeTools.js +54 -14
- package/package.json +2 -1
package/README.md
CHANGED
|
@@ -326,7 +326,11 @@ Every write tool accepts:
|
|
|
326
326
|
|
|
327
327
|
Deletes need `confirm: true`: `mail_trash`, `calendar_remove`, `contacts_remove`, and `contacts_edit` when it clears every email or phone. These take one id per call, except `mail_trash`, which also takes a list (`message_ids`).
|
|
328
328
|
|
|
329
|
-
`mail_send` supports a stable `idempotency_key` per intended delivery.
|
|
329
|
+
`mail_send` supports a stable `idempotency_key` per intended delivery. Accepted delivery is replayed without sending again; changed content with the same key is refused. Without a key, identical accepted content is suppressed without expiry. A new key can name an intentional new delivery only after accepted or proven-unstarted outcomes; changing/removing keys cannot bypass identical pending or terminal `not_sent` content. Uncertain sends never expire or automatically retry. Missing Sent rows cannot prove a queued send will not finish. Claims persist across processes/restarts in the private `~/.apple-tools-mcp/mail-send-claims` directory, containing only hashes and outcome metadata. Dry runs create no claims.
|
|
330
|
+
|
|
331
|
+
`mail_send_reconcile` is a separate **no-send** operation with exact claim/attempt/revision/content identity, protected administrator-issued authority, a persistent cross-process writer fence, and fresh complete Sent **and** Outbox evidence collected after fencing. It preserves original attempts and appends authoritative audit/state records. `not_sent` is terminal, not retryable: any later retry requires a separate single-use authorization consumed durably before the existing transport handler. Legacy claims are always ineligible. Installation does not create authority, resolve any historical claim, retry mail, or alter a page ledger. By default, reconciliation refuses without the independently established administrative exclusion/evidence boundary. See the [full protocol and transition table](docs/mail-send-reconciliation.md).
|
|
332
|
+
|
|
333
|
+
Send and reconciliation results expose `structuredContent.mail_send` (schema version 1), separating suppression without current handler entry, attempted-but-unresolved transport, accepted historical replay, terminal suppression, identity/writer/evidence refusal and uncertain bridge handoff. Suppression and uncertainty authorize no retry or page-ledger update. Historical send replay also sets MCP `isError` so text-only clients cannot mistake it for a newly sent message. Global writer locks/fences do not expire or auto-recover after a crash; availability recovery requires a separate explicit maintenance decision.
|
|
330
334
|
|
|
331
335
|
A bridge request that expires before execution is rejected. After a handoff with an unknown outcome, local fallback is suppressed. The System Events preflight allows 10 seconds (12-second process cap); timeout reports `probe_timeout` and unknown permission status, separately from an explicit permission denial.
|
|
332
336
|
|
|
@@ -336,6 +340,8 @@ A dry run or a call that still needs confirm does not deliver anything. The resu
|
|
|
336
340
|
|
|
337
341
|
Responses name the action, ids, and recipients. They do not echo message bodies.
|
|
338
342
|
|
|
343
|
+
No dashes go out under your name. `mail_send`, `mail_draft`, `mail_reply`, `mail_forward` and `messages_send` rewrite dashes used as punctuation before Mail or Messages sees the text: an em dash or en dash becomes a comma ("to" between two numbers, nothing at the start or end of a line), and a hyphen with a space on each side becomes a comma. Hyphens inside names, identifiers, dates and URLs stay, and so does a hyphen that starts a line (a list bullet or the `-- ` signature line). The rewrite runs before the send claim and the Sent check, so both see the text that went out, and the result says how many it rewrote. A dry run reports it too.
|
|
344
|
+
|
|
339
345
|
A missing or malformed id or recipient is refused. Calendar times are local datetimes, `YYYY-MM-DD HH:MM`. Phrases like "next Tuesday" are rejected on writes.
|
|
340
346
|
|
|
341
347
|
### Mail
|
|
@@ -343,6 +349,7 @@ A missing or malformed id or recipient is refused. Calendar times are local date
|
|
|
343
349
|
| Tool | Arguments | Confirm |
|
|
344
350
|
|------|-----------|---------|
|
|
345
351
|
| `mail_send` | `to[]` (required), `cc[]`, `bcc[]`, `subject` (required), `body` (required), `body_format` (`plain` or `html`), `idempotency_key` | when recipients > 1 |
|
|
352
|
+
| `mail_send_reconcile` | `action` (`begin`/`commit`), exact claim binding, `deployment_ref`, `approval_ref`; commit also needs `fence_id`, `evidence_ref`, outcome and reason code | protected authority, not `confirm` |
|
|
346
353
|
| `mail_draft` | `to[]` (required), `cc[]`, `bcc[]`, `subject`, `body`, `body_format` | no (saved to Drafts) |
|
|
347
354
|
| `mail_reply` | `message_id` or `file_path`, `body` (required), `reply_all`, `save_as_draft` | when `reply_all` is true |
|
|
348
355
|
| `mail_forward` | `message_id` or `file_path`, `to[]` (required), `body`, `save_as_draft` | when recipients > 1 |
|
|
@@ -0,0 +1,264 @@
|
|
|
1
|
+
# Mail send reconciliation protocol v1
|
|
2
|
+
|
|
3
|
+
## Boundary and deployment
|
|
4
|
+
|
|
5
|
+
This is a **no-send** operation, not a Mail transport or a locked-screen
|
|
6
|
+
workaround. It imports no Mail, shell, UI, wake, clipboard or page-ledger code.
|
|
7
|
+
Installation does not adjudicate claims, create authority, authorize a retry,
|
|
8
|
+
change a page ledger or deliver historical mail. All legacy records are
|
|
9
|
+
ineligible, regardless of age, mailbox observations or missing metadata. No
|
|
10
|
+
legacy migration or adjudication is implemented.
|
|
11
|
+
|
|
12
|
+
The default deployment is closed. Positive reconciliation needs an external
|
|
13
|
+
administrator-controlled authority described below. This package does **not**
|
|
14
|
+
create that authority, manufacture verification evidence, stop old writers or
|
|
15
|
+
disable their launch sources. Without proven exclusion of nonparticipating
|
|
16
|
+
writers, it refuses. Do not create an authority manifest simply to bypass this
|
|
17
|
+
refusal. Establishing the privileged operational boundary and collecting real
|
|
18
|
+
evidence require their own approved operational work; offline fixtures are not
|
|
19
|
+
live evidence. No live claim or Mail operation is needed to install or smoke-test
|
|
20
|
+
the package.
|
|
21
|
+
|
|
22
|
+
## Identity and delivery lineage
|
|
23
|
+
|
|
24
|
+
`claim_id` is the existing claim-directory digest. The request binds the exact
|
|
25
|
+
`attempt`, `revision`, `fingerprint_algorithm: sha256-mail-content-v1` and
|
|
26
|
+
`fingerprint`. The fingerprint preserves the existing algorithm: SHA-256 of
|
|
27
|
+
the JSON array containing sorted/lowercased/trimmed To, Cc, Bcc, exact subject,
|
|
28
|
+
exact body and body format (default plain). It does not equate different HTML
|
|
29
|
+
or body strings. A supplied idempotency key must hash to that same directory;
|
|
30
|
+
it is never stored. Missing or conflicting identities do not create a claim.
|
|
31
|
+
The public `mail_send` structured result supplies modern claim bindings.
|
|
32
|
+
|
|
33
|
+
The latest attempt is authoritative. Changing or removing a key cannot escape
|
|
34
|
+
an unresolved or terminal not_sent claim with identical content, including a
|
|
35
|
+
legacy pending claim. A new key can name a genuinely new intended delivery
|
|
36
|
+
only after all identical-content lineages are accepted or proven not_started.
|
|
37
|
+
This retains the existing intentional-new-delivery convention for successful
|
|
38
|
+
sends, not for uncertain ones. Changing actual content defines another
|
|
39
|
+
fingerprint; callers must not disguise a retry by modifying a payload.
|
|
40
|
+
|
|
41
|
+
## Trusted references and authority
|
|
42
|
+
|
|
43
|
+
Tool arguments accept **references**, not caller-authored checked strings,
|
|
44
|
+
scripts, raw evidence or authority objects. A reference is the SHA-256 of the
|
|
45
|
+
exact UTF-8 bytes of an administrator-provisioned JSON file:
|
|
46
|
+
|
|
47
|
+
`/Library/Application Support/AppleTools/Reconciliation/<kind>/<ref>.json`
|
|
48
|
+
|
|
49
|
+
Kinds are `deployment`, `approval`, `evidence`, `authorization`. The root,
|
|
50
|
+
every ancestor, every file and `revocations.json` must be root-owned, not
|
|
51
|
+
group/world-writable and not a symlink. Files must be regular and bounded to
|
|
52
|
+
64 KiB. Content hashes must match. Missing, corrupt, unprotected or revoked
|
|
53
|
+
references refuse. These checks establish administrative provenance; a tool
|
|
54
|
+
caller with the ordinary user identity cannot issue proofs. Root is the
|
|
55
|
+
authorized issuer. The protocol does not claim protection against a malicious
|
|
56
|
+
administrator, kernel, or a Mail user independently sending messages.
|
|
57
|
+
|
|
58
|
+
`revocations.json` has `schema_version: 1`, `references: [<hash>...]` and
|
|
59
|
+
`ids: [<hash>...]`. It is reread on every authority lookup; a missing list is
|
|
60
|
+
not an empty list. References or authority IDs can be revoked. Revocation
|
|
61
|
+
before durable consumption prevents a retry; revocation cannot undo a consumed
|
|
62
|
+
permission or an already invoked transport. Expiration is checked again before
|
|
63
|
+
transport entry. Neither age nor revoked permission restores permission.
|
|
64
|
+
|
|
65
|
+
All authority records have `schema_version: 1`, integer epoch-millisecond
|
|
66
|
+
`issued_at`, `expires_at`, and `revoked: false`. The entire validity interval
|
|
67
|
+
is at most 60 seconds, with no future issue time and no clock uncertainty.
|
|
68
|
+
Authority records are immutable-by-reference. Replacing a record needs a new
|
|
69
|
+
reference. Operation IDs, fingerprints and protected references are bounded
|
|
70
|
+
hashes; operator/epoch IDs are bounded lowercase codes, not names or free text.
|
|
71
|
+
|
|
72
|
+
A deployment proof has `kind: deployment`, an epoch code, the complete list
|
|
73
|
+
of account hashes, authorized operator codes, `clock_uncertainty_ms: 0`,
|
|
74
|
+
`nonparticipating_launch_disabled: true`, and true exclusion assertions for
|
|
75
|
+
**all** of `daemon`, `local_fallback`, `accepted_bridge`, `scripts_appleevents`,
|
|
76
|
+
`old_processes`, `outstanding_effects`. The administrative issuer must actually
|
|
77
|
+
disable nonparticipating launch sources for the validity window and drain
|
|
78
|
+
already accepted requests/scripts/AppleEvents, not infer exclusion from a PID,
|
|
79
|
+
reused PID, heartbeat, lease, socket closure or timeout. The deployment proof
|
|
80
|
+
is the trusted administrative attestation of that operational enforcement,
|
|
81
|
+
not an automatic discovery mechanism. If it cannot be established, refuse.
|
|
82
|
+
|
|
83
|
+
Reconciliation approval has `kind: reconcile`, a unique hash ID, the full
|
|
84
|
+
claim binding, epoch and an operator code from that deployment proof. Retry
|
|
85
|
+
authorization is a separate record with `kind: retry`, a separate unique ID,
|
|
86
|
+
the **terminal** binding, operator, epoch and `single_use: true`. Reconciliation
|
|
87
|
+
neither issues nor consumes retry authorization. `confirm: true` is not
|
|
88
|
+
authority. There is no automatic approval, retry, requeue or ledger reset.
|
|
89
|
+
|
|
90
|
+
## Writer fence and fresh evidence
|
|
91
|
+
|
|
92
|
+
1. `mail_send_reconcile(action: begin, <binding>, deployment_ref, approval_ref)`
|
|
93
|
+
validates an existing modern pending claim and protected authority under
|
|
94
|
+
the global `.writer-lock`. It exclusively creates and synchronizes a
|
|
95
|
+
persistent `.reconciliation-fence.json`, then returns a random hash
|
|
96
|
+
`fence_id`. Repeating begin with the same identity and references returns
|
|
97
|
+
that fence. No transport is invoked.
|
|
98
|
+
2. Every participating `mail_send` and other Mail write (reply, forward,
|
|
99
|
+
draft, mark, archive, trash) takes the same cross-process lock and refuses
|
|
100
|
+
while the fence exists. A bridge request accepted before begin still
|
|
101
|
+
checks it when its handler executes. Nonparticipating versions/scripts
|
|
102
|
+
are excluded only by the administrative boundary, never by pretending
|
|
103
|
+
they honor this lock. The deployment epoch cannot change mid-operation.
|
|
104
|
+
3. Only **after** the fence exists, the authorized operator obtains complete
|
|
105
|
+
exact-content Sent **and** Outbox observations from the accepted source,
|
|
106
|
+
`complete_exact_mail_snapshot_v1`. This name denotes a privileged,
|
|
107
|
+
administrator-validated complete snapshot; it does not bless an arbitrary
|
|
108
|
+
client claiming that source. This build ships no snapshot collector.
|
|
109
|
+
The administrator provisions the protected evidence record with its
|
|
110
|
+
provenance and explicit adjudication. Caller-created artifacts are not
|
|
111
|
+
accepted. Negative observations alone do not decide an outcome.
|
|
112
|
+
4. Commit rechecks authority, exclusion, binding, freshness and both mailbox
|
|
113
|
+
observations under the lock. It appends one authoritative terminal
|
|
114
|
+
state/audit record, synchronizes it, then removes/synchronizes the fence.
|
|
115
|
+
It never enters Mail. Refusals retain an existing fence; they never make
|
|
116
|
+
a claim retryable. An expired fence has **no automatic release**.
|
|
117
|
+
|
|
118
|
+
Evidence has `kind: mail_verification`, a unique hash ID, exact binding,
|
|
119
|
+
fence ID, epoch, authorized operator, source, zero clock uncertainty,
|
|
120
|
+
`effects_drained: true`, explicit `outcome: sent | not_sent`, and the matching
|
|
121
|
+
reason code `operator_verified_sent | operator_verified_not_sent`.
|
|
122
|
+
|
|
123
|
+
Separate `sent` and `outbox` observations each require `completed: true`,
|
|
124
|
+
`error: null`, `index_used: false`, the complete deployment `accounts` list,
|
|
125
|
+
`exact_fingerprint`, integer `observed_at` **after** fence creation, integer
|
|
126
|
+
`search_from` no later than attempt creation, `search_to` equal to the
|
|
127
|
+
observation time, and `matches: []`. Both observations must be at most 60
|
|
128
|
+
seconds old, not in the future, and no later than the evidence issue time.
|
|
129
|
+
Partial scans, unavailable accounts, stale indexes, errors, incomplete history,
|
|
130
|
+
unknown clocks, ambiguity or any queued Outbox match refuse. A sent decision
|
|
131
|
+
requires exactly one Sent match with an account from the covered set, exact
|
|
132
|
+
fingerprint, protected `message_ref`, and `message_id_hash` matching the
|
|
133
|
+
evidence-level exact Message-ID hash. Not_sent requires zero matches in both
|
|
134
|
+
mailboxes **plus** the explicit protected operator decision.
|
|
135
|
+
|
|
136
|
+
## Authoritative audit/state transaction and failure recovery
|
|
137
|
+
|
|
138
|
+
New attempts keep their original `<attempt>.json` pending record forever.
|
|
139
|
+
Immutable, exclusively created `<attempt>.events/<revision>.json` records
|
|
140
|
+
are the **only** outcome state; there is no separate mutable state file to
|
|
141
|
+
update ahead of the audit. Records include schema version, binding, revision,
|
|
142
|
+
previous hash, integrity hash and bounded metadata. Initial attempts also
|
|
143
|
+
have an integrity hash. Hashes detect accidental corruption, not same-user
|
|
144
|
+
forgery: the user's claim storage is not immutable against that user.
|
|
145
|
+
|
|
146
|
+
Ordering: create initial attempt exclusively, write, file fsync, parent
|
|
147
|
+
directory fsync, claim-root fsync, then handler entry. For outcomes, create
|
|
148
|
+
the journal directory, synchronize its parent, exclusively create the next
|
|
149
|
+
event, write, file fsync and journal-directory fsync before returning a
|
|
150
|
+
committed receipt. The appended record is simultaneously audit and state.
|
|
151
|
+
No terminal or retryable state is published by a separate write.
|
|
152
|
+
|
|
153
|
+
Torn, missing-sequence, divergent, corrupt or unsynchronized writes fail
|
|
154
|
+
closed. Disk-full and failed fsync never permit transport or a second
|
|
155
|
+
transport invocation. A crash or unknown durability failure retains the
|
|
156
|
+
global lock, without expiry, PID-based takeover or automatic repair. Recovery
|
|
157
|
+
of that availability requires a separate explicit maintenance decision;
|
|
158
|
+
this API does not remove an orphan lock. An already committed identical
|
|
159
|
+
reconciliation can return its immutable receipt read-only even with an orphan
|
|
160
|
+
lock or lost reply. A complete record surviving an interrupted synchronization
|
|
161
|
+
is revalidated and synchronized (file and parent directories) before replay;
|
|
162
|
+
an unavailable disk cannot produce a successful receipt. No missing or torn
|
|
163
|
+
record is synthesized. A leftover fence after a commit is not automatically
|
|
164
|
+
cleared by replay. It cannot unlock mail. Original attempts are never deleted,
|
|
165
|
+
rewritten or retroactively annotated.
|
|
166
|
+
|
|
167
|
+
Allowlisted reconciliation audit fields are request hash, receipt hash,
|
|
168
|
+
evidence/approval references, reason code, operator code, optional protected
|
|
169
|
+
message reference and commit time, plus structural binding/hash fields.
|
|
170
|
+
No raw key, addresses, subject, body, clipboard, scripts, free-text reason,
|
|
171
|
+
raw error or tool-result text is persisted.
|
|
172
|
+
|
|
173
|
+
## Transition table
|
|
174
|
+
|
|
175
|
+
| Current state | Operation | Result |
|
|
176
|
+
|---|---|---|
|
|
177
|
+
| Absent | ordinary send | Durable new pending attempt, then one handler invocation |
|
|
178
|
+
| Modern pending | another ordinary send, any key | Suppressed; no new attempt or handler |
|
|
179
|
+
| Modern pending | valid reconciliation | Append done or terminal not_sent; no handler |
|
|
180
|
+
| Legacy pending | reconciliation | Always ineligible; no migration or new metadata |
|
|
181
|
+
| Legacy pending | ordinary send, any key | Suppressed |
|
|
182
|
+
| Done | same delivery send | Accepted historical replay, not a new delivery |
|
|
183
|
+
| Done | genuinely new intentional key | New delivery, unless another identical-content lineage blocks it |
|
|
184
|
+
| Not_started | ordinary send | Existing proven-unstarted behavior; new pending attempt |
|
|
185
|
+
| Not_sent | ordinary send, changed/removed key, confirm | Terminal suppression; no attempt allocation |
|
|
186
|
+
| Not_sent | separate valid single-use retry approval | Durable consumption, then one new pending attempt |
|
|
187
|
+
| Terminal | identical reconciliation | Return the committed receipt |
|
|
188
|
+
| Terminal | conflicting outcome, stale binding or revision | Refuse |
|
|
189
|
+
| Consumed retry | timeout, crash, lost reply, proven-unstarted | Permission remains spent; no automatic recovery |
|
|
190
|
+
|
|
191
|
+
Retry consumption exclusively creates and synchronizes a global
|
|
192
|
+
`.authorizations/<authorization-id>.json` audit binding the grant to one
|
|
193
|
+
claim/fingerprint and one new retry attempt **before** that attempt enters
|
|
194
|
+
the existing transport handler. The new attempt also stores the authorization
|
|
195
|
+
ID. Concurrent/replayed consumers cannot invoke another handler. A crash
|
|
196
|
+
after consumption but before transport sacrifices permission and may sacrifice
|
|
197
|
+
delivery. V1 does **not** allow another authorization after a consumed,
|
|
198
|
+
proven-unstarted retry; a separately reviewed future protocol would be needed.
|
|
199
|
+
Admission checks both the attempt's authorization provenance and all durable
|
|
200
|
+
consumption records for its claim lineage, including a consumption whose crash
|
|
201
|
+
prevented creation of the retry attempt. A different grant cannot restore it.
|
|
202
|
+
The complete consumption record has a verified integrity hash before any lineage
|
|
203
|
+
field is trusted. Missing hashes and valid-shape corruption refuse closed. As
|
|
204
|
+
with claim/event hashes, this detects corruption, not malicious same-user edits.
|
|
205
|
+
This promises at-most-once authorized handler invocation, not exactly-once
|
|
206
|
+
delivery by Mail or a remote mail server.
|
|
207
|
+
|
|
208
|
+
Page-ledger reconciliation is a separate workflow. Every machine result says
|
|
209
|
+
`ledger_action: none` and `retry_authorized: false` (no permission for a future
|
|
210
|
+
invocation). A claim receipt cannot reset or advance the page ledger. A caller
|
|
211
|
+
observing disagreement must report that mismatch; it cannot partially reset
|
|
212
|
+
two systems. This operation never imports or touches a ledger.
|
|
213
|
+
|
|
214
|
+
## External results and safe logs
|
|
215
|
+
|
|
216
|
+
MCP exposes `structuredContent.mail_send` with `schema_version: 1`, `code`,
|
|
217
|
+
`current_invocation_transport: none | entered | unknown`,
|
|
218
|
+
`historical_effects`, `ledger_action`, `retry_authorized`, and applicable
|
|
219
|
+
binding/fence/receipt fields. `entered` means this invocation entered the
|
|
220
|
+
existing synchronous transport **handler**, not proof that Mail acknowledged
|
|
221
|
+
a send. Lower-level dispatch remains unknown unless independently observed.
|
|
222
|
+
|
|
223
|
+
Important codes: `pending_suppressed`, `transport_unresolved`,
|
|
224
|
+
`transport_accepted`, `accepted_replay`, `not_sent_suppressed`,
|
|
225
|
+
`identity_refused`, `legacy_ineligible`, `active_writer_refused`,
|
|
226
|
+
`evidence_refused`, `authorization_refused`, `durability_refused`,
|
|
227
|
+
`revision_refused`, `outcome_conflict`, `bridge_uncertain`,
|
|
228
|
+
`evidence_required`, `reconciled`, `reconciliation_replayed`.
|
|
229
|
+
`authorization_spent` distinguishes a consumed approval whose handler proved
|
|
230
|
+
it never started sending; that result still grants no future attempt.
|
|
231
|
+
Suppression has no handler entry this invocation, but earlier effects may
|
|
232
|
+
still finish. An uncertain bridge handoff reports unknown entry for send;
|
|
233
|
+
reconciliation always reports none. It never locally replays a possibly
|
|
234
|
+
accepted bridge operation. Text-only clients also get `isError: true` for
|
|
235
|
+
historical send replay, preventing them mistaking suppression for a newly sent
|
|
236
|
+
message. All callers must honor `ledger_action: none` on suppression and
|
|
237
|
+
uncertainty, not scrape text or treat `ok` as a new delivery.
|
|
238
|
+
|
|
239
|
+
Allowlisted stage records are `handler_entered`, `handler_completed` and
|
|
240
|
+
`verification_completed`, with
|
|
241
|
+
entered/completed semantics, bounded hash operation ID, numeric attempt,
|
|
242
|
+
local-handler route, protocol version, monotonic elapsed milliseconds, and
|
|
243
|
+
explicit unknown dispatch-attempted/acknowledged fields. A completion marker
|
|
244
|
+
for the handler means only it returned. Verification outcomes are allowlisted
|
|
245
|
+
as sent, outbox, accepted, not_started, unresolved or unknown, never raw tool
|
|
246
|
+
text. Bridge outcome codes also record verification
|
|
247
|
+
results without claiming that suppressed mail was sent. Logging failure
|
|
248
|
+
does not change state or grant permission. No sender changes or timeout
|
|
249
|
+
increases are part of this contract.
|
|
250
|
+
|
|
251
|
+
## Offline verification and smoke
|
|
252
|
+
|
|
253
|
+
`tests/unit/mail-reconciliation.test.js` uses fresh temporary directories,
|
|
254
|
+
synthetic manifests, injected authority/IO and independent processes with
|
|
255
|
+
controlled start barriers. It never calls Mail, a page ledger, an existing
|
|
256
|
+
claim or a real verification collector. It covers identity, evidence,
|
|
257
|
+
mailbox/account ambiguity, exclusion, persistence/fault boundaries, immutable
|
|
258
|
+
replay, terminal suppression, authorization and structured external results.
|
|
259
|
+
Existing mail-send and bridge tests cover late completion and fallback rules.
|
|
260
|
+
|
|
261
|
+
Installation smoke can list the tool schema and call a synthetic
|
|
262
|
+
`dry_run: true` reconciliation with an isolated home. Preview creates no
|
|
263
|
+
claim, fence, audit or authority. It is not an adjudication or a delivery
|
|
264
|
+
verification. Never use a historical claim for smoke testing.
|
package/lib/mailIdempotency.js
CHANGED
|
@@ -1,13 +1,7 @@
|
|
|
1
1
|
import fs from "fs";
|
|
2
2
|
import path from "path";
|
|
3
|
-
import { createHash } from "crypto";
|
|
4
3
|
import { getAppleToolsDir } from "./config.js";
|
|
5
|
-
|
|
6
|
-
const digest = (value) => createHash("sha256").update(value).digest("hex");
|
|
7
|
-
const uncertain = () => ({
|
|
8
|
-
ok: false, unconfirmed: true, sendStarted: true,
|
|
9
|
-
message: "mail_send: unconfirmed. An earlier identical send may still complete. Check Sent and Outbox; do not resend."
|
|
10
|
-
});
|
|
4
|
+
import { FINGERPRINT_ALGORITHM, mailFingerprint, mailClaimId, mailOutcome, readMailClaim, appendMailOutcome, durableCreate, syncDirectory, withMailWriterLock, reconciliationFencePath, protectedMailAuthority, validateRetryAuthorization, assertUnspentRetryLineage, refuse, claimBinding, mailRecordHash, mailAttempts } from "./mailReconciliation.js";
|
|
11
5
|
|
|
12
6
|
/** Cross-process, restart-safe send claims. Only hashes and outcome metadata
|
|
13
7
|
* are stored. A crash or corrupt record fails closed, including an empty file
|
|
@@ -15,56 +9,91 @@ const uncertain = () => ({
|
|
|
15
9
|
* expires: a missing Sent row cannot prove a queued send will not run later.
|
|
16
10
|
*/
|
|
17
11
|
export function idempotentMailSend(args, run, {
|
|
18
|
-
directory = path.join(getAppleToolsDir(), "mail-send-claims"), now = Date.now
|
|
12
|
+
directory = path.join(getAppleToolsDir(), "mail-send-claims"), now = Date.now,
|
|
13
|
+
authority = protectedMailAuthority(), io = fs, log = record => console.error(JSON.stringify(record)), monotonic = () => process.hrtime.bigint()
|
|
19
14
|
} = {}) {
|
|
20
15
|
if (args.dry_run === true) return run();
|
|
21
16
|
const key = args.idempotency_key;
|
|
22
17
|
if (key !== undefined && (typeof key !== "string" || !key.trim() || key.length > 256)) {
|
|
23
|
-
return
|
|
18
|
+
return mailOutcome("identity_refused");
|
|
24
19
|
}
|
|
25
|
-
const
|
|
26
|
-
const
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
]));
|
|
30
|
-
const dir = path.join(directory, digest(key === undefined ? fingerprint : `key:${key}`));
|
|
20
|
+
const fingerprint = mailFingerprint(args);
|
|
21
|
+
const id = mailClaimId(fingerprint, key);
|
|
22
|
+
const dir = path.join(directory, id);
|
|
23
|
+
let entered = false;
|
|
31
24
|
try {
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
25
|
+
return withMailWriterLock(directory, () => {
|
|
26
|
+
if (fs.existsSync(reconciliationFencePath(directory))) return mailOutcome("active_writer_refused");
|
|
27
|
+
for (const candidate of fs.readdirSync(directory).filter(name => /^[a-f0-9]{64}$/.test(name) && name !== id)) {
|
|
28
|
+
const attempts = mailAttempts(directory, candidate);
|
|
29
|
+
if (!attempts.length) continue;
|
|
30
|
+
const previous = readMailClaim(directory, candidate, Math.max(...attempts));
|
|
31
|
+
if (previous.fingerprint === fingerprint && !["done", "not_started"].includes(previous.state)) {
|
|
32
|
+
return mailOutcome(previous.state === "not_sent" ? "not_sent_suppressed" : "pending_suppressed", { historical: previous.state, ...(previous.legacy ? { legacy: true } : claimBinding(previous)) });
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
|
|
36
|
+
fs.chmodSync(directory, 0o700);
|
|
37
|
+
fs.chmodSync(dir, 0o700);
|
|
38
|
+
const attempts = mailAttempts(directory, id);
|
|
39
|
+
const last = attempts.length ? Math.max(...attempts) : 0;
|
|
40
|
+
let authorizationId;
|
|
41
|
+
let authorizationBinding;
|
|
42
|
+
if (last) {
|
|
43
|
+
const previous = readMailClaim(directory, id, last);
|
|
44
|
+
if (previous.fingerprint !== fingerprint) {
|
|
45
|
+
return mailOutcome("identity_refused");
|
|
46
|
+
}
|
|
47
|
+
if (previous.state === "done") {
|
|
48
|
+
if (previous.legacy && previous.result?.ok !== true) return mailOutcome("pending_suppressed");
|
|
49
|
+
return { ...mailOutcome("accepted_replay", { ok: true, historical: "accepted", ...(previous.legacy ? { legacy: true } : claimBinding(previous)) }), deduplicated: true };
|
|
50
|
+
}
|
|
51
|
+
if (previous.state === "not_sent" && args.retry_authorization_ref !== undefined && !previous.legacy) {
|
|
52
|
+
assertUnspentRetryLineage(directory, previous);
|
|
53
|
+
authorizationId = validateRetryAuthorization(authority, args.retry_authorization_ref, args.deployment_ref, previous, now());
|
|
54
|
+
authorizationBinding = claimBinding(previous);
|
|
55
|
+
for (const attempt of attempts) {
|
|
56
|
+
const original = JSON.parse(fs.readFileSync(path.join(dir, `${attempt}.json`), "utf8"));
|
|
57
|
+
if (original.authorization_id === authorizationId) refuse("authorization_refused");
|
|
58
|
+
}
|
|
59
|
+
} else if (previous.state !== "not_started") {
|
|
60
|
+
return mailOutcome(previous.state === "not_sent" ? "not_sent_suppressed" : "pending_suppressed", { historical: previous.state, ...(previous.legacy ? { legacy: true } : claimBinding(previous)) });
|
|
61
|
+
}
|
|
41
62
|
}
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
63
|
+
const file = path.join(dir, `${last + 1}.json`);
|
|
64
|
+
if (args.retry_authorization_ref !== undefined && !authorizationId) refuse("authorization_refused");
|
|
65
|
+
if (authorizationId) {
|
|
66
|
+
const consumed = path.join(directory, ".authorizations");
|
|
67
|
+
io.mkdirSync(consumed, { recursive: true, mode: 0o700 });
|
|
68
|
+
syncDirectory(directory, io);
|
|
69
|
+
if (fs.existsSync(path.join(consumed, `${authorizationId}.json`))) refuse("authorization_refused");
|
|
70
|
+
const consumption = { schema_version: 1, authorization_id: authorizationId, authorization_ref: args.retry_authorization_ref, ...authorizationBinding, retry_attempt: last + 1, consumed_at: now() };
|
|
71
|
+
consumption.integrity_hash = mailRecordHash(consumption);
|
|
72
|
+
durableCreate(path.join(consumed, `${authorizationId}.json`), consumption, io);
|
|
45
73
|
}
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
74
|
+
const claim = { protocol_version: 1, claim_id: id, attempt: last + 1, revision: 1, fingerprint_algorithm: FINGERPRINT_ALGORITHM, fingerprint, createdAt: now(), state: "pending", ...(authorizationId ? { authorization_id: authorizationId } : {}) };
|
|
75
|
+
claim.integrity_hash = mailRecordHash(claim);
|
|
76
|
+
durableCreate(file, claim, io);
|
|
77
|
+
syncDirectory(directory, io);
|
|
78
|
+
if (authorizationId) validateRetryAuthorization(authority, args.retry_authorization_ref, args.deployment_ref, readMailClaim(directory, id, last), now());
|
|
79
|
+
const started = monotonic();
|
|
80
|
+
const stage = (code, verification = "unknown") => {
|
|
81
|
+
try { log({ schema_version: 1, stage: code, semantics: code.endsWith("completed") ? "completed" : "entered", attempt: claim.attempt, operation_id: id, route: "local_handler", protocol_version: 1, elapsed_ms: Math.max(0, Number(monotonic() - started) / 1e6), dispatch_attempted: "unknown", dispatch_acknowledged: "unknown", verification }); } catch {}
|
|
82
|
+
};
|
|
83
|
+
stage("handler_entered");
|
|
84
|
+
entered = true;
|
|
85
|
+
let result;
|
|
86
|
+
try { result = run(); } catch { return mailOutcome("transport_unresolved", { entry: "entered", ...claimBinding(claim) }); }
|
|
87
|
+
stage("handler_completed");
|
|
88
|
+
const safe = result?.sendStarted === false || result?.planned === true || /^mail_send refused:/.test(result?.message || "");
|
|
89
|
+
stage("verification_completed", result?.ok === true ? ["sent", "outbox"].includes(result.mailbox) ? result.mailbox : "accepted" : safe ? "not_started" : "unresolved");
|
|
90
|
+
const state = result?.ok === true ? "done" : safe && !authorizationId ? "not_started" : "pending";
|
|
91
|
+
let finalClaim = readMailClaim(directory, id, last + 1);
|
|
92
|
+
if (state !== "pending") finalClaim = appendMailOutcome(directory, finalClaim, { state, committed_at: now() }, io);
|
|
93
|
+
const code = result?.ok === true ? "transport_accepted" : safe ? authorizationId ? "authorization_spent" : "not_started" : "transport_unresolved";
|
|
94
|
+
return { ...result, ...mailOutcome(code, { ok: result?.ok === true, entry: "entered", historical: state, ...claimBinding(finalClaim) }), ...(safe ? { sendStarted: false } : {}), message: result?.message || mailOutcome(code).message };
|
|
95
|
+
});
|
|
96
|
+
} catch (error) {
|
|
97
|
+
return mailOutcome(error.mailCode || "durability_refused", { entry: entered ? "entered" : "none" });
|
|
69
98
|
}
|
|
70
99
|
}
|
|
@@ -0,0 +1,341 @@
|
|
|
1
|
+
import fs from "fs";
|
|
2
|
+
import path from "path";
|
|
3
|
+
import { createHash, randomUUID } from "crypto";
|
|
4
|
+
import { getAppleToolsDir } from "./config.js";
|
|
5
|
+
|
|
6
|
+
export const FINGERPRINT_ALGORITHM = "sha256-mail-content-v1";
|
|
7
|
+
export const RECONCILIATION_VERSION = 1;
|
|
8
|
+
const digest = value => createHash("sha256").update(value).digest("hex");
|
|
9
|
+
const hashPattern = /^[a-f0-9]{64}$/;
|
|
10
|
+
const codePattern = /^[a-z][a-z0-9_-]{0,63}$/;
|
|
11
|
+
const bindingFields = ["claim_id", "attempt", "revision", "fingerprint_algorithm", "fingerprint"];
|
|
12
|
+
const refusals = new Set(["identity_refused", "legacy_ineligible", "active_writer_refused", "evidence_refused", "authorization_refused", "durability_refused", "revision_refused", "outcome_conflict"]);
|
|
13
|
+
const reasonCodes = new Set(["operator_verified_sent", "operator_verified_not_sent"]);
|
|
14
|
+
|
|
15
|
+
export const mailRecordHash = value => digest(JSON.stringify(value));
|
|
16
|
+
|
|
17
|
+
export function mailFingerprint(args) {
|
|
18
|
+
const addresses = values => Array.isArray(values) ? values.map(value => String(value).trim().toLowerCase()).sort() : values;
|
|
19
|
+
return digest(JSON.stringify([addresses(args.to), addresses(args.cc || []), addresses(args.bcc || []), args.subject, args.body, args.body_format || "plain"]));
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export function mailClaimId(fingerprint, key) {
|
|
23
|
+
return digest(key === undefined ? fingerprint : `key:${key}`);
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
export function mailOutcome(code, { ok = false, entry = "none", historical = "unknown", ...fields } = {}) {
|
|
27
|
+
return {
|
|
28
|
+
ok,
|
|
29
|
+
sendStarted: entry === "entered" ? true : entry === "unknown" ? undefined : false,
|
|
30
|
+
unconfirmed: ["pending_suppressed", "transport_unresolved", "bridge_uncertain", "active_writer_refused", "durability_refused"].includes(code),
|
|
31
|
+
message: `mail_send: ${code}. No automatic retry or ledger update is authorized.`,
|
|
32
|
+
mail_send: { schema_version: 1, code, current_invocation_transport: entry, historical_effects: historical, ledger_action: "none", retry_authorized: false, ...fields }
|
|
33
|
+
};
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
export function refuse(code) {
|
|
37
|
+
const error = new Error(refusals.has(code) ? code : "durability_refused");
|
|
38
|
+
error.mailCode = error.message;
|
|
39
|
+
throw error;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
function regularFile(file) {
|
|
43
|
+
const stat = fs.lstatSync(file);
|
|
44
|
+
if (!stat.isFile() || stat.isSymbolicLink() || stat.size > 65536) refuse("durability_refused");
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
function readJson(file) {
|
|
48
|
+
regularFile(file);
|
|
49
|
+
return JSON.parse(fs.readFileSync(file, "utf8"));
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
export function syncDirectory(directory, io = fs) {
|
|
53
|
+
const descriptor = io.openSync(directory, "r");
|
|
54
|
+
try { io.fsyncSync(descriptor); } finally { io.closeSync(descriptor); }
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
export function durableCreate(file, value, io = fs) {
|
|
58
|
+
const descriptor = io.openSync(file, "wx", 0o600);
|
|
59
|
+
try {
|
|
60
|
+
io.writeFileSync(descriptor, JSON.stringify(value));
|
|
61
|
+
io.fsyncSync(descriptor);
|
|
62
|
+
} finally { io.closeSync(descriptor); }
|
|
63
|
+
syncDirectory(path.dirname(file), io);
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
export function withMailWriterLock(directory, work) {
|
|
67
|
+
const missing = [];
|
|
68
|
+
for (let current = directory; !fs.existsSync(current); current = path.dirname(current)) missing.push(current);
|
|
69
|
+
fs.mkdirSync(directory, { recursive: true, mode: 0o700 });
|
|
70
|
+
for (const created of missing) syncDirectory(path.dirname(created));
|
|
71
|
+
const lock = path.join(directory, ".writer-lock");
|
|
72
|
+
try { fs.mkdirSync(lock, { mode: 0o700 }); } catch { refuse("active_writer_refused"); }
|
|
73
|
+
try {
|
|
74
|
+
const result = work();
|
|
75
|
+
fs.rmdirSync(lock);
|
|
76
|
+
return result;
|
|
77
|
+
} catch (error) {
|
|
78
|
+
if (error.mailCode && error.mailCode !== "durability_refused") fs.rmdirSync(lock);
|
|
79
|
+
throw error;
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
export function claimBinding(claim) {
|
|
84
|
+
return Object.fromEntries(bindingFields.map(field => [field, claim[field]]));
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
function sameBinding(left, right) {
|
|
88
|
+
return bindingFields.every(field => left[field] === right[field]);
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
function validateBinding(value) {
|
|
92
|
+
if (!value || !hashPattern.test(value.claim_id) || !hashPattern.test(value.fingerprint) || value.fingerprint_algorithm !== FINGERPRINT_ALGORITHM ||
|
|
93
|
+
!Number.isSafeInteger(value.attempt) || value.attempt < 1 || !Number.isSafeInteger(value.revision) || value.revision < 1) refuse("identity_refused");
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
export function readMailClaim(directory, id, attempt) {
|
|
97
|
+
if (!hashPattern.test(id) || !Number.isSafeInteger(attempt) || attempt < 1) refuse("identity_refused");
|
|
98
|
+
const claimDirectory = path.join(directory, id);
|
|
99
|
+
if (!fs.existsSync(path.join(claimDirectory, `${attempt}.json`))) refuse("identity_refused");
|
|
100
|
+
const stat = fs.lstatSync(claimDirectory);
|
|
101
|
+
if (!stat.isDirectory() || stat.isSymbolicLink()) refuse("identity_refused");
|
|
102
|
+
const claim = readJson(path.join(claimDirectory, `${attempt}.json`));
|
|
103
|
+
if (claim.protocol_version === undefined) return { ...claim, legacy: true };
|
|
104
|
+
if (claim.protocol_version !== 1) refuse("identity_refused");
|
|
105
|
+
validateBinding(claim);
|
|
106
|
+
const { integrity_hash: initialHash, ...initialPayload } = claim;
|
|
107
|
+
if (initialHash !== mailRecordHash(initialPayload) || !Number.isSafeInteger(claim.createdAt) || claim.createdAt < 0 ||
|
|
108
|
+
claim.claim_id !== id || claim.attempt !== attempt || claim.revision !== 1 || claim.state !== "pending") refuse("identity_refused");
|
|
109
|
+
let state = { ...claim, record_hash: digest(JSON.stringify(claim)) };
|
|
110
|
+
const initialDescriptor = fs.openSync(path.join(claimDirectory, `${attempt}.json`), "r");
|
|
111
|
+
try { fs.fsyncSync(initialDescriptor); } finally { fs.closeSync(initialDescriptor); }
|
|
112
|
+
syncDirectory(claimDirectory);
|
|
113
|
+
syncDirectory(directory);
|
|
114
|
+
const journal = path.join(claimDirectory, `${attempt}.events`);
|
|
115
|
+
if (!fs.existsSync(journal)) return state;
|
|
116
|
+
const journalStat = fs.lstatSync(journal);
|
|
117
|
+
if (!journalStat.isDirectory() || journalStat.isSymbolicLink()) refuse("durability_refused");
|
|
118
|
+
const names = fs.readdirSync(journal).sort((left, right) => Number(left.slice(0, -5)) - Number(right.slice(0, -5)));
|
|
119
|
+
for (let index = 0; index < names.length; index++) {
|
|
120
|
+
if (names[index] !== `${index + 2}.json`) refuse("durability_refused");
|
|
121
|
+
const event = readJson(path.join(journal, names[index]));
|
|
122
|
+
const { integrity_hash: eventHash, ...eventPayload } = event;
|
|
123
|
+
if (eventHash !== mailRecordHash(eventPayload) || event.schema_version !== 1 || event.revision !== state.revision + 1 || event.previous_hash !== state.record_hash ||
|
|
124
|
+
event.claim_id !== id || event.attempt !== attempt || event.fingerprint !== claim.fingerprint || event.fingerprint_algorithm !== claim.fingerprint_algorithm ||
|
|
125
|
+
!["done", "not_started", "not_sent"].includes(event.state) || state.state !== "pending") refuse("durability_refused");
|
|
126
|
+
state = { ...claim, ...event, record_hash: digest(JSON.stringify(event)) };
|
|
127
|
+
const descriptor = fs.openSync(path.join(journal, names[index]), "r");
|
|
128
|
+
try { fs.fsyncSync(descriptor); } finally { fs.closeSync(descriptor); }
|
|
129
|
+
}
|
|
130
|
+
syncDirectory(journal);
|
|
131
|
+
syncDirectory(claimDirectory);
|
|
132
|
+
return state;
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
export function appendMailOutcome(directory, claim, metadata, io = fs) {
|
|
136
|
+
const journal = path.join(directory, claim.claim_id, `${claim.attempt}.events`);
|
|
137
|
+
io.mkdirSync(journal, { recursive: true, mode: 0o700 });
|
|
138
|
+
syncDirectory(path.dirname(journal), io);
|
|
139
|
+
const event = {
|
|
140
|
+
schema_version: 1, ...claimBinding(claim), revision: claim.revision + 1,
|
|
141
|
+
previous_hash: claim.record_hash, ...metadata
|
|
142
|
+
};
|
|
143
|
+
event.integrity_hash = mailRecordHash(event);
|
|
144
|
+
durableCreate(path.join(journal, `${event.revision}.json`), event, io);
|
|
145
|
+
return { ...claim, ...event, record_hash: digest(JSON.stringify(event)) };
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
const defaultAuthorityRoot = "/Library/Application Support/AppleTools/Reconciliation";
|
|
149
|
+
|
|
150
|
+
function assertProtected(file, directory = false) {
|
|
151
|
+
let current = path.resolve(file);
|
|
152
|
+
while (true) {
|
|
153
|
+
const stat = fs.lstatSync(current);
|
|
154
|
+
if (stat.isSymbolicLink() || stat.uid !== 0 || (stat.mode & 0o022) !== 0 ||
|
|
155
|
+
(current === path.resolve(file) && (directory ? !stat.isDirectory() : !stat.isFile()))) refuse("evidence_refused");
|
|
156
|
+
const parent = path.dirname(current);
|
|
157
|
+
if (parent === current) break;
|
|
158
|
+
current = parent;
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
export function protectedMailAuthority(root = defaultAuthorityRoot) {
|
|
163
|
+
return {
|
|
164
|
+
load(kind, reference) {
|
|
165
|
+
if (!["deployment", "approval", "evidence", "authorization"].includes(kind) || !hashPattern.test(reference)) refuse("evidence_refused");
|
|
166
|
+
try {
|
|
167
|
+
assertProtected(root, true);
|
|
168
|
+
const file = path.join(root, kind, `${reference}.json`);
|
|
169
|
+
assertProtected(file);
|
|
170
|
+
regularFile(file);
|
|
171
|
+
const revocationsFile = path.join(root, "revocations.json");
|
|
172
|
+
assertProtected(revocationsFile);
|
|
173
|
+
const revocations = readJson(revocationsFile);
|
|
174
|
+
const raw = fs.readFileSync(file, "utf8");
|
|
175
|
+
if (raw.length > 65536 || digest(raw) !== reference || revocations.schema_version !== 1 || !Array.isArray(revocations.references) ||
|
|
176
|
+
revocations.references.some(value => !hashPattern.test(value)) || !Array.isArray(revocations.ids) || revocations.ids.some(value => !hashPattern.test(value))) refuse("evidence_refused");
|
|
177
|
+
const record = JSON.parse(raw);
|
|
178
|
+
if (revocations.references.includes(reference) || revocations.ids.includes(record.id)) refuse("evidence_refused");
|
|
179
|
+
return record;
|
|
180
|
+
} catch { refuse("evidence_refused"); }
|
|
181
|
+
}
|
|
182
|
+
};
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
function fresh(record, now, maximumAge = 60000) {
|
|
186
|
+
if (!record || record.schema_version !== 1 || !Number.isSafeInteger(record.issued_at) || !Number.isSafeInteger(record.expires_at) ||
|
|
187
|
+
record.issued_at > now || now - record.issued_at > maximumAge || record.expires_at <= now || record.expires_at - record.issued_at > maximumAge || record.revoked !== false) refuse("evidence_refused");
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
function deploymentProof(authority, reference, now) {
|
|
191
|
+
const record = authority.load("deployment", reference);
|
|
192
|
+
fresh(record, now);
|
|
193
|
+
const required = ["daemon", "local_fallback", "accepted_bridge", "scripts_appleevents", "old_processes", "outstanding_effects"];
|
|
194
|
+
if (record.kind !== "deployment" || !codePattern.test(record.epoch) || !Array.isArray(record.accounts) || !record.accounts.length ||
|
|
195
|
+
record.accounts.some(account => !hashPattern.test(account)) || new Set(record.accounts).size !== record.accounts.length ||
|
|
196
|
+
!Array.isArray(record.operators) || !record.operators.length || record.operators.some(operator => !codePattern.test(operator)) ||
|
|
197
|
+
required.some(writer => record.excluded?.[writer] !== true) || record.nonparticipating_launch_disabled !== true || record.clock_uncertainty_ms !== 0) refuse("active_writer_refused");
|
|
198
|
+
return record;
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
function approvalProof(authority, reference, kind, target, deployment, now) {
|
|
202
|
+
const record = authority.load(kind === "retry" ? "authorization" : "approval", reference);
|
|
203
|
+
fresh(record, now);
|
|
204
|
+
if (record.kind !== kind || !sameBinding(record, target) || !codePattern.test(record.operator) ||
|
|
205
|
+
!deployment.operators.includes(record.operator) || record.epoch !== deployment.epoch || !hashPattern.test(record.id)) refuse("authorization_refused");
|
|
206
|
+
return record;
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
export function mailAttempts(directory, id) {
|
|
210
|
+
const names = fs.readdirSync(path.join(directory, id)).filter(name => name.endsWith(".json"));
|
|
211
|
+
if (names.some(name => !/^[1-9]\d*\.json$/.test(name) || !Number.isSafeInteger(Number(name.slice(0, -5))))) refuse("identity_refused");
|
|
212
|
+
return names.map(name => Number(name.slice(0, -5)));
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
function latestAttempt(directory, id) {
|
|
216
|
+
const names = mailAttempts(directory, id);
|
|
217
|
+
return names.length ? Math.max(...names) : 0;
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
export function reconciliationFencePath(directory) {
|
|
221
|
+
return path.join(directory, ".reconciliation-fence.json");
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
export function fencedMailWrite(run, { directory = path.join(getAppleToolsDir(), "mail-send-claims") } = {}) {
|
|
225
|
+
try {
|
|
226
|
+
return withMailWriterLock(directory, () => fs.existsSync(reconciliationFencePath(directory)) ? mailOutcome("active_writer_refused") : run());
|
|
227
|
+
} catch (error) { return mailOutcome(error.mailCode || "durability_refused"); }
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
export function mailSendReconcile(args, {
|
|
231
|
+
directory = path.join(getAppleToolsDir(), "mail-send-claims"), authority = protectedMailAuthority(), now = Date.now, io = fs
|
|
232
|
+
} = {}) {
|
|
233
|
+
try {
|
|
234
|
+
const allowed = [...bindingFields, "action", "idempotency_key", "deployment_ref", "approval_ref", "evidence_ref", "fence_id", "outcome", "reason_code", "dry_run", "confirm"];
|
|
235
|
+
if (!args || Object.keys(args).some(key => !allowed.includes(key)) || !["begin", "commit"].includes(args.action)) refuse("identity_refused");
|
|
236
|
+
validateBinding(args);
|
|
237
|
+
if ((args.dry_run !== undefined && typeof args.dry_run !== "boolean") || (args.confirm !== undefined && typeof args.confirm !== "boolean") ||
|
|
238
|
+
!hashPattern.test(args.deployment_ref) || !hashPattern.test(args.approval_ref)) refuse("identity_refused");
|
|
239
|
+
if (args.action === "begin" && ["outcome", "reason_code", "evidence_ref", "fence_id"].some(field => args[field] !== undefined)) refuse("identity_refused");
|
|
240
|
+
if (args.idempotency_key !== undefined && (typeof args.idempotency_key !== "string" || !args.idempotency_key.trim() || args.idempotency_key.length > 256 || mailClaimId(args.fingerprint, args.idempotency_key) !== args.claim_id)) refuse("identity_refused");
|
|
241
|
+
if (args.dry_run === true) return { ...mailOutcome("reconciliation_preview"), planned: true };
|
|
242
|
+
if (!fs.existsSync(directory)) refuse("identity_refused");
|
|
243
|
+
const initial = readMailClaim(directory, args.claim_id, args.attempt);
|
|
244
|
+
if (initial.legacy) refuse("legacy_ineligible");
|
|
245
|
+
const requestHash = digest(JSON.stringify(allowed.map(field => args[field] ?? null)));
|
|
246
|
+
if (initial.reconciliation?.request_hash === requestHash && latestAttempt(directory, args.claim_id) === args.attempt) {
|
|
247
|
+
return mailOutcome("reconciliation_replayed", { ok: true, historical: initial.state, receipt: initial.reconciliation.receipt });
|
|
248
|
+
}
|
|
249
|
+
return withMailWriterLock(directory, () => {
|
|
250
|
+
const claim = readMailClaim(directory, args.claim_id, args.attempt);
|
|
251
|
+
if (latestAttempt(directory, args.claim_id) !== args.attempt) refuse("revision_refused");
|
|
252
|
+
if (claim.fingerprint !== args.fingerprint) refuse("identity_refused");
|
|
253
|
+
if (claim.reconciliation?.request_hash === requestHash) return mailOutcome("reconciliation_replayed", { ok: true, historical: claim.state, receipt: claim.reconciliation.receipt });
|
|
254
|
+
if (claim.state !== "pending") refuse("outcome_conflict");
|
|
255
|
+
if (!sameBinding(args, claim)) refuse("revision_refused");
|
|
256
|
+
const observedNow = now();
|
|
257
|
+
const deployment = deploymentProof(authority, args.deployment_ref, observedNow);
|
|
258
|
+
const approval = approvalProof(authority, args.approval_ref, "reconcile", args, deployment, observedNow);
|
|
259
|
+
const fenceFile = reconciliationFencePath(directory);
|
|
260
|
+
if (args.action === "begin") {
|
|
261
|
+
if (fs.existsSync(fenceFile)) {
|
|
262
|
+
const previous = readJson(fenceFile);
|
|
263
|
+
if (!sameBinding(previous, args) || previous.approval_ref !== args.approval_ref || previous.deployment_ref !== args.deployment_ref) refuse("active_writer_refused");
|
|
264
|
+
return mailOutcome("evidence_required", { ok: true, fence_id: previous.fence_id, ...claimBinding(claim) });
|
|
265
|
+
}
|
|
266
|
+
const fence = { schema_version: 1, ...claimBinding(claim), fence_id: digest(randomUUID()), created_at: observedNow, approval_ref: args.approval_ref, deployment_ref: args.deployment_ref, epoch: deployment.epoch };
|
|
267
|
+
durableCreate(fenceFile, fence, io);
|
|
268
|
+
return mailOutcome("evidence_required", { ok: true, fence_id: fence.fence_id, ...claimBinding(claim) });
|
|
269
|
+
}
|
|
270
|
+
const fence = readJson(fenceFile);
|
|
271
|
+
if (!sameBinding(fence, args) || !hashPattern.test(args.fence_id) || fence.fence_id !== args.fence_id || fence.epoch !== deployment.epoch ||
|
|
272
|
+
fence.approval_ref !== args.approval_ref || fence.deployment_ref !== args.deployment_ref) refuse("active_writer_refused");
|
|
273
|
+
if (!["sent", "not_sent"].includes(args.outcome) || !reasonCodes.has(args.reason_code) || args.reason_code !== `operator_verified_${args.outcome}`) refuse("evidence_refused");
|
|
274
|
+
const evidence = authority.load("evidence", args.evidence_ref);
|
|
275
|
+
fresh(evidence, observedNow);
|
|
276
|
+
if (evidence.kind !== "mail_verification" || !hashPattern.test(evidence.id) || !sameBinding(evidence, args) || evidence.fence_id !== fence.fence_id ||
|
|
277
|
+
evidence.epoch !== deployment.epoch || evidence.operator !== approval.operator || evidence.source !== "complete_exact_mail_snapshot_v1" ||
|
|
278
|
+
evidence.clock_uncertainty_ms !== 0 || evidence.outcome !== args.outcome || evidence.reason_code !== args.reason_code || evidence.effects_drained !== true) refuse("evidence_refused");
|
|
279
|
+
for (const mailbox of ["sent", "outbox"]) {
|
|
280
|
+
const observation = evidence[mailbox];
|
|
281
|
+
if (!observation || observation.completed !== true || observation.error !== null || observation.index_used !== false ||
|
|
282
|
+
!Number.isSafeInteger(observation.observed_at) || observation.observed_at <= fence.created_at || observation.observed_at > observedNow ||
|
|
283
|
+
observedNow - observation.observed_at > 60000 || evidence.issued_at < observation.observed_at || !Number.isSafeInteger(observation.search_from) || observation.search_from > claim.createdAt ||
|
|
284
|
+
observation.search_to !== observation.observed_at || observation.exact_fingerprint !== claim.fingerprint ||
|
|
285
|
+
!Array.isArray(observation.accounts) || JSON.stringify([...observation.accounts].sort()) !== JSON.stringify([...deployment.accounts].sort()) ||
|
|
286
|
+
!Array.isArray(observation.matches)) refuse("evidence_refused");
|
|
287
|
+
}
|
|
288
|
+
if (evidence.outbox.matches.length !== 0 || (args.outcome === "not_sent" ? evidence.sent.matches.length !== 0 : evidence.sent.matches.length !== 1)) refuse("evidence_refused");
|
|
289
|
+
let messageRef;
|
|
290
|
+
if (args.outcome === "sent") {
|
|
291
|
+
const match = evidence.sent.matches[0];
|
|
292
|
+
if (!match || !hashPattern.test(match.message_ref) || !hashPattern.test(match.message_id_hash) || !deployment.accounts.includes(match.account) ||
|
|
293
|
+
match.fingerprint !== claim.fingerprint || match.message_id_hash !== evidence.message_id_hash) refuse("evidence_refused");
|
|
294
|
+
messageRef = match.message_ref;
|
|
295
|
+
}
|
|
296
|
+
deploymentProof(authority, args.deployment_ref, now());
|
|
297
|
+
approvalProof(authority, args.approval_ref, "reconcile", args, deployment, now());
|
|
298
|
+
const revalidated = authority.load("evidence", args.evidence_ref);
|
|
299
|
+
fresh(revalidated, now());
|
|
300
|
+
if (JSON.stringify(revalidated) !== JSON.stringify(evidence)) refuse("evidence_refused");
|
|
301
|
+
const receipt = digest(JSON.stringify([requestHash, claim.record_hash]));
|
|
302
|
+
appendMailOutcome(directory, claim, {
|
|
303
|
+
state: args.outcome === "sent" ? "done" : "not_sent", committed_at: observedNow,
|
|
304
|
+
reconciliation: { request_hash: requestHash, receipt, evidence_ref: args.evidence_ref, approval_ref: args.approval_ref, reason_code: args.reason_code, operator: approval.operator, ...(messageRef ? { message_ref: messageRef } : {}) }
|
|
305
|
+
}, io);
|
|
306
|
+
io.unlinkSync(fenceFile);
|
|
307
|
+
syncDirectory(directory, io);
|
|
308
|
+
return mailOutcome("reconciled", { ok: true, historical: args.outcome, receipt });
|
|
309
|
+
});
|
|
310
|
+
} catch (error) {
|
|
311
|
+
return mailOutcome(error.mailCode || "durability_refused");
|
|
312
|
+
}
|
|
313
|
+
}
|
|
314
|
+
|
|
315
|
+
export function validateRetryAuthorization(authority, reference, deploymentRef, claim, now) {
|
|
316
|
+
try {
|
|
317
|
+
const deployment = deploymentProof(authority, deploymentRef, now);
|
|
318
|
+
const approval = approvalProof(authority, reference, "retry", claim, deployment, now);
|
|
319
|
+
if (claim.state !== "not_sent" || claim.authorization_id !== undefined || approval.single_use !== true) refuse("authorization_refused");
|
|
320
|
+
return approval.id;
|
|
321
|
+
} catch { refuse("authorization_refused"); }
|
|
322
|
+
}
|
|
323
|
+
|
|
324
|
+
export function assertUnspentRetryLineage(directory, claim) {
|
|
325
|
+
const consumed = path.join(directory, ".authorizations");
|
|
326
|
+
if (!fs.existsSync(consumed)) return;
|
|
327
|
+
const stat = fs.lstatSync(consumed);
|
|
328
|
+
if (!stat.isDirectory() || stat.isSymbolicLink()) refuse("durability_refused");
|
|
329
|
+
for (const name of fs.readdirSync(consumed)) {
|
|
330
|
+
if (!/^[a-f0-9]{64}\.json$/.test(name)) refuse("durability_refused");
|
|
331
|
+
const record = readJson(path.join(consumed, name));
|
|
332
|
+
const { integrity_hash: integrityHash, ...payload } = record;
|
|
333
|
+
if (integrityHash !== mailRecordHash(payload)) refuse("durability_refused");
|
|
334
|
+
validateBinding(record);
|
|
335
|
+
if (record.schema_version !== 1 || record.authorization_id !== name.slice(0, -5) ||
|
|
336
|
+
!hashPattern.test(record.authorization_ref) ||
|
|
337
|
+
!Number.isSafeInteger(record.retry_attempt) || record.retry_attempt !== record.attempt + 1 ||
|
|
338
|
+
!Number.isSafeInteger(record.consumed_at) || record.consumed_at < 0) refuse("durability_refused");
|
|
339
|
+
if (record.claim_id === claim.claim_id) refuse("authorization_refused");
|
|
340
|
+
}
|
|
341
|
+
}
|
package/lib/noDashes.js
ADDED
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* No dashes in anything sent or drafted as the account owner.
|
|
3
|
+
*
|
|
4
|
+
* Mail and messages written for a person read as machine-written when they
|
|
5
|
+
* carry dashes used as punctuation, so every mail and Messages write rewrites
|
|
6
|
+
* them before anything reaches Mail or Messages:
|
|
7
|
+
* - an em dash, en dash or similar dash character becomes a comma (or nothing
|
|
8
|
+
* at the start or end of a line, and "to" between two numbers);
|
|
9
|
+
* - a hyphen (or two or three) with a space on each side becomes a comma.
|
|
10
|
+
* Hyphens inside names, identifiers, paths, URLs and dates are not punctuation
|
|
11
|
+
* and stay: Alexa-Echo-MCP, v1.1.0, 2026-11-10. A hyphen at the start of a line
|
|
12
|
+
* (a list bullet, or the "-- " signature line) also stays.
|
|
13
|
+
*
|
|
14
|
+
* Linear-time patterns only: these run on tool input.
|
|
15
|
+
*/
|
|
16
|
+
|
|
17
|
+
const DASH_CHARS = "‒–—―⸺⸻︱︲﹘";
|
|
18
|
+
const DASH_RUN = new RegExp(`[ \\t]*[${DASH_CHARS}]+[ \\t]*`, "g");
|
|
19
|
+
const NUMBER_RANGE = /(\d)[‒–—](?=\d)/g;
|
|
20
|
+
const SPACED_HYPHEN = /(\S)[ \t]+(?:-{1,3}|[‐‑−])[ \t]+(?=\S)/g;
|
|
21
|
+
const TRAILING_HYPHEN = /(\S)[ \t]+(?:-{1,3}|[‐‑−])[ \t]*$/;
|
|
22
|
+
const HTML_DASH_ENTITY = /&(?:mdash|ndash|horbar);|&#(?:8210|8211|8212|8213|x201[2345]);/gi;
|
|
23
|
+
|
|
24
|
+
function rewriteLine(line) {
|
|
25
|
+
let count = 0;
|
|
26
|
+
let text = line.replace(NUMBER_RANGE, (_, digit) => {
|
|
27
|
+
count += 1;
|
|
28
|
+
return `${digit} to `;
|
|
29
|
+
});
|
|
30
|
+
text = text.replace(DASH_RUN, (match, offset, whole) => {
|
|
31
|
+
count += 1;
|
|
32
|
+
if (!whole.slice(0, offset).trim()) return match.match(/^[ \t]*/)[0];
|
|
33
|
+
if (!whole.slice(offset + match.length).trim()) return "";
|
|
34
|
+
return ", ";
|
|
35
|
+
});
|
|
36
|
+
text = text.replace(SPACED_HYPHEN, (_, before) => {
|
|
37
|
+
count += 1;
|
|
38
|
+
return `${before}, `;
|
|
39
|
+
});
|
|
40
|
+
text = text.replace(TRAILING_HYPHEN, (_, before) => {
|
|
41
|
+
count += 1;
|
|
42
|
+
return before;
|
|
43
|
+
});
|
|
44
|
+
if (count > 0) {
|
|
45
|
+
text = text.replace(/,[ \t]*,/g, ",").replace(/,[ \t]*([.;:!?)\]])/g, "$1").replace(/([(\[])[ \t]*,[ \t]*/g, "$1");
|
|
46
|
+
}
|
|
47
|
+
return { text, count };
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/**
|
|
51
|
+
* @param {string} value
|
|
52
|
+
* @param {{ html?: boolean }} [opts] - html: also rewrite — style entities
|
|
53
|
+
* @returns {{ text: string, count: number }}
|
|
54
|
+
*/
|
|
55
|
+
export function rewriteDashes(value, { html = false } = {}) {
|
|
56
|
+
if (typeof value !== "string" || value === "") return { text: value ?? "", count: 0 };
|
|
57
|
+
const source = html ? value.replace(HTML_DASH_ENTITY, "—") : value;
|
|
58
|
+
let count = 0;
|
|
59
|
+
const lines = source.split("\n").map((line) => {
|
|
60
|
+
const out = rewriteLine(line);
|
|
61
|
+
count += out.count;
|
|
62
|
+
return out.text;
|
|
63
|
+
});
|
|
64
|
+
return count > 0 ? { text: lines.join("\n"), count } : { text: value, count: 0 };
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/**
|
|
68
|
+
* The lines that would change, for callers that refuse instead of rewriting.
|
|
69
|
+
* @returns {string[]}
|
|
70
|
+
*/
|
|
71
|
+
export function findDashes(value, opts = {}) {
|
|
72
|
+
if (typeof value !== "string" || value === "") return [];
|
|
73
|
+
const source = opts.html ? value.replace(HTML_DASH_ENTITY, "—") : value;
|
|
74
|
+
return source.split("\n").filter((line) => rewriteLine(line).count > 0);
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
// Text fields of each write that goes out under the owner's name.
|
|
78
|
+
export const DASH_FIELDS = {
|
|
79
|
+
mail_send: ["subject", "body"],
|
|
80
|
+
mail_draft: ["subject", "body"],
|
|
81
|
+
mail_reply: ["body"],
|
|
82
|
+
mail_forward: ["body"],
|
|
83
|
+
messages_send: ["text"]
|
|
84
|
+
};
|
|
85
|
+
|
|
86
|
+
/**
|
|
87
|
+
* @param {string} tool
|
|
88
|
+
* @param {object} args
|
|
89
|
+
* @returns {{ args: object, count: number }}
|
|
90
|
+
*/
|
|
91
|
+
export function withoutDashes(tool, args) {
|
|
92
|
+
const fields = DASH_FIELDS[tool];
|
|
93
|
+
if (!fields || !args || typeof args !== "object") return { args, count: 0 };
|
|
94
|
+
const html = String(args.body_format || "").toLowerCase() === "html";
|
|
95
|
+
const out = { ...args };
|
|
96
|
+
let count = 0;
|
|
97
|
+
for (const field of fields) {
|
|
98
|
+
if (typeof out[field] !== "string") continue;
|
|
99
|
+
const rewritten = rewriteDashes(out[field], { html: html && field === "body" });
|
|
100
|
+
out[field] = rewritten.text;
|
|
101
|
+
count += rewritten.count;
|
|
102
|
+
}
|
|
103
|
+
return { args: count > 0 ? out : args, count };
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
export function dashNote(count) {
|
|
107
|
+
return ` Rewrote ${count} ${count === 1 ? "dash" : "dashes"} (em dash, en dash or spaced hyphen) as commas or words before writing; nothing goes out with dashes.`;
|
|
108
|
+
}
|
package/lib/writeTools.js
CHANGED
|
@@ -34,6 +34,8 @@ import { planWriteRoute, planAfterDelegation, tccFallbackAdvice } from "./writeR
|
|
|
34
34
|
import { requestWriteViaBridge, probeSocket, defaultSocketPath } from "./writeBridge.js";
|
|
35
35
|
import { needsHostTccAdvice } from "./appleScript.js";
|
|
36
36
|
import { idempotentMailSend } from "./mailIdempotency.js";
|
|
37
|
+
import { mailSendReconcile, mailOutcome, fencedMailWrite } from "./mailReconciliation.js";
|
|
38
|
+
import { withoutDashes, dashNote } from "./noDashes.js";
|
|
37
39
|
|
|
38
40
|
const CONFIRM_PROPS = {
|
|
39
41
|
dry_run: { type: "boolean", description: "Preview only: report what would happen and change nothing (default false)" },
|
|
@@ -49,7 +51,7 @@ export const WRITE_TOOL_DEFINITIONS = [
|
|
|
49
51
|
// ============ MAIL WRITES ============
|
|
50
52
|
{
|
|
51
53
|
name: "mail_send",
|
|
52
|
-
description: "Send an email through Mail.app. Success
|
|
54
|
+
description: "Send an email through Mail.app. Success requires Sent/Outbox verification, not merely an AppleScript return. Multiple recipients require confirm=true. Durable claims never expire uncertainty or automatically retry; changing/removing a key cannot bypass pending or terminal not_sent lineage. Read structuredContent.mail_send: suppression/replay is not a new delivery and cannot advance a page ledger. Legacy pending claims cannot be reconciled. A later retry after terminal not_sent needs separate protected single-use authorization, not confirm or a new key. Dashes used as punctuation (em dash, en dash, a spaced hyphen) are rewritten as commas or words before anything is written; hyphens inside names and identifiers stay.",
|
|
53
55
|
inputSchema: {
|
|
54
56
|
type: "object",
|
|
55
57
|
properties: {
|
|
@@ -58,16 +60,42 @@ export const WRITE_TOOL_DEFINITIONS = [
|
|
|
58
60
|
bcc: { type: "array", items: { type: "string" }, description: "BCC email addresses" },
|
|
59
61
|
subject: { type: "string", description: "Subject line (required)" },
|
|
60
62
|
body: { type: "string", description: "Message body (required)" },
|
|
61
|
-
idempotency_key: { type: "string", description: "Stable
|
|
63
|
+
idempotency_key: { type: "string", description: "Stable delivery key. A new key may name a genuinely new delivery only after an accepted or proven-unstarted outcome; changing/removing a key cannot bypass pending or terminal not_sent lineage." },
|
|
64
|
+
retry_authorization_ref: { type: "string", description: "Protected, separately issued single-use retry approval reference. Not issued by reconciliation; unavailable without the reviewed deployment authority." },
|
|
65
|
+
deployment_ref: { type: "string", description: "Protected complete-writer-exclusion deployment proof reference for an explicitly authorized retry." },
|
|
62
66
|
body_format: { type: "string", enum: ["plain", "html"], description: "Plain text (default) or HTML. HTML is tag-stripped; the body is pasted into Mail's compose window (System Events focus on the message body, then Cmd-A and clipboard paste). AppleScript content/html content is not set because it quote-wraps the Sent body" },
|
|
63
67
|
...CONFIRM_PROPS
|
|
64
68
|
},
|
|
65
69
|
required: ["to", "subject", "body"]
|
|
66
70
|
}
|
|
67
71
|
},
|
|
72
|
+
{
|
|
73
|
+
name: "mail_send_reconcile",
|
|
74
|
+
description: "No-send claim adjudication. Legacy claims are always ineligible. begin establishes a persistent global writer fence before fresh evidence is collected; commit requires protected administrator-provisioned approval, complete Sent AND Outbox evidence, and exclusion of all old/queued/script writers. Missing authority refuses. Neither action sends, retries, wakes Mail, changes the page ledger, or issues retry permission.",
|
|
75
|
+
inputSchema: {
|
|
76
|
+
type: "object", additionalProperties: false,
|
|
77
|
+
properties: {
|
|
78
|
+
action: { type: "string", enum: ["begin", "commit"] },
|
|
79
|
+
claim_id: { type: "string", pattern: "^[a-f0-9]{64}$" },
|
|
80
|
+
attempt: { type: "integer", minimum: 1 },
|
|
81
|
+
revision: { type: "integer", minimum: 1 },
|
|
82
|
+
fingerprint_algorithm: { type: "string", enum: ["sha256-mail-content-v1"] },
|
|
83
|
+
fingerprint: { type: "string", pattern: "^[a-f0-9]{64}$" },
|
|
84
|
+
idempotency_key: { type: "string" },
|
|
85
|
+
deployment_ref: { type: "string", pattern: "^[a-f0-9]{64}$" },
|
|
86
|
+
approval_ref: { type: "string", pattern: "^[a-f0-9]{64}$" },
|
|
87
|
+
evidence_ref: { type: "string", pattern: "^[a-f0-9]{64}$" },
|
|
88
|
+
fence_id: { type: "string", pattern: "^[a-f0-9]{64}$" },
|
|
89
|
+
outcome: { type: "string", enum: ["sent", "not_sent"] },
|
|
90
|
+
reason_code: { type: "string", enum: ["operator_verified_sent", "operator_verified_not_sent"] },
|
|
91
|
+
...CONFIRM_PROPS
|
|
92
|
+
},
|
|
93
|
+
required: ["action", "claim_id", "attempt", "revision", "fingerprint_algorithm", "fingerprint", "deployment_ref", "approval_ref"]
|
|
94
|
+
}
|
|
95
|
+
},
|
|
68
96
|
{
|
|
69
97
|
name: "mail_draft",
|
|
70
|
-
description: "Save an email to Drafts without sending it. Drafts are never delivered, so no recipient confirmation is required.",
|
|
98
|
+
description: "Save an email to Drafts without sending it. Drafts are never delivered, so no recipient confirmation is required. Dashes used as punctuation (em dash, en dash, a spaced hyphen) are rewritten as commas or words before anything is written; hyphens inside names and identifiers stay.",
|
|
71
99
|
inputSchema: {
|
|
72
100
|
type: "object",
|
|
73
101
|
properties: {
|
|
@@ -84,7 +112,7 @@ export const WRITE_TOOL_DEFINITIONS = [
|
|
|
84
112
|
},
|
|
85
113
|
{
|
|
86
114
|
name: "mail_reply",
|
|
87
|
-
description: "Reply to an existing email. The reply text is pasted above the quoted original in a visible Mail window (System Events focus on the message body, then Command-Up and clipboard paste — not Cmd-A, which would replace the quote; AppleScript content is not set because Mail 16 leaves it empty). reply_all=true fans out to every original recipient and requires confirm=true. A real send is verified in Sent/Outbox before success. A send hang is a timeout, not TCC, unless Mail reports -1743/-10004; hang recover uses In-Reply-To. Clients must Sent-check before retrying a timed-out send.",
|
|
115
|
+
description: "Reply to an existing email. The reply text is pasted above the quoted original in a visible Mail window (System Events focus on the message body, then Command-Up and clipboard paste — not Cmd-A, which would replace the quote; AppleScript content is not set because Mail 16 leaves it empty). reply_all=true fans out to every original recipient and requires confirm=true. A real send is verified in Sent/Outbox before success. A send hang is a timeout, not TCC, unless Mail reports -1743/-10004; hang recover uses In-Reply-To. Clients must Sent-check before retrying a timed-out send. Dashes used as punctuation (em dash, en dash, a spaced hyphen) are rewritten as commas or words before anything is written; hyphens inside names and identifiers stay.",
|
|
88
116
|
inputSchema: {
|
|
89
117
|
type: "object",
|
|
90
118
|
properties: {
|
|
@@ -99,7 +127,7 @@ export const WRITE_TOOL_DEFINITIONS = [
|
|
|
99
127
|
},
|
|
100
128
|
{
|
|
101
129
|
name: "mail_forward",
|
|
102
|
-
description: "Forward an existing email to new recipients. An optional note is pasted above the forwarded original in a visible Mail window (same System Events prepend as mail_reply; AppleScript content is not set). More than one recipient requires confirm=true. A real send is verified in Sent/Outbox before success. A send hang is a timeout, not TCC, unless Mail reports -1743/-10004; hang recover matches intended To plus Fwd: subject or original Message-ID. Clients must Sent-check before retrying a timed-out send.",
|
|
130
|
+
description: "Forward an existing email to new recipients. An optional note is pasted above the forwarded original in a visible Mail window (same System Events prepend as mail_reply; AppleScript content is not set). More than one recipient requires confirm=true. A real send is verified in Sent/Outbox before success. A send hang is a timeout, not TCC, unless Mail reports -1743/-10004; hang recover matches intended To plus Fwd: subject or original Message-ID. Clients must Sent-check before retrying a timed-out send. Dashes used as punctuation (em dash, en dash, a spaced hyphen) are rewritten as commas or words before anything is written; hyphens inside names and identifiers stay.",
|
|
103
131
|
inputSchema: {
|
|
104
132
|
type: "object",
|
|
105
133
|
properties: {
|
|
@@ -154,7 +182,7 @@ export const WRITE_TOOL_DEFINITIONS = [
|
|
|
154
182
|
// ============ MESSAGES WRITES ============
|
|
155
183
|
{
|
|
156
184
|
name: "messages_send",
|
|
157
|
-
description: "Send an iMessage or SMS. Address it with 'to' (E.164 phone numbers like +15551234567, or Apple ID emails) or with 'chat_id' (a chat GUID from chat.db, e.g. 'iMessage;-;+15551234567' or 'iMessage;+;chat123456'). Group chats and multiple recipients require confirm=true.",
|
|
185
|
+
description: "Send an iMessage or SMS. Address it with 'to' (E.164 phone numbers like +15551234567, or Apple ID emails) or with 'chat_id' (a chat GUID from chat.db, e.g. 'iMessage;-;+15551234567' or 'iMessage;+;chat123456'). Group chats and multiple recipients require confirm=true. Dashes used as punctuation (em dash, en dash, a spaced hyphen) are rewritten as commas or words before anything is written; hyphens inside names and identifiers stay.",
|
|
158
186
|
inputSchema: {
|
|
159
187
|
type: "object",
|
|
160
188
|
properties: {
|
|
@@ -315,6 +343,7 @@ export const WRITE_TOOL_DEFINITIONS = [
|
|
|
315
343
|
];
|
|
316
344
|
|
|
317
345
|
export const WRITE_TOOL_HANDLERS = {
|
|
346
|
+
mail_send_reconcile: mailSendReconcile,
|
|
318
347
|
mail_send: (args) => mailCompose(args, { draft: false }),
|
|
319
348
|
mail_draft: (args) => mailCompose(args, { draft: true }),
|
|
320
349
|
mail_reply: mailReply,
|
|
@@ -359,7 +388,8 @@ export function mcpWriteResult(writeResult) {
|
|
|
359
388
|
const failed = !writeResult || writeResult.ok === false;
|
|
360
389
|
return {
|
|
361
390
|
content: [{ type: "text", text: message }],
|
|
362
|
-
...(
|
|
391
|
+
...(writeResult?.mail_send ? { structuredContent: { mail_send: writeResult.mail_send } } : {}),
|
|
392
|
+
...((failed || planned || writeResult?.mail_send?.code === "accepted_replay") ? { isError: true } : {})
|
|
363
393
|
};
|
|
364
394
|
}
|
|
365
395
|
|
|
@@ -373,9 +403,18 @@ export function executeWriteToolLocally(name, args = {}) {
|
|
|
373
403
|
return { ok: false, message: `Unknown write tool: ${name}`, unsupported: true };
|
|
374
404
|
}
|
|
375
405
|
try {
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
406
|
+
// Every send and draft path (stdio, HTTP, the indexer's write bridge) ends here, so the
|
|
407
|
+
// dash rewrite runs once before claims, Sent checks and Mail or Messages see the text.
|
|
408
|
+
const { args: clean, count } = withoutDashes(name, args || {});
|
|
409
|
+
const run = () => {
|
|
410
|
+
if (name === "mail_send") return idempotentMailSend(clean, () => handler(clean));
|
|
411
|
+
if (name.startsWith("mail_") && name !== "mail_send_reconcile") return fencedMailWrite(() => handler(clean));
|
|
412
|
+
return handler(clean);
|
|
413
|
+
};
|
|
414
|
+
const result = run();
|
|
415
|
+
return count > 0 && result && typeof result.message === "string"
|
|
416
|
+
? { ...result, message: result.message + dashNote(count) }
|
|
417
|
+
: result;
|
|
379
418
|
} catch (e) {
|
|
380
419
|
return { ok: false, message: `${name} failed: ${e.message}` };
|
|
381
420
|
}
|
|
@@ -428,7 +467,8 @@ export function loggedBridgeHandler(run, log, now = () => Date.now()) {
|
|
|
428
467
|
const planned = !ok && Boolean(result && result.planned);
|
|
429
468
|
// Mail accepted the send but Sent/Outbox didn't show it within budget — not a failure.
|
|
430
469
|
const unconfirmed = !ok && !planned && Boolean(result && result.unconfirmed);
|
|
431
|
-
const
|
|
470
|
+
const mailCode = result?.mail_send?.code;
|
|
471
|
+
const outcome = mailCode ? mailCode : ok ? "ok" : planned ? "planned (dry run / needs confirm)" : unconfirmed ? "unconfirmed (transport status unknown)" : "failed";
|
|
432
472
|
const why = ok || planned || unconfirmed ? "" : ` (${classifyWriteFailure(result && result.message)}${result && result.unsupported ? ", unsupported" : ""})`;
|
|
433
473
|
log(`${new Date(started).toISOString()} write bridge: ${tool} ${outcome} in ${now() - started}ms${why}`);
|
|
434
474
|
return result;
|
|
@@ -461,12 +501,12 @@ export async function dispatchWriteTool(name, args = {}, deps = {}) {
|
|
|
461
501
|
const { delivered, response, error, mayHaveStarted } = await request({ socketPath, tool: name, args });
|
|
462
502
|
// A lost response is not evidence of a failed send. Preserve the daemon's
|
|
463
503
|
// ownership after any handoff that could have reached it.
|
|
464
|
-
if ((name === "mail_send" || name === "mail_reply" || name === "mail_forward" || name === "messages_send") &&
|
|
504
|
+
if ((name === "mail_send" || name === "mail_send_reconcile" || name === "mail_reply" || name === "mail_forward" || name === "messages_send") &&
|
|
465
505
|
((!delivered && mayHaveStarted !== false) ||
|
|
466
506
|
(delivered && (!response || typeof response !== "object" ||
|
|
467
|
-
(response.unsupported && response.sendStarted !== false))))) {
|
|
507
|
+
(response.unsupported && (name === "mail_send_reconcile" || response.sendStarted !== false)))))) {
|
|
468
508
|
log(`Write bridge outcome unknown for ${name}; local fallback suppressed.`);
|
|
469
|
-
return { ok: false, unconfirmed: true, sendStarted:
|
|
509
|
+
return { ...(name.startsWith("mail_send") ? mailOutcome("bridge_uncertain", { entry: name === "mail_send_reconcile" ? "none" : "unknown" }) : {}), ok: false, unconfirmed: true, sendStarted: name === "mail_send_reconcile" ? false : undefined,
|
|
470
510
|
message: `${name}: unconfirmed. The daemon may still complete the write. Check Sent/Outbox or the destination before retrying; no local resend was started.` };
|
|
471
511
|
}
|
|
472
512
|
const { fallbackLocal } = planAfterDelegation({ delivered, response });
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "apple-tools-mcp",
|
|
3
|
-
"version": "3.3.
|
|
3
|
+
"version": "3.3.2",
|
|
4
4
|
"description": "MCP server for semantic search and write actions across Apple Mail, Messages, Calendar, and Contacts. Speaks stdio (local) or bearer-token-authenticated Streamable HTTP (LAN / Tailscale).",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "index.js",
|
|
@@ -52,6 +52,7 @@
|
|
|
52
52
|
"lib/",
|
|
53
53
|
"bin/",
|
|
54
54
|
"examples/",
|
|
55
|
+
"docs/mail-send-reconciliation.md",
|
|
55
56
|
"scripts/audit-index.js",
|
|
56
57
|
"scripts/smoke-writes.js",
|
|
57
58
|
"scripts/postinstall.js",
|