@datalayer/agent-runtimes 1.5.24 → 1.5.26

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.
@@ -1,93 +1,7 @@
1
1
  /**
2
- * What the gateway's `pap_sign_in` tool answers, read and checked
3
- * (AGENT_PROTOCOLS PI-56, PAP_DATALAYER P-03): the person signs in at a
4
- * company themselves — on the company's page (`direct`), by entering a
5
- * code there (`device`), or by typing what the company asks on Datalayer's
6
- * own page (`mediated`), never in the conversation. The chat shows the link,
7
- * the code and until when; the agent never sees what the person types. A
8
- * business over PACT answers its `pact_sign_in` the same way (a `device`
9
- * sign-in at the business).
10
- *
11
- * Pure: no React. A test reaches it without a chat around it.
2
+ * What the gateway's `pap_sign_in` answers, read and checked: kept in
3
+ * `portable/signIn`, which Datalayer Mobile reads too (MOBILE M-037).
12
4
  *
13
5
  * @module apps/plugins/pap-sign-in/signIn
14
6
  */
15
- /** A sign-in waiting for the person, as the card shows it. */
16
- export type PapSignInWaiting = {
17
- mode: 'direct' | 'device' | 'mediated';
18
- /** The company's page — Datalayer's own, for `mediated` — `https` only. */
19
- open: string;
20
- /** The page's domain, read from its address: what the person can trust. */
21
- host: string;
22
- /**
23
- * The company's domain, when the gateway names it: for a bound `direct`
24
- * sign-in the page opened is Datalayer's start link (PAP_DATALAYER P-04),
25
- * which sends the person on to the company and takes them back only from it.
26
- */
27
- company?: string;
28
- /** The code to enter, for `device`. */
29
- code?: string;
30
- /** Where the company sent a code, for `mediated`, when it did. */
31
- sentTo?: string;
32
- /** Until when, ISO 8601. */
33
- expiresAt?: string;
34
- /**
35
- * What the company said it needs (its `authorization` event's scope,
36
- * PAP_DATALAYER P-02): what the person is asked to allow there.
37
- */
38
- needs?: string[];
39
- };
40
- /** What the card says. */
41
- export declare const PAP_SIGN_IN_WORDS: {
42
- readonly title: (host: string) => string;
43
- readonly direct: "Open the company’s page through Datalayer, sign in there, and this conversation goes on once you are back.";
44
- readonly device: "Open the company’s page and enter this code there.";
45
- /** `mediated`: the page is Datalayer's, which names the company and asks what it asks. */
46
- readonly mediatedTitle: (host: string) => string;
47
- readonly mediated: "Open this page: it names the company and asks what the company needs. Type it there, never in this conversation.";
48
- readonly sentTo: (to: string) => string;
49
- readonly needs: (scopes: string[]) => string;
50
- readonly open: (host: string) => string;
51
- readonly code: "Your code";
52
- readonly copy: "Copy the code";
53
- readonly copied: "Copied";
54
- readonly until: (at: string) => string;
55
- readonly checkAgain: "I have signed in: check again";
56
- readonly tellMe: "Tell me when you are done.";
57
- readonly checkMessage: (host: string) => string;
58
- readonly refused: "This sign-in link cannot be opened safely, so it is not shown.";
59
- readonly qr: (host: string) => string;
60
- /** Once the person's browser came back from the company (P-04), said under the card. */
61
- readonly returned: {
62
- readonly signed_in: (company: string) => string;
63
- readonly denied: (company: string) => string;
64
- readonly refused: (company: string) => string;
65
- };
66
- };
67
- /**
68
- * Where Datalayer's `/pap/signed-in` page says a Direct Sign-In came back
69
- * (PAP_DATALAYER P-04): the card waiting for that company hears it in the
70
- * person's tab, so the conversation goes on there.
71
- */
72
- export declare const PAP_SIGN_IN_CHANNEL = "datalayer-pap-sign-in";
73
- /** How a Direct Sign-In came back. */
74
- export type PapSignInReturn = keyof typeof PAP_SIGN_IN_WORDS.returned;
75
- /** What a message on the channel says of this company's sign-in, or `null`: another company's, or not one. */
76
- export declare function signInReturnOf(message: unknown, company: string): PapSignInReturn | null;
77
- /**
78
- * `pap_sign_in` — or a business's `pact_sign_in` (PI-56) — as the gateway
79
- * names it with or without a prefix.
80
- */
81
- export declare const PAP_SIGN_IN_TOOL: RegExp;
82
- /** Whether a tool is `pap_sign_in` or `pact_sign_in`, as the gateway names it with or without a prefix. */
83
- export declare const isPapSignInTool: (name: string) => boolean;
84
- /** The page's address, `https` only; `null` for anything else. */
85
- export declare function safeSignInUrl(open: unknown): URL | null;
86
- /**
87
- * The sign-in waiting for the person, or why it is not shown: `null` for a
88
- * result that is not one (another status: the chat's default row says it),
89
- * `{ refused }` for a link that is not `https`.
90
- */
91
- export declare function readPapSignIn(result: unknown): PapSignInWaiting | {
92
- refused: string;
93
- } | null;
7
+ export * from '../../../portable/signIn';
@@ -2,147 +2,10 @@
2
2
  * Copyright (c) 2025-2026 Datalayer, Inc.
3
3
  * Distributed under the terms of the Modified BSD License.
4
4
  */
5
- /** What the card says. */
6
- export const PAP_SIGN_IN_WORDS = {
7
- title: (host) => `Sign in at ${host}`,
8
- direct: 'Open the company’s page through Datalayer, sign in there, and this conversation goes on once you are back.',
9
- device: 'Open the company’s page and enter this code there.',
10
- /** `mediated`: the page is Datalayer's, which names the company and asks what it asks. */
11
- mediatedTitle: (host) => `Sign in through ${host}`,
12
- mediated: 'Open this page: it names the company and asks what the company needs. Type it there, never in this conversation.',
13
- sentTo: (to) => `The company sent a code to ${to}.`,
14
- needs: (scopes) => `It needs: ${scopes.join(', ')}.`,
15
- open: (host) => `Open ${host}`,
16
- code: 'Your code',
17
- copy: 'Copy the code',
18
- copied: 'Copied',
19
- until: (at) => `Until ${new Date(at).toLocaleTimeString(undefined, { hour: '2-digit', minute: '2-digit' })}.`,
20
- checkAgain: 'I have signed in: check again',
21
- tellMe: 'Tell me when you are done.',
22
- checkMessage: (host) => `I have signed in at ${host}. Please check again.`,
23
- refused: 'This sign-in link cannot be opened safely, so it is not shown.',
24
- qr: (host) => `A code to scan to open ${host} on your phone`,
25
- /** Once the person's browser came back from the company (P-04), said under the card. */
26
- returned: {
27
- signed_in: (company) => `Signed in at ${company}: checking again.`,
28
- denied: (company) => `You did not sign in at ${company}: ask again when you want to.`,
29
- refused: (company) => `That sign-in at ${company} was refused, and nothing was kept: start it again here.`,
30
- },
31
- };
32
5
  /**
33
- * Where Datalayer's `/pap/signed-in` page says a Direct Sign-In came back
34
- * (PAP_DATALAYER P-04): the card waiting for that company hears it in the
35
- * person's tab, so the conversation goes on there.
6
+ * What the gateway's `pap_sign_in` answers, read and checked: kept in
7
+ * `portable/signIn`, which Datalayer Mobile reads too (MOBILE M-037).
8
+ *
9
+ * @module apps/plugins/pap-sign-in/signIn
36
10
  */
37
- export const PAP_SIGN_IN_CHANNEL = 'datalayer-pap-sign-in';
38
- /** One OAuth scope token (RFC 6749 §3.3). */
39
- const SCOPE = /^[\x21\x23-\x5B\x5D-\x7E]{1,128}$/;
40
- const DOMAIN = /^(?=.{1,253}$)([a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,63}$/;
41
- /** What a message on the channel says of this company's sign-in, or `null`: another company's, or not one. */
42
- export function signInReturnOf(message, company) {
43
- if (!message || typeof message !== 'object' || Array.isArray(message)) {
44
- return null;
45
- }
46
- const said = message;
47
- const outcome = said.outcome;
48
- return said.company === company &&
49
- (outcome === 'signed_in' || outcome === 'denied' || outcome === 'refused')
50
- ? outcome
51
- : null;
52
- }
53
- /**
54
- * `pap_sign_in` — or a business's `pact_sign_in` (PI-56) — as the gateway
55
- * names it with or without a prefix.
56
- */
57
- export const PAP_SIGN_IN_TOOL = /(^|[_.:\-/])pa(?:p|ct)_sign_in$/;
58
- /** Whether a tool is `pap_sign_in` or `pact_sign_in`, as the gateway names it with or without a prefix. */
59
- export const isPapSignInTool = (name) => PAP_SIGN_IN_TOOL.test(name);
60
- /** An MCP result's own object: its structured content, or the JSON of its text. */
61
- function unwrapped(result) {
62
- let value = result;
63
- if (typeof value === 'string') {
64
- try {
65
- value = JSON.parse(value);
66
- }
67
- catch {
68
- return null;
69
- }
70
- }
71
- if (!value || typeof value !== 'object' || Array.isArray(value)) {
72
- return null;
73
- }
74
- const data = value;
75
- if (data.structuredContent && typeof data.structuredContent === 'object') {
76
- return unwrapped(data.structuredContent);
77
- }
78
- if (Array.isArray(data.content)) {
79
- const text = data.content.find(part => part?.type === 'text' && typeof part.text === 'string');
80
- return text ? unwrapped(text.text) : null;
81
- }
82
- // FastMCP wraps a non-object answer as `{result: …}`.
83
- if (data.result && typeof data.result === 'object' && !('status' in data)) {
84
- return unwrapped(data.result);
85
- }
86
- return data;
87
- }
88
- /** The page's address, `https` only; `null` for anything else. */
89
- export function safeSignInUrl(open) {
90
- if (typeof open !== 'string') {
91
- return null;
92
- }
93
- try {
94
- const url = new URL(open);
95
- return url.protocol === 'https:' && url.hostname ? url : null;
96
- }
97
- catch {
98
- return null;
99
- }
100
- }
101
- /**
102
- * The sign-in waiting for the person, or why it is not shown: `null` for a
103
- * result that is not one (another status: the chat's default row says it),
104
- * `{ refused }` for a link that is not `https`.
105
- */
106
- export function readPapSignIn(result) {
107
- const data = unwrapped(result);
108
- if (!data || data.status !== 'waiting_for_the_person') {
109
- return null;
110
- }
111
- if (data.mode !== 'direct' &&
112
- data.mode !== 'device' &&
113
- data.mode !== 'mediated') {
114
- return null;
115
- }
116
- const url = safeSignInUrl(data.open);
117
- if (!url) {
118
- return { refused: PAP_SIGN_IN_WORDS.refused };
119
- }
120
- if (data.mode === 'device' && (typeof data.code !== 'string' || !data.code)) {
121
- return null;
122
- }
123
- // A bound Direct Sign-In opens Datalayer's start link: the card names the company the gateway
124
- // names (`PapSignIn.company`); without one, the page's own domain is the company's.
125
- const company = typeof data.company === 'string' && DOMAIN.test(data.company)
126
- ? data.company
127
- : '';
128
- // What the company said it needs: scope tokens only, anything else not shown.
129
- const needs = Array.isArray(data.needs)
130
- ? data.needs.filter((scope) => typeof scope === 'string' && SCOPE.test(scope))
131
- : [];
132
- return {
133
- mode: data.mode,
134
- open: url.toString(),
135
- host: url.hostname,
136
- ...(company ? { company } : {}),
137
- ...(typeof data.code === 'string' && data.code ? { code: data.code } : {}),
138
- ...(data.mode === 'mediated' &&
139
- typeof data.sent_to === 'string' &&
140
- data.sent_to
141
- ? { sentTo: data.sent_to }
142
- : {}),
143
- ...(typeof data.expires_at === 'string' && data.expires_at
144
- ? { expiresAt: data.expires_at }
145
- : {}),
146
- ...(needs.length > 0 ? { needs } : {}),
147
- };
148
- }
11
+ export * from '../../../portable/signIn';
@@ -539,6 +539,8 @@ export function ChatMessageList({ displayItems, actOn, upload, isLoading, isStre
539
539
  }
540
540
  }
541
541
  }
542
+ // The host's footer, asked once: a row only when it draws something.
543
+ const messageFooter = renderMessageFooter?.(message);
542
544
  return (_jsx(Box, { "data-chat-message": message.role, display: "flex", flexDirection: "column", alignItems: isUser ? 'flex-end' : 'flex-start', px: padding, py: compact ? '2px' : 1, children: _jsxs(Box, { display: "flex", gap: 2, flexDirection: isUser ? 'row-reverse' : 'row', alignItems: "flex-start",
543
545
  /*
544
546
  Full width, always.
@@ -611,7 +613,7 @@ export function ChatMessageList({ displayItems, actOn, upload, isLoading, isStre
611
613
  whiteSpace: 'pre-wrap',
612
614
  wordBreak: 'break-word',
613
615
  }, children: [message.metadata?.input === 'voice' ? (_jsx(Box, { as: "span", "data-spoken": "", title: "Said aloud", "aria-label": "Said aloud:", display: "inline-flex", verticalAlign: "text-bottom", mr: 1, opacity: 0.85, children: _jsx(MicrophoneIcon, { size: 14, "aria-hidden": "true" }) })) : null, text] }));
614
- })()) : message.live && !getMessageText(message) ? (_jsx(TypingDots, { size: 6 })) : (_jsx(ChatMarkdown, { density: density, text: getMessageText(message) || (isStreaming ? '...' : '') }))] }), message.displays?.length ? (_jsx(Box, { "data-chat-displays": "", display: "flex", flexDirection: "column", gap: 2, mt: 2, width: "100%", children: message.displays.map(display => platform ? (_jsx(ReactorDisplay, { display: display, act: actOn?.(display), upload: upload }, display.id)) : (_jsx(DisplayText, { display: display }, display.id))) })) : null, renderMessageFooter?.(message) ? (_jsx(Box, { display: "flex", gap: 2, alignItems: "center", mt: 1, flexWrap: "wrap", flexDirection: isUser ? 'row-reverse' : 'row', children: renderMessageFooter(message) })) : null] })] }) }, message.id));
616
+ })()) : message.live && !getMessageText(message) ? (_jsx(TypingDots, { size: 6 })) : (_jsx(ChatMarkdown, { density: density, text: getMessageText(message) || (isStreaming ? '...' : '') }))] }), message.displays?.length ? (_jsx(Box, { "data-chat-displays": "", display: "flex", flexDirection: "column", gap: 2, mt: 2, width: "100%", children: message.displays.map(display => platform ? (_jsx(ReactorDisplay, { display: display, act: actOn?.(display), upload: upload }, display.id)) : (_jsx(DisplayText, { display: display }, display.id))) })) : null, messageFooter ? (_jsx(Box, { display: "flex", gap: 2, alignItems: "center", mt: 1, flexWrap: "wrap", flexDirection: isUser ? 'row-reverse' : 'row', children: messageFooter })) : null] })] }) }, message.id));
615
617
  };
616
618
  return (_jsxs(_Fragment, { children: [displayItems.map((item, index) => {
617
619
  const itemUI = renderItem(item, index);
@@ -21,6 +21,7 @@
21
21
  * @module portable/conversation
22
22
  */
23
23
  import { type AgUiEvent } from './agui';
24
+ import { type ProtocolDisplay } from './displays';
24
25
  /** How many rows a conversation keeps: its newest. */
25
26
  export declare const ITEM_LIMIT = 400;
26
27
  /** How many characters of an answer are kept. */
@@ -51,6 +52,8 @@ export type ConversationItem = {
51
52
  /** Its result in words, cut at its limit. */
52
53
  result: string;
53
54
  error: string;
55
+ /** The protocol display its result carries, read strictly (`portable/displays`, MOBILE M-037). */
56
+ display: ProtocolDisplay | null;
54
57
  } | {
55
58
  kind: 'step';
56
59
  id: string;
@@ -25,6 +25,7 @@
25
25
  * @module portable/conversation
26
26
  */
27
27
  import { REACTOR_UI_NAME, toolResultOf, UI_ON_RUN, } from './agui';
28
+ import { displayOfToolResult } from './displays';
28
29
  import { RUN_END_WORDS } from './records';
29
30
  import { messagesOfThread } from './thread';
30
31
  /** How many rows a conversation keeps: its newest. */
@@ -56,6 +57,17 @@ const appended = (kept, delta, limit) => {
56
57
  }
57
58
  return cut(kept + delta, limit);
58
59
  };
60
+ /** A result as the model read it: the page's `_meta` (its display) is the card's, not words. */
61
+ function withoutMeta(result) {
62
+ if (result &&
63
+ typeof result === 'object' &&
64
+ !Array.isArray(result) &&
65
+ '_meta' in result) {
66
+ const { _meta: _page, ...view } = result;
67
+ return view;
68
+ }
69
+ return result;
70
+ }
59
71
  /** A result in words. */
60
72
  function said(result) {
61
73
  if (result === undefined || result === null) {
@@ -214,6 +226,7 @@ export function reduceConversation(state, event) {
214
226
  status: 'running',
215
227
  result: '',
216
228
  error: '',
229
+ display: null,
217
230
  },
218
231
  ], 1);
219
232
  }
@@ -232,8 +245,9 @@ export function reduceConversation(state, event) {
232
245
  ? {
233
246
  ...item,
234
247
  status: result.success ? 'complete' : 'error',
235
- result: cut(said(result.result), TOOL_TEXT_LIMIT),
248
+ result: cut(said(withoutMeta(result.result)), TOOL_TEXT_LIMIT),
236
249
  error: result.error ?? '',
250
+ display: displayOfToolResult(item.name, result.result, item.id),
237
251
  }
238
252
  : item) ?? noted(state, event));
239
253
  }
@@ -0,0 +1,100 @@
1
+ /**
2
+ * A Direct Conversation the person types in themselves (PAP_DATALAYER P-08,
3
+ * MOBILE M-038): a linked sub-conversation under the one a company answered
4
+ * in, where the person's own words go to the company as `sender: human`,
5
+ * never through the application's model, until the company closes it.
6
+ *
7
+ * Each message takes a one-use ticket IAM gives the person for one
8
+ * application, one company and one conversation (`POST /pap/my/direct`, with
9
+ * their own sign-in), then goes to the gateway with it (`POST
10
+ * /api/mcp/v1/pap/direct`); the company's replies are read back from the
11
+ * cursor last read (`GET /api/mcp/v1/pap/direct`), never by sending again.
12
+ * One client for every page (the Studio's chat, Datalayer Mobile): the
13
+ * addresses, the person's sign-in and `fetch` are given.
14
+ *
15
+ * Pure but for the given `fetch`: no React, DOM or storage.
16
+ *
17
+ * @module portable/direct
18
+ */
19
+ /** Where the person writes: the application, the company by its domain, and the conversation there. */
20
+ export type DirectTarget = {
21
+ appUid: string;
22
+ company: string;
23
+ conversationId: string;
24
+ };
25
+ /** One reply of the company, and who wrote it there. */
26
+ export type DirectReply = {
27
+ text: string;
28
+ from: 'agent' | 'human';
29
+ };
30
+ /** What the company answered, and where the conversation stands. */
31
+ export type DirectAnswer = {
32
+ directConversation: string;
33
+ replies: DirectReply[];
34
+ status: string;
35
+ responder: string;
36
+ cursor: string;
37
+ /** The `PapReplies` display, when the company wrote anything. */
38
+ display: unknown;
39
+ };
40
+ /** The longest message the gateway takes. */
41
+ export declare const DIRECT_MAX = 4000;
42
+ /** What a page says around the person's own words. */
43
+ export declare const DIRECT_WORDS: {
44
+ readonly notConfigured: "Datalayer is not configured to send your words to a company here.";
45
+ readonly signIn: "Sign in to Datalayer first: only you write in your Direct Conversation.";
46
+ readonly tooLong: "Write a message of at most 4000 characters.";
47
+ readonly empty: "Write something to send.";
48
+ readonly unread: (company: string) => string;
49
+ readonly write: (company: string) => string;
50
+ readonly says: (company: string) => string;
51
+ readonly writing: (company: string) => string;
52
+ readonly how: "What you write here goes to the company as your own words, never through the application. The company’s answers appear here.";
53
+ readonly you: "You";
54
+ readonly agent: "Its agent";
55
+ readonly human: "One of its people";
56
+ readonly back: "Back to the application";
57
+ readonly closed: (company: string) => string;
58
+ readonly locked: (company: string) => string;
59
+ };
60
+ /** The addresses of IAM and the gateway, the person's sign-in, and `fetch`. */
61
+ export type DirectClientOptions = {
62
+ iamUrl: string;
63
+ gatewayUrl: string;
64
+ getAccessToken: () => string | undefined;
65
+ fetch: typeof fetch;
66
+ };
67
+ /** The gateway's answer, read whole or refused. */
68
+ export declare function directAnswerOf(raw: unknown, company: string): DirectAnswer;
69
+ /** IAM's ticket and the gateway's Direct Conversation routes, as the person. */
70
+ export declare function directClient({ iamUrl, gatewayUrl, getAccessToken, fetch: fetcher, }: DirectClientOptions): {
71
+ ticket: (target: DirectTarget) => Promise<string>;
72
+ /**
73
+ * The person's own words, sent as theirs: a ticket, then the words with
74
+ * it. Refused in the gateway's sentence, and never retried.
75
+ */
76
+ send: (target: DirectTarget, text: string) => Promise<DirectAnswer>;
77
+ /** What the company wrote since `cursor`: read, never sent again. */
78
+ read: (target: DirectTarget, cursor?: string) => Promise<DirectAnswer>;
79
+ };
80
+ export type DirectClient = ReturnType<typeof directClient>;
81
+ /** One line of the Direct Conversation: the person's, or the company's (its agent or one of its people). */
82
+ export type DirectLine = {
83
+ from: 'you' | 'agent' | 'human';
84
+ text: string;
85
+ };
86
+ /** A Direct Conversation open under its parent: the parent's composer is locked while it is. */
87
+ export type DirectOpen = {
88
+ /** Before the first words, the conversation it opens under; after, the Direct Conversation itself. */
89
+ target: DirectTarget;
90
+ lines: DirectLine[];
91
+ cursor: string;
92
+ /** Closed by the company: nothing more is sent, and the parent is talked to again. */
93
+ closed: boolean;
94
+ };
95
+ /** A Direct Conversation opened under the conversation a company answered in. */
96
+ export declare const openDirect: (target: DirectTarget) => DirectOpen;
97
+ /** The open conversation with what the company answered, and the person's words when they sent some. */
98
+ export declare function withDirectAnswer(open: DirectOpen, answer: DirectAnswer, mine?: string): DirectOpen;
99
+ /** Who wrote a line, said apart: the person, the company's agent, one of its people. */
100
+ export declare const directAuthor: (line: DirectLine) => string;
@@ -0,0 +1,172 @@
1
+ /*
2
+ * Copyright (c) 2025-2026 Datalayer, Inc.
3
+ * Distributed under the terms of the Modified BSD License.
4
+ */
5
+ /** The longest message the gateway takes. */
6
+ export const DIRECT_MAX = 4000;
7
+ /** What a page says around the person's own words. */
8
+ export const DIRECT_WORDS = {
9
+ notConfigured: 'Datalayer is not configured to send your words to a company here.',
10
+ signIn: 'Sign in to Datalayer first: only you write in your Direct Conversation.',
11
+ tooLong: `Write a message of at most ${DIRECT_MAX} characters.`,
12
+ empty: 'Write something to send.',
13
+ unread: (company) => `${company}'s answer could not be read.`,
14
+ write: (company) => `Write to ${company} yourself`,
15
+ says: (company) => `Your own words to ${company}, sent as yours, not through the application`,
16
+ writing: (company) => `Writing to ${company} yourself`,
17
+ how: 'What you write here goes to the company as your own words, never through the application. The company’s answers appear here.',
18
+ you: 'You',
19
+ agent: 'Its agent',
20
+ human: 'One of its people',
21
+ back: 'Back to the application',
22
+ closed: (company) => `${company} closed this conversation: write through the application again.`,
23
+ locked: (company) => `You are writing to ${company} yourself: go back to the application to talk to it.`,
24
+ };
25
+ const root = (url) => url.replace(/\/+$/, '');
26
+ /** The sentence a refusal carries: its `note` (closed, none, another) or its `detail`. */
27
+ async function refusal(response, fallback) {
28
+ const body = (await response.json().catch(() => ({})));
29
+ const said = typeof body.note === 'string'
30
+ ? body.note
31
+ : typeof body.detail === 'string'
32
+ ? body.detail
33
+ : '';
34
+ return new Error(said || `${fallback} (${response.status})`);
35
+ }
36
+ /** The gateway's answer, read whole or refused. */
37
+ export function directAnswerOf(raw, company) {
38
+ const data = raw;
39
+ const replies = data?.replies;
40
+ if (!data ||
41
+ typeof data.direct_conversation !== 'string' ||
42
+ !Array.isArray(replies) ||
43
+ typeof data.status !== 'string' ||
44
+ replies.some(reply => !reply ||
45
+ typeof reply.text !== 'string' ||
46
+ (reply.from !== 'agent' &&
47
+ reply.from !== 'human'))) {
48
+ throw new Error(DIRECT_WORDS.unread(company));
49
+ }
50
+ return {
51
+ directConversation: data.direct_conversation,
52
+ replies: replies.map(reply => ({
53
+ text: reply.text,
54
+ from: reply.from,
55
+ })),
56
+ status: data.status,
57
+ responder: typeof data.responder === 'string' ? data.responder : '',
58
+ cursor: typeof data.cursor === 'string' ? data.cursor : '',
59
+ display: data.display ?? null,
60
+ };
61
+ }
62
+ /** IAM's ticket and the gateway's Direct Conversation routes, as the person. */
63
+ export function directClient({ iamUrl, gatewayUrl, getAccessToken, fetch: fetcher, }) {
64
+ const bearer = () => {
65
+ const token = getAccessToken();
66
+ if (!token) {
67
+ throw new Error(DIRECT_WORDS.signIn);
68
+ }
69
+ return { Authorization: `Bearer ${token}` };
70
+ };
71
+ const configured = (...urls) => {
72
+ if (urls.some(url => !url)) {
73
+ throw new Error(DIRECT_WORDS.notConfigured);
74
+ }
75
+ };
76
+ /** A one-use ticket for one message, asked of IAM with the person's own sign-in. */
77
+ const ticket = async (target) => {
78
+ configured(iamUrl);
79
+ const response = await fetcher(`${root(iamUrl)}/api/iam/v1/pap/my/direct`, {
80
+ method: 'POST',
81
+ headers: { ...bearer(), 'Content-Type': 'application/json' },
82
+ body: JSON.stringify({
83
+ app_uid: target.appUid,
84
+ company: target.company,
85
+ conversation_id: target.conversationId,
86
+ }),
87
+ });
88
+ if (!response.ok) {
89
+ throw await refusal(response, 'Your words could not be sent');
90
+ }
91
+ const body = (await response.json());
92
+ if (typeof body.ticket !== 'string' || !body.ticket) {
93
+ throw new Error('Your words could not be sent: no ticket came back.');
94
+ }
95
+ return body.ticket;
96
+ };
97
+ return {
98
+ ticket,
99
+ /**
100
+ * The person's own words, sent as theirs: a ticket, then the words with
101
+ * it. Refused in the gateway's sentence, and never retried.
102
+ */
103
+ send: async (target, text) => {
104
+ const words = text.trim();
105
+ if (!words) {
106
+ throw new Error(DIRECT_WORDS.empty);
107
+ }
108
+ if (words.length > DIRECT_MAX) {
109
+ throw new Error(DIRECT_WORDS.tooLong);
110
+ }
111
+ configured(gatewayUrl);
112
+ const used = await ticket(target);
113
+ const response = await fetcher(`${root(gatewayUrl)}/api/mcp/v1/pap/direct`, {
114
+ method: 'POST',
115
+ headers: { ...bearer(), 'Content-Type': 'application/json' },
116
+ body: JSON.stringify({ ticket: used, text: words }),
117
+ });
118
+ if (!response.ok) {
119
+ throw await refusal(response, 'Your words were not sent');
120
+ }
121
+ return directAnswerOf(await response.json(), target.company);
122
+ },
123
+ /** What the company wrote since `cursor`: read, never sent again. */
124
+ read: async (target, cursor = '') => {
125
+ configured(gatewayUrl);
126
+ const query = new URLSearchParams({
127
+ app_uid: target.appUid,
128
+ company: target.company,
129
+ conversation_id: target.conversationId,
130
+ });
131
+ if (cursor) {
132
+ query.set('cursor', cursor);
133
+ }
134
+ const response = await fetcher(`${root(gatewayUrl)}/api/mcp/v1/pap/direct?${query.toString()}`, { headers: bearer() });
135
+ if (!response.ok) {
136
+ throw await refusal(response, DIRECT_WORDS.unread(target.company));
137
+ }
138
+ return directAnswerOf(await response.json(), target.company);
139
+ },
140
+ };
141
+ }
142
+ /** A Direct Conversation opened under the conversation a company answered in. */
143
+ export const openDirect = (target) => ({
144
+ target,
145
+ lines: [],
146
+ cursor: '',
147
+ closed: false,
148
+ });
149
+ /** The open conversation with what the company answered, and the person's words when they sent some. */
150
+ export function withDirectAnswer(open, answer, mine) {
151
+ return {
152
+ target: {
153
+ ...open.target,
154
+ conversationId: answer.directConversation || open.target.conversationId,
155
+ },
156
+ lines: [
157
+ ...open.lines,
158
+ ...(mine !== undefined
159
+ ? [{ from: 'you', text: mine.trim() }]
160
+ : []),
161
+ ...answer.replies.map(reply => ({ from: reply.from, text: reply.text })),
162
+ ],
163
+ cursor: answer.cursor || open.cursor,
164
+ closed: answer.status === 'closed',
165
+ };
166
+ }
167
+ /** Who wrote a line, said apart: the person, the company's agent, one of its people. */
168
+ export const directAuthor = (line) => line.from === 'you'
169
+ ? DIRECT_WORDS.you
170
+ : line.from === 'agent'
171
+ ? DIRECT_WORDS.agent
172
+ : DIRECT_WORDS.human;