Direct document-AI actions (/direct/v1)
The /direct/v1 surface lets a browser-based Office add-in run document-AI actions through a Myra
gateway. Three add-ins consume it: the Office.js Outlook task pane (over the open
message), the Office.js Excel task pane (over the selected cell range) and the Office.js
Word task pane (over the selection/document, inserting as tracked changes). It is the
direct-adapter sibling of the Microsoft 365 Copilot lane (/copilot/v1):
the action shaping, server-pinned prompts, model pinning, CONTENT pipeline, PII/redact behaviour,
billing, and one-request_log-row semantics are identical — read that page for the request/response
shape and per-action params. This page documents only what differs.
What differs from /copilot/v1
/copilot/v1 (Copilot) |
/direct/v1 (Office add-in) |
|
|---|---|---|
| Caller | Microsoft's servers (server-to-server) | the user's browser (Office task pane) |
| CORS | none (server-side call) | enabled for the SPA origin (a deployment setting) |
| Entra app | the Copilot app (copilot_entra_*) |
the add-in's own app (direct_entra_*) |
generate action |
rejected 400 (never widens) |
available (direct-only) — a generic generative verb |
ground action |
permanently excluded (Art.44) | reserved direct-only (not yet built) |
Everything else is shared code (one ENTRA_ACCESS_PIPELINE, one entra_auth middleware, one action
shaper); the lane is selected by a server-set tag, never by the request.
Authentication
Send a Microsoft Entra OAuth2 access token minted by Office SSO
(OfficeRuntime.auth.getAccessToken) as a bearer:
The header must be exactly that shape: the scheme Bearer (case-insensitive), one space, then the
token (no whitespace or control characters; at most 16 KB in the parser — in practice the HTTP front
end limits a header line to 8 KB and answers longer ones with 400). A missing prefix, another scheme,
extra or different whitespace, or a repeated Authorization header is rejected 401 before the token
is validated.
It is validated exactly as the Copilot token (signature against the tenant JWKS, issuer pin,
aud/azp allowlist, mandatory exp, a delegated-token scp gate) — but against the
direct_entra_* settings, which describe the add-in's own Entra app registration, not the
Copilot app. Key consequences:
- The token's
audis the add-in's App ID URI (api://<host>/{add-in-client-id}). This value must be listed indirect_entra_aud_allowand must not overlapcopilot_entra_aud_allow— the disjointaudis the fence that keeps a Copilot server-to-server token off this browser lane (the write API rejects an overlapping value400). If the two lists overlap anyway (for example after a direct database edit), a token whoseaudis valid on both lanes is refused401at request time and the gateway logs an error. - The token's
azp/appidis a Microsoft Office host client id (host/platform-dependent), not the add-in's app id — list the relevant host id(s) indirect_entra_azp_allow.azpvalues may overlap the Copilot lane (they are Microsoft's), so no overlap check is applied to them. - When
direct_entra_scope_requiredis set, the token's space-separatedscpmust contain that exact value, else403("This token lacks the required document-AI scope"). Unset, only the presence ofscpis checked.
The Myra tenant (tid) and user (oid) resolution and the document-AI entitlement gate are
identical to the Copilot lane. Unset direct_entra_aud_allow/direct_entra_azp_allow → the lane is
dormant (every token 401) — the feature ships dark.
Reading the gateway row: a retryable database fault (no free connection, a lock wait timeout, a deadlock) answers 503 service_unavailable with Retry-After: 1; any other fault answers 503 without Retry-After. Resolving the gateway configuration: a retryable internal fault answers 503 service_unavailable with Retry-After: 1; anything else keeps the 403 "not fully configured" answer. The request is never admitted on a failed read.
CORS
/direct/v1 is CORS-enabled for the single configured SPA origin (set by your operator, e.g.
https://ai.myra.eu — the task panes are hosted there under /outlook/ and /excel/):
OPTIONSpreflight →204withAccess-Control-Allow-Methods: GET, POST, OPTIONSandAccess-Control-Allow-Headers: Authorization, Content-TypeandAccess-Control-Max-Age: 86400(GETis for the model-catalog endpoint below; actions arePOST).- The
POST/error response carriesAccess-Control-Allow-Originon every status (so the pane can read the body of a401/403/413/429, not an opaque CORS error — including the gateway's own413 payload_too_largefor a request body over 1 MB, which carriesmax_body: 1048576; see Request body size limits) andAccess-Control-Expose-Headers: X-Request-Id, Retry-After, X-AIG-PII-Active, X-AIG-Model, X-AIG-Doc-AI-Action. - No
Access-Control-Allow-Credentials— auth is a Bearer token, never a cookie.
Endpoints, request/response, and errors
Identical to /copilot/v1 with the path prefix /direct/v1:
POST /direct/v1/summarize
POST /direct/v1/rewrite
POST /direct/v1/translate
POST /direct/v1/redact
POST /direct/v1/generate # direct-only
GET /direct/v1/models # the offerable model catalog for the add-in picker
Request body, per-action params, the 200 chat-completions shape, redact fail-closed behaviour,
and the error table are the same. Lane-specific notes:
- A URL whose prefix does not match the authenticated lane (e.g.
/copilot/v1/...presented with an add-in token, or vice versa) is rejected400 invalid_request— the action is resolved from the lane, not trusted from the URL. generate(direct-only). A generic generative action: "using the suppliedtextas context, produce exactly whatparams.instructionasks for; return ONLY that." The Excel add-in uses it for its formula / clean / build-a-table actions (the fixedrewriteprompt — "improve clarity, preserve meaning" — is a poor base for those).params.instructionis required (400if absent — a generate with no instruction is meaningless) and is sanitised into one bounded slot exactly likerewrite's. It is rejected400on/copilot/v1(identical to an unknown action — the copilot lane never widens); it resolves only on the direct lane.groundis not a valid action on either lane yet (400); when built it will be direct-only.- Error body the add-ins read. On a non-2xx answer the Outlook, Word and Excel add-ins and the OX mail plugin read only
{"error":{"code":"…"}}and map acodeof the form^[a-z0-9_]{1,48}$that is in a closed table (quota_exceeded,wallet_insufficient,user_budget_exceeded,team_budget_exceeded,trial_expired,trial_budget_exhausted,subscription_inactive,plan_model_not_allowed,wallet_funds_reserved,spend_unverified) to a fixed message. Themessagetext is never displayed. A body that is absent, not JSON, not an object, or carries an unknown or malformedcodeis ignored, and the add-in maps the HTTP status instead, using the client's existing status mapping (for example429= rate limit,503= busy). A typedcodeis honoured on any non-2xx answer, as the web app does.
Per-call model selection (the sovereignty picker, direct-only)
By default every action runs on the gateway's server-pinned document_ai_model. The direct lane
additionally lets the add-in user pick a different model per call, validated server-side against
what the workspace is actually entitled to. The client is never the authz boundary (invariant 11): a
desired model is a request, not an instruction.
💡 Note: The picker offers every model the designated document-AI gateway is entitled to — the gateway's offerable catalog (residency ∩ provider-allowlist ∩ plan tier ∩ EU-Gov), the same set that can actually route. It does not itself impose a residency filter: the sovereignty guarantee comes from the gateway being an EU-hosted (Myra) gateway by configuration, so on such a gateway every offered model is EU-hosted. If an operator configures a document-AI gateway with non-EU commercial providers, those models are offered too — the picker reflects the gateway's actual entitlement, not a separate residency policy.
GET /direct/v1/models
Returns the offerable catalog the add-in picker populates from — the same set the override
validator (below) checks membership against, so offer equals route. Authenticated exactly like the
action POST (the same bearer token, the same entitlement gate); a GET is served by a dedicated
responder (not the inference pipeline).
default— the gateway's pinned model id (provider/model); always a member ofmodels.models— the offerable model ids (provider/model), each one the tenant may select. The list is the gateway's chat-model catalog gated by the same eligibility authority as routing (residency ∩ provider-allowlist ∩ plan tier ∩ EU-Gov), so a model that would not route is never offered. It is memoised per gateway for 60 s.- An absent/garbage response is treated by the add-in as no choice — the picker hides and the
action runs on the pinned default.
401(token absent/garbage) and403(workspace not provisioned) are the usual auth outcomes. If the catalog cannot be read, the answer is500(internal_error, "Model selection is temporarily unavailable").
The model body field on an action POST
An action body may carry an optional top-level model string (alongside text/params):
Accepted shape and handling (direct lane only — on /copilot/v1 the field is ignored, the
model stays server-pinned):
model value |
Outcome |
|---|---|
absent, JSON null, ""/blank, or exactly the pinned default |
the request runs on the server-pinned document_ai_model (and keeps its stored-config rescue) — identical to today |
a value in the offerable catalog (matched as provider/model or the bare model id, re-canonicalised to provider/model) |
the request runs on the chosen model; the pick is treated as explicit (a later entitlement denial returns a clean 403, never a silent swap to another model) |
| a value not in the catalog, or a non-string | 400 model_not_allowed |
Rejected, fail-closed (invariant 11): a wrong value is never degraded to the pinned-default
path — an unknown/not-allowed/malformed model is 400 model_not_allowed, so a client can never route
a model the workspace is not entitled to (which would bypass residency/cost controls on the
platform-managed fleet). ABSENT and MALFORMED take different paths: absent keeps the pin, malformed
is rejected.
Untrusted model output written into cells (Excel add-in)
The /direct/v1 responses are OpenAI chat-completions text — untrusted (a model response is
hostile until validated). The Excel add-in writes some of that text back into spreadsheet cells, which
is a spreadsheet formula / CSV-injection trust boundary handled client-side, in the add-in (the
server returns text; the add-in decides how to write it):
- Accepted / neutralised: a value written as data (the clean / build-a-table actions) that begins
with
=,+,-,@(or after leading whitespace/tab/CR/LF) is written as literal text — the add-in apostrophe-prefixes it AND forces the target cells to text (numberFormat = "@"), so Excel never evaluates it. Exception: a leading+/-on a pure numeric literal (e.g.-5,+3.14,-1.5e-3) is preserved as a computable number (Excel stores it as the number, not a formula) — only non-numeric trigger values are neutralised, so a cleaned negative column stays summable. Embedded tab/newline characters in a source cell are collapsed to a space so a hostile sheet cannot forge extra columns/rows in the prompt. - Rejected: a formula (the write-a-formula action, written live) that uses a network/exfil/DDE or
code-execution function (
WEBSERVICE,FILTERXML,ENCODEURL,RTD,IMAGE,HYPERLINK,CALL,REGISTER,EXEC,IMPORT*,PY,SQL.REQUEST, DDEcmd|…!) is not written and the user is told why — even though the user asked for a formula (a denylist; the residual risk of a novel function is mitigated by the mandatory preview-before-write).IMAGEis the worst exfil vector — it auto-fetches an arbitrary URL on write with no click;PY(Python in Excel) andSQL.REQUEST(ODBC) are the code-execution / data-connection vectors. Leading-trigger disguises (+WEBSERVICE,@WEBSERVICE,\t=WEBSERVICE,=+PY) are canonicalised before matching.
Nothing is ever written to the sheet automatically — every write shows a preview the user must confirm.
The Excel add-in also offers a read-only "Ask a question" action: it sends the user's
question as generate's params.instruction with the selected range (TSV) as context and renders the
answer in the task pane only (as textContent, never innerHTML). It has no write path, so it
adds no new cell-injection surface — the untrusted answer is display text.
The pane's tone / length / format quick-controls are composed client-side onto the
action's existing params slot by the shared office-addins/action-controls.ts helper — they never
introduce a new slot: generate/rewrite get the control phrases appended to instruction, and
summarize gets the length slot; translate/redact take none. The write-a-formula action is
deliberately exempt (controls would corrupt its "return ONLY a formula" instruction, so its instruction
stays authoritative and the controls are hidden for it).
Untrusted model output inserted into the document (Word add-in)
The Word add-in inserts /direct/v1 response text into the user's document — the same
untrusted model output boundary as Excel, handled client-side, in the add-in:
- Accepted: markdown headings, paragraphs and list items are parsed (client-side, pure
md.ts) into a flat list of inert text blocks and inserted via the Word API'sinsertText/insertParagraph+insertBreak(line break only) + a built-in heading style + paragraph alignment ONLY. - Single newline: a single newline inside a paragraph is a hard line break in the insert (an
address block or a signature keeps its lines), as on the chat screen. The rule is applied to a
whole group of lines up to the next blank line. If any line in the group has an HTML tag (a
<followed by a letter,/,!or?), a backtick,$$math, a square bracket](any link, image, reference or footnote), a list marker inside a quote (> - a), or a line that starts with<but is not a tag (<3), the newlines in that whole group are spaces, even after a heading or list line inside the group. The insert never breaks visible text where the screen does not; text the screen hides (a setext underline, a hidden reference definition) stays typed and may sit on its own line. A trailing backslash always stays visible, exactly as typed. If the response contains a code fence,$$, an HTML comment or<!/<?, or a<script>,<pre>,<style>or<textarea>tag, Word maps no HTML and every newline inside a paragraph is a space (the insert falls back to the previous behaviour). - Heading and list markers: a heading (
#to######) or a list item (-,*,+, or one to nine digits and.or)) needs a plain space or tab after the marker, as on the screen. A non-breaking space, an ideographic space (U+3000), a vertical tab, U+2028/U+2029 or any other Unicode space is not a separator, so#+ NBSP +ais a normal paragraph and is typed as is. A heading may be indented by up to three spaces (as on the screen); a list marker may be indented by any spaces or tabs, and the indent is not typed. A number of ten or more digits, or seven or more#, is no marker either. One leading BOM (U+FEFF) is ignored, as on the screen, so a response that starts with a BOM can still begin with a heading or list; a BOM later in the text stays text. Only a space or tab line is blank (a line holding just a non-breaking space is text, not a paragraph break). Word may show more as typed than the screen here: a bare#or-with nothing after it is typed text in Word (the screen shows an empty heading or item), and a#indented by four or more spaces or a tab is typed text with the indent trimmed, and a closing#sequence after a heading (# a #) stays typed in the Word heading (the screen drops it). Word makes a heading or a list item only where the screen shows one (never more; some items the screen shows, e.g. inside a quote or table, stay plain text): the add-in runs the same Markdown parser rules as the screen (the same structural parser plugins), and a line with a heading or list marker becomes that block only if the screen's parse makes it one. A marker the screen shows as text, code, HTML or math is typed in Word. This covers a list marker indented by four or more spaces beyond its enclosing list item (or by tabs that reach four or more columns past the item's text), such as- aafter a blank line (an indented code block on the screen), an ordered item that does not start at 1 right after a paragraph line or indented code (10) a), an empty item (a lone-or2.) after a paragraph or indented code, and a marker inside an HTML block, a code fence or a$$block. A marker in a heading or list item (- # h) is one list item whose text is# h. A marker indented into an open list item (up to three spaces past that item's text) is a nested item in Word as on the screen, and a marker outdented from it ends it. An empty item on its own is an empty list item on the screen and typed text in Word. If the screen cannot parse the text (over its parse budget), it shows plain text and Word types every marker. A block nested past the depth cap (raw HTML wrappers bring it closer) is flattened on the screen and typed in Word. A list or heading under a folded Quellen block or inside a collapsed<details>block is still a list / heading in Word, which has no folding. - Control characters: no control character reaches the document. After the structure is decided, the NUL character, U+FFFE, U+FFFF and an unpaired surrogate become U+FFFD; every other C0 control (except tab and the line break), DEL, the C1 controls and U+2028/U+2029 become a space (valid surrogate pairs, tabs and line breaks are kept). Text that is empty after that is dropped.
- Thematic break: a line of three or more of the same
-,*or_(up to three leading spaces, only spaces or tabs between and after), such as* * *or- - -, ends the paragraph and inserts nothing (Word has no rule in the safe insert); it is never a list item.---directly under a text line stays typed (it is a setext underline). A shape followed by any other character (a non-breaking space, say) is not a thematic break; it is handled by the marker rules above:* * *followed by a non-breaking space is a list item whose text is* *(the screen nests a second item; Word types it). An indented shape (four or more spaces or a tab) and a shape inside a run Word types as is stay typed, never a list item. -
HTML subset (deliberately small): Word may show more as typed than the screen, but never applies formatting the screen does not. Two constructs are honoured, both only when the whole text is unambiguous:
<br>(<br>,<br/>,<br />, any case) becomes a line break. Any other tag, and any<br>in a group of lines that also holds a backtick, a backslash,$, a link, an image or a footnote reference, a list or quote indented four or more spaces, or another tag, is shown as typed.- Aligned paragraph: a group of lines (up to the next blank line) that is exactly
<div align="V">…</div>,<p align="V">…</p>(double, single or no quotes) or<center>…</center>, with nothing before, after or inside but text and<br>, becomes one paragraph with that alignment (Vis exactlyleft,right,centerorjustify, lowercase, the same list as the screen). Anything else (uppercase tags, other attributes, nested tags, text after the closing tag, an indented tag) is shown as typed and unaligned. - If the response contains a code fence (three backticks or
~~~),$$, a comment,<!,<?,<script>,<pre>,<style>or<textarea>anywhere, Word honours no HTML anywhere in it. - A paragraph group (text between blank lines) with a lot of markup characters (quote markers, list
markers, emphasis, brackets, tags; line breaks
<br>and hyphens do not count) or deep indentation, or a response with many HTML tags, is inserted as typed: no HTML mapping and no line breaks in that group. This is a rough safety estimate, so a long, heavily punctuated paragraph can be typed too. Other groups in the same response are not affected. - Content the screen hides or collapses (a
<details>body, a link title, a setext underline) is shown in Word without the folding (the<details>tags are typed text), so Word may show more text than the screen. - Character references (
&) are not decoded. No tag, attribute,styleor URL ever reaches Word as markup. Differences from the screen are pinned intests/fixtures/markdown_line_breaks.json(export_divergence.word). - Neutralised: markdown links
[text](url)and imagesare rendered as inert plain text (the link becomestext (url), the image becomes its alt text) — never a live hyperlink or a remote image. So a[x](javascript:…)orin a hostile response cannot execute a URL or fire a remote-fetch beacon. Emphasis/code markers are flattened. - Rejected (by construction + enforced): the add-in never calls a Word sink that could render
a live hyperlink / image / HTML / field code —
insertHtml,insertOoxml,insertFileFromBase64,insertInlinePictureFromBase64,insertField,range.hyperlinksare all forbidden in the add-in source by a lint grep-guard (scripts/lint_office_addins.sh) and the inert-block behaviour is unit-tested + fuzzed (md.test.ts/md.fuzz.test.ts). This is the Word analogue of Excel's formula denylist above. - Linear time: the markdown transform is linear in the response length (no unbounded
rescans on runs of unclosed
[/![, nor on long whitespace runs between a heading / list marker and its text or on a very long digit run (the markers are read by a hand-written single pass, not a pattern), nor on runs of<or<br>, nor on a very long break-shaped line), so a hostile response cannot stall the task pane. This is guarded by a CPU-time scaling test; the accepted and neutralised shapes above are unchanged.
Every AI edit lands as a tracked change (when the Word host supports WordApi 1.4), so the user reviews and accepts/rejects it — nothing is applied silently.
Enabling document AI for a tenant
Provisioning is identical to the Copilot lane — see
Enabling document AI for a tenant. The same
designated gateway + model serve both lanes; note that this gateway's ip_allowlist must stay empty
if used by the browser lane (arbitrary end-user IPs).
Numbers in the direct document AI responses, including the model catalog, are written exactly. If a response cannot be encoded, the endpoint answers 500 with { "error": "internal error", "code": "response_encode_failed" }; see Error codes.