@primusclaw/personal-agent-teams 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (128) hide show
  1. package/dist/LICENSE +37 -0
  2. package/dist/index.js +8817 -0
  3. package/dist/main.js +8739 -0
  4. package/dist/types/activity/decorations.d.ts +40 -0
  5. package/dist/types/activity/feedback-loop.d.ts +9 -0
  6. package/dist/types/activity/inbound/actions.d.ts +55 -0
  7. package/dist/types/activity/inbound/identity.d.ts +36 -0
  8. package/dist/types/activity/inbound/index.d.ts +9 -0
  9. package/dist/types/activity/inbound/links.d.ts +30 -0
  10. package/dist/types/activity/inbound/markup.d.ts +39 -0
  11. package/dist/types/activity/inbound/mentions.d.ts +37 -0
  12. package/dist/types/activity/inbound/patterns.d.ts +21 -0
  13. package/dist/types/activity/inbound/quotes-html.d.ts +17 -0
  14. package/dist/types/activity/inbound/quotes.d.ts +32 -0
  15. package/dist/types/activity/inbound/schema.d.ts +44 -0
  16. package/dist/types/activity/inbound/to-event.d.ts +24 -0
  17. package/dist/types/activity/outbound.d.ts +25 -0
  18. package/dist/types/activity/redact-activity.d.ts +16 -0
  19. package/dist/types/activity/reference.d.ts +9 -0
  20. package/dist/types/activity/stream-activity.d.ts +16 -0
  21. package/dist/types/assembly/features-assistant.d.ts +42 -0
  22. package/dist/types/assembly/features-base.d.ts +49 -0
  23. package/dist/types/assembly/features-proactive.d.ts +26 -0
  24. package/dist/types/assembly/features-remote.d.ts +13 -0
  25. package/dist/types/assembly/features-review.d.ts +31 -0
  26. package/dist/types/assembly/features-switches.d.ts +26 -0
  27. package/dist/types/assembly/features-text.d.ts +35 -0
  28. package/dist/types/assembly/features-turns.d.ts +19 -0
  29. package/dist/types/assembly/features-w8.d.ts +18 -0
  30. package/dist/types/assembly/features.d.ts +42 -0
  31. package/dist/types/assembly/http.d.ts +23 -0
  32. package/dist/types/assembly/inbound.d.ts +18 -0
  33. package/dist/types/assembly/outbound.d.ts +40 -0
  34. package/dist/types/assembly/plugins.d.ts +20 -0
  35. package/dist/types/assembly/runner.d.ts +28 -0
  36. package/dist/types/assembly/secrets.d.ts +11 -0
  37. package/dist/types/assembly/timers.d.ts +14 -0
  38. package/dist/types/assembly/worker-services.d.ts +23 -0
  39. package/dist/types/assembly/worker.d.ts +19 -0
  40. package/dist/types/azure/keyvault-config.d.ts +24 -0
  41. package/dist/types/azure/keyvault.d.ts +52 -0
  42. package/dist/types/azure/workload-identity.d.ts +56 -0
  43. package/dist/types/caps.d.ts +13 -0
  44. package/dist/types/cards/cjk.d.ts +9 -0
  45. package/dist/types/cards/json.d.ts +12 -0
  46. package/dist/types/cards/kit.d.ts +115 -0
  47. package/dist/types/cards/view-buttons.d.ts +4 -0
  48. package/dist/types/config/env.d.ts +48 -0
  49. package/dist/types/config/style.d.ts +32 -0
  50. package/dist/types/connector/errors.d.ts +34 -0
  51. package/dist/types/connector/hosts.d.ts +40 -0
  52. package/dist/types/connector/lanes.d.ts +10 -0
  53. package/dist/types/connector/limits.d.ts +23 -0
  54. package/dist/types/connector/outbox.d.ts +97 -0
  55. package/dist/types/connector/py-parse.d.ts +10 -0
  56. package/dist/types/connector/request.d.ts +21 -0
  57. package/dist/types/connector/response.d.ts +9 -0
  58. package/dist/types/connector/retry.d.ts +57 -0
  59. package/dist/types/connector/timer.d.ts +18 -0
  60. package/dist/types/connector/tokens/assertion.d.ts +38 -0
  61. package/dist/types/connector/tokens/cached.d.ts +33 -0
  62. package/dist/types/connector/tokens/federated.d.ts +41 -0
  63. package/dist/types/connector/tokens/http.d.ts +11 -0
  64. package/dist/types/connector/tokens/imds.d.ts +26 -0
  65. package/dist/types/feedback/vote.d.ts +10 -0
  66. package/dist/types/gate/entry-env.d.ts +25 -0
  67. package/dist/types/gate/no-queue.d.ts +22 -0
  68. package/dist/types/gate/routes.d.ts +34 -0
  69. package/dist/types/html/entities.d.ts +2 -0
  70. package/dist/types/html/html5-entities.d.ts +6 -0
  71. package/dist/types/html/lexer.d.ts +18 -0
  72. package/dist/types/inbound/attachments.d.ts +36 -0
  73. package/dist/types/inbound/download.d.ts +34 -0
  74. package/dist/types/inbound/fetcher.d.ts +63 -0
  75. package/dist/types/inbound/names.d.ts +2 -0
  76. package/dist/types/inbound/types.d.ts +24 -0
  77. package/dist/types/index.d.ts +15 -0
  78. package/dist/types/main.d.ts +13 -0
  79. package/dist/types/messenger/acks.d.ts +23 -0
  80. package/dist/types/messenger/conversation.d.ts +59 -0
  81. package/dist/types/messenger/masker.d.ts +20 -0
  82. package/dist/types/messenger/render.d.ts +27 -0
  83. package/dist/types/observability/build-info.d.ts +7 -0
  84. package/dist/types/outbound/log-fields.d.ts +14 -0
  85. package/dist/types/outbound/outbox.d.ts +70 -0
  86. package/dist/types/richtext/blocks.d.ts +7 -0
  87. package/dist/types/richtext/check.d.ts +4 -0
  88. package/dist/types/richtext/constants.d.ts +15 -0
  89. package/dist/types/richtext/escape.d.ts +37 -0
  90. package/dist/types/richtext/index.d.ts +30 -0
  91. package/dist/types/richtext/inline.d.ts +11 -0
  92. package/dist/types/richtext/lines.d.ts +18 -0
  93. package/dist/types/richtext/scan.d.ts +17 -0
  94. package/dist/types/richtext/status.d.ts +9 -0
  95. package/dist/types/richtext/url.d.ts +2 -0
  96. package/dist/types/servicebus/client.d.ts +40 -0
  97. package/dist/types/servicebus/consumer.d.ts +53 -0
  98. package/dist/types/servicebus/outbox.d.ts +22 -0
  99. package/dist/types/stream/busy.d.ts +17 -0
  100. package/dist/types/stream/informative.d.ts +10 -0
  101. package/dist/types/stream/live-stream.d.ts +25 -0
  102. package/dist/types/stream/mutex.d.ts +6 -0
  103. package/dist/types/stream/teams-stream.d.ts +63 -0
  104. package/dist/types/surface.d.ts +46 -0
  105. package/dist/types/views/approval/index.d.ts +33 -0
  106. package/dist/types/views/assistant/index.d.ts +40 -0
  107. package/dist/types/views/commands/index.d.ts +26 -0
  108. package/dist/types/views/feedback/index.d.ts +23 -0
  109. package/dist/types/views/index.d.ts +3 -0
  110. package/dist/types/views/observe/index.d.ts +10 -0
  111. package/dist/types/views/proactive/index.d.ts +31 -0
  112. package/dist/types/views/registry.d.ts +21 -0
  113. package/dist/types/views/remote/agents-card.d.ts +10 -0
  114. package/dist/types/views/remote/elements.d.ts +18 -0
  115. package/dist/types/views/remote/hidden-card.d.ts +4 -0
  116. package/dist/types/views/remote/index.d.ts +12 -0
  117. package/dist/types/views/remote/permission-cards.d.ts +9 -0
  118. package/dist/types/views/remote/sessions-card.d.ts +8 -0
  119. package/dist/types/views/remote/small-cards.d.ts +14 -0
  120. package/dist/types/views/remote/status-card.d.ts +5 -0
  121. package/dist/types/views/remote/window-card.d.ts +5 -0
  122. package/dist/types/views/review/index.d.ts +21 -0
  123. package/dist/types/views/turn/index.d.ts +28 -0
  124. package/dist/types/views/turn/note.d.ts +10 -0
  125. package/dist/types/views/turn/stop.d.ts +8 -0
  126. package/dist/types/worker-api.d.ts +69 -0
  127. package/package.json +39 -4
  128. package/README.md +0 -3
@@ -0,0 +1,115 @@
1
+ import type { CardElement, Json, JsonObject } from "./json.js";
2
+ export declare const CARD_VERSION = "1.5";
3
+ export declare const SCHEMA = "http://adaptivecards.io/schemas/adaptive-card.json";
4
+ export declare const ADAPTIVE_CARD = "application/vnd.microsoft.card.adaptive";
5
+ /** One emoji per meaning, used for that meaning only (a header, a section, a badge, a list row, at most one in a button). */
6
+ export declare const ICONS: {
7
+ readonly review: "🔍";
8
+ readonly good: "✅";
9
+ readonly needs_you: "⚠️";
10
+ readonly failed: "❌";
11
+ readonly working: "⏳";
12
+ readonly handoff: "🤝";
13
+ readonly board: "📋";
14
+ readonly connect: "🔌";
15
+ readonly feedback: "💬";
16
+ readonly question: "❓";
17
+ readonly denied: "🚫";
18
+ readonly stopped: "⏹️";
19
+ readonly expired: "⌛";
20
+ readonly notice: "🔔";
21
+ readonly settings: "⚙️";
22
+ readonly session: "🗂️";
23
+ readonly repo: "📦";
24
+ readonly changes: "📝";
25
+ readonly file: "📎";
26
+ readonly machine: "🖥️";
27
+ readonly dropped: "🗑️";
28
+ };
29
+ export type Meaning = keyof typeof ICONS;
30
+ export declare const EMOJI_MAX = 3;
31
+ /** The status a header can say; "default" draws Teams' emphasis band. */
32
+ export declare const TONES: readonly ["good", "attention", "warning", "accent", "default"];
33
+ export type Tone = (typeof TONES)[number];
34
+ export type ButtonStyle = "positive" | "destructive" | "";
35
+ export declare const BUTTONS_MAX = 3;
36
+ export declare const TITLE_MAX = 120;
37
+ export declare const FACT_TITLE_MAX = 40;
38
+ export declare const FACT_VALUE_MAX = 200;
39
+ export declare const BUTTON_TITLE_MAX = 40;
40
+ /** The kit was asked for something no card may have (an unknown tone, a fourth button). */
41
+ export declare class CardKitError extends Error {
42
+ name: string;
43
+ }
44
+ export interface TextOptions {
45
+ subtle?: boolean;
46
+ size?: string;
47
+ weight?: string;
48
+ maxLines?: number;
49
+ spacing?: string;
50
+ mono?: boolean;
51
+ /** Further TextBlock properties, added last (an `id`, `horizontalAlignment`, `color` of a fold's label...). */
52
+ extra?: JsonObject;
53
+ }
54
+ /** One wrapped TextBlock of body copy (Chinese made full-width). Colour is not an option: status belongs in the header. */
55
+ export declare function text(value: string, options?: TextOptions): CardElement;
56
+ /** A subtle small line: when a card runs out, who else can answer, what a button does not do. */
57
+ export declare function note(value: string, extra?: JsonObject): CardElement;
58
+ /** `words` after the emoji of `meaning`; '' meaning: the words alone. */
59
+ export declare function icon(meaning: Meaning | "", words: string): string;
60
+ export interface HeaderOptions {
61
+ tone?: Tone;
62
+ subtitle?: string;
63
+ titleId?: string;
64
+ emoji?: Meaning | "";
65
+ }
66
+ /** The header row on top of a card: a short bar in the tone's colour beside one bold sentence and at most one subtle line. */
67
+ export declare function header(title: string, options?: HeaderOptions): CardElement;
68
+ /** The list that holds a header's title and subtitle, to add one more subtle line under them. */
69
+ export declare function headerItems(block: CardElement): CardElement[];
70
+ /** A heading inside a card (a column of the board): the same bar as the header, with one bold line of default size. */
71
+ export declare function section(title: string, tone?: Tone): CardElement;
72
+ export interface Badge {
73
+ meaning: Meaning;
74
+ label: string;
75
+ count: number;
76
+ tone: Tone;
77
+ }
78
+ /** Count badges side by side: a box in the tone's container style with the emoji, the count and its label on one line. */
79
+ export declare function badges(counts: readonly Badge[]): CardElement;
80
+ /** A section head on a band of the tone's container style: one bold line, with the section's emoji first. */
81
+ export declare function band(title: string, tone?: Tone, meaning?: Meaning | ""): CardElement;
82
+ /** One entry of a list on one line: its status emoji, then its words and, after " · ", what matters about it. */
83
+ export declare function row(rowId: string, meaning: Meaning, words: string, detail?: string): CardElement;
84
+ export declare const EMOJI: RegExp;
85
+ export declare function emojiIn(value: string): string[];
86
+ /** What a card may carry: EMOJI_MAX, and one more for each list row, section band and count badge in it. */
87
+ export declare function emojiBudget(card: JsonObject): number;
88
+ /** The rows that have a value, as one FactSet (an empty list when none has): short names, clipped values. */
89
+ export declare function facts(rows: ReadonlyArray<readonly [string, unknown]>, limit?: number): CardElement[];
90
+ /** `items` hidden behind one subtle "label ▾" line that shows them in place. `foldId` must be unique in the card. */
91
+ export declare function fold(foldId: string, items: CardElement[], label?: string): CardElement[];
92
+ export declare function buttons(actions: ReadonlyArray<CardElement | null | undefined>, primary?: ButtonStyle): CardElement[];
93
+ /** An Action.Execute (what Teams desktop and mobile both send back to the worker). */
94
+ export declare function execute(title: string, verb: string, data: JsonObject): CardElement;
95
+ export declare function openUrl(title: string, url: string): CardElement;
96
+ export interface AdaptiveCard extends JsonObject {
97
+ type: "AdaptiveCard";
98
+ version: string;
99
+ $schema: string;
100
+ body: CardElement[];
101
+ }
102
+ /** The Adaptive Card itself. `buttonsMax` is raised only where the buttons are someone else's choices that must all stay reachable. */
103
+ export declare function card(body: CardElement[], actions?: CardElement[], buttonsMax?: number, extra?: JsonObject): AdaptiveCard;
104
+ export interface CardAttachment extends JsonObject {
105
+ contentType: string;
106
+ content: Json;
107
+ }
108
+ export interface CardMessage extends JsonObject {
109
+ type: "message";
110
+ attachments: CardAttachment[];
111
+ }
112
+ /** A message whose one attachment is the card. */
113
+ export declare function cardActivity(content: JsonObject): CardMessage;
114
+ /** `cardActivity(card(body, actions))`: what most builders return. */
115
+ export declare function message(body: CardElement[], actions?: CardElement[], buttonsMax?: number, extra?: JsonObject): CardMessage;
@@ -0,0 +1,4 @@
1
+ /** Core's view buttons as the card kit's actions: one that comes back to the worker (Action.Execute) or opens a link. */
2
+ import type { ViewButton } from "@primusclaw/personal-agent";
3
+ import type { CardElement } from "./json.js";
4
+ export declare function viewButton(button: ViewButton): CardElement;
@@ -0,0 +1,48 @@
1
+ import { type WorkerIdentity } from "../azure/workload-identity.js";
2
+ import type { OutboundMode } from "../caps.js";
3
+ import { type Style } from "./style.js";
4
+ export type Env = Readonly<Record<string, string | undefined>>;
5
+ export declare class TeamsConfigError extends Error {
6
+ name: string;
7
+ }
8
+ export type BotTokenSource = "imds" | "federated";
9
+ export interface BotSettings {
10
+ readonly tokenSource: BotTokenSource;
11
+ readonly msiClientId: string;
12
+ readonly tenantId: string;
13
+ readonly assertionKeyFile: string;
14
+ readonly assertionIssuer: string;
15
+ readonly assertionSubject: string;
16
+ }
17
+ export interface BusSettings {
18
+ /** The namespace's host name: the queues are reached as the worker's identity. "" : by the connection strings. */
19
+ readonly namespace: string;
20
+ readonly listenConnectionString: string;
21
+ readonly sendConnectionString: string;
22
+ readonly inboundQueue: string;
23
+ readonly outboundQueue: string;
24
+ readonly receiverCount: number;
25
+ }
26
+ export interface TeamsSettings {
27
+ readonly outboundMode: OutboundMode;
28
+ readonly bot: BotSettings;
29
+ readonly bus: BusSettings;
30
+ /** The worker's own identity, when SERVICEBUS_NAMESPACE or SECRETS_SOURCE=keyvault needs it. */
31
+ readonly workerIdentity: WorkerIdentity | undefined;
32
+ readonly installHintUrl: string;
33
+ readonly style: Style;
34
+ }
35
+ /** An on/off setting, `fallback` when unset or empty. */
36
+ export declare function switchOf(env: Env, name: string, fallback: boolean): boolean;
37
+ /** TEAMS_STREAMING: `off`, or the chat kinds that get Teams' floating status (`personal`, `groupChat`, comma separated). */
38
+ export declare function streamScopes(raw: string): ReadonlySet<string>;
39
+ export declare function styleFromEnv(env: Env): Style;
40
+ /** SERVICEBUS_NAMESPACE: the namespace's host name (<name>.servicebus.windows.net), or "" for the connection strings. */
41
+ export declare function busNamespace(raw: string): string;
42
+ /**
43
+ * The Teams settings from `env`. `queues` false (the release gate's test entry: no Service Bus at all) skips the queue
44
+ * settings, which are then empty.
45
+ */
46
+ export declare function teamsSettingsFromEnv(env: Env, options?: {
47
+ readonly queues?: boolean;
48
+ }): TeamsSettings;
@@ -0,0 +1,32 @@
1
+ /**
2
+ * How replies look in Teams: the switches of the reply style (TEAMS_* settings, read once at start). Each can be turned
3
+ * off with one setting, and whatever a switch turns on degrades to a plain message when Teams does not take it.
4
+ *
5
+ * - `aiLabel` (TEAMS_AI_LABEL, on): an AI-generated answer carries Teams' "AI generated" label.
6
+ * - `streaming` (TEAMS_STREAMING, `personal,groupChat`): the chat kinds where a turn shows Teams' floating status (direct
7
+ * outbound mode only; `off` turns it off).
8
+ * - `streamText` (TEAMS_STREAM_TEXT, off): the agent's visible text is streamed into the answer's bubble.
9
+ * - `assistantReceipt` (TEAMS_ASSISTANT_RECEIPT, on), `assistantProgress` (TEAMS_ASSISTANT_PROGRESS, on),
10
+ * `assistantStreamSay` (TEAMS_ASSISTANT_STREAM_SAY, on): the assistant's receipt, its live steps and streamed words.
11
+ * - `ownThumbsMobile` (TEAMS_OWN_THUMBS_MOBILE, on), `suggestedReplies` (TEAMS_SUGGESTED_REPLIES, on), `citations`
12
+ * (TEAMS_CITATIONS, off).
13
+ */
14
+ /** The Teams conversation types a stream may be used in (a channel never). */
15
+ export declare const STREAM_SCOPES: readonly ["personal", "groupChat"];
16
+ export type StreamScope = (typeof STREAM_SCOPES)[number];
17
+ export interface Style {
18
+ readonly aiLabel: boolean;
19
+ readonly streaming: ReadonlySet<string>;
20
+ readonly streamText: boolean;
21
+ readonly assistantReceipt: boolean;
22
+ readonly assistantProgress: boolean;
23
+ readonly assistantStreamSay: boolean;
24
+ readonly ownThumbsMobile: boolean;
25
+ readonly suggestedReplies: boolean;
26
+ readonly citations: boolean;
27
+ }
28
+ export declare const DEFAULT_STYLE: Style;
29
+ /** Whether Teams' floating status is on for this kind of chat ("personal", "groupChat"; a channel never). */
30
+ export declare function streamsIn(style: Style, conversationType: string): boolean;
31
+ /** One line for the start-up log (names and values only), as the Python worker wrote it. */
32
+ export declare function describeStyle(style: Style): string;
@@ -0,0 +1,34 @@
1
+ /**
2
+ * The failures of a direct send to the Bot Connector, as classes: what a token source, the request builder and the retry
3
+ * loop throw. Their messages are reasons (a status, an error code, an error kind), never a body, a text or a token.
4
+ */
5
+ /** The bot's token could not be had. `transient`: worth another try (busy or unreachable), as opposed to a refusal. */
6
+ export declare class TokenError extends Error {
7
+ readonly transient: boolean;
8
+ name: string;
9
+ constructor(message: string, transient?: boolean);
10
+ }
11
+ /** An envelope that cannot be addressed, or a serviceUrl the bot's token may not be sent to (Python's ValueError). */
12
+ export declare class UnaddressableError extends Error {
13
+ name: string;
14
+ }
15
+ /** This send did not reach Teams: the reason (never the text), how many requests were made, what Teams answered. */
16
+ export declare class UndeliverableError extends Error {
17
+ name: string;
18
+ /** The number of requests made. */
19
+ readonly attempts: number;
20
+ /** The HTTP status Teams answered with (0: none, a network or token failure). */
21
+ readonly status: number;
22
+ /** The Connector's error code, never its message. */
23
+ readonly code: string;
24
+ constructor(reason: string, details?: {
25
+ attempts?: number;
26
+ status?: number;
27
+ code?: string;
28
+ cause?: unknown;
29
+ });
30
+ }
31
+ /** The overall deadline of one operation passed (the `signal.reason` of a deadline, and what a raced wait rejects with). */
32
+ export declare class DeadlineError extends Error {
33
+ name: string;
34
+ }
@@ -0,0 +1,40 @@
1
+ /**
2
+ * Where the bot's token may be sent: the Bot Connector host rule (Microsoft's hosts, a deployment may tighten or extend
3
+ * the list), and the release gate's rule (one recording connector's origin and nothing else). Both are a
4
+ * `ServiceUrlPolicy`, injected into the request builder and the outbox; nothing here is module state.
5
+ *
6
+ * The default allow-list: `smba.trafficmanager.net` as an exact host (trafficmanager.net is Azure Traffic Manager, where
7
+ * any tenant can create `attacker.trafficmanager.net`), and suffixes only for domains in which only Microsoft can create
8
+ * names.
9
+ */
10
+ import { type Logger } from "@primusclaw/personal-agent";
11
+ export declare const DEFAULT_HOSTS: readonly string[];
12
+ export declare const DEFAULT_SUFFIXES: readonly string[];
13
+ /** Decides whether the bot's token may go to a serviceUrl. Throws UnaddressableError when it may not. */
14
+ export interface ServiceUrlPolicy {
15
+ check(serviceUrl: unknown): void;
16
+ }
17
+ /** Microsoft's Bot Connector hosts: an https address on an allowed host, port 443, without user info. */
18
+ export declare class ConnectorHosts implements ServiceUrlPolicy {
19
+ readonly hosts: readonly string[];
20
+ readonly suffixes: readonly string[];
21
+ /** `hosts`: exact host names. `suffixes`: ".example.com" allows any name under example.com, not example.com itself. */
22
+ constructor(hosts?: readonly string[], suffixes?: readonly string[]);
23
+ /** The lower-cased host of `serviceUrl` when it is an https Bot Connector address on an allowed host; throws otherwise. */
24
+ host(serviceUrl: unknown): string;
25
+ check(serviceUrl: unknown): void;
26
+ /**
27
+ * The allow-list from two ";"- or ","-separated settings. An unset setting (undefined) keeps its default; a set one
28
+ * replaces it, so an empty value allows nothing of that kind. Suffixes are written `.example.com` or `*.example.com`.
29
+ * An entry that is not a host name of at least two labels is ignored with an error in the log, so a typo narrows the
30
+ * list instead of widening it.
31
+ */
32
+ static fromSettings(hosts: string | undefined, suffixes: string | undefined, logger?: Logger): ConnectorHosts;
33
+ }
34
+ /** The production rule with the default lists. */
35
+ export declare const DEFAULT_CONNECTOR_HOSTS: ConnectorHosts;
36
+ /**
37
+ * The release gate's rule (its test entry, never production): `connectorUrl` (http://127.0.0.1:<port>, the gate's
38
+ * recording connector) is the only origin the bot's (made-up) token is sent to, and no Microsoft host is.
39
+ */
40
+ export declare function onlyConnector(connectorUrl: string): ServiceUrlPolicy;
@@ -0,0 +1,10 @@
1
+ export declare class Lanes {
2
+ private readonly lanes;
3
+ /** How many keys are held or waited for just now. */
4
+ get size(): number;
5
+ /**
6
+ * Run `work` once every earlier holder of `key` is done. With `signal`, waiting for the lane ends when it aborts (the
7
+ * work is then not run, and the holders behind still wait for the ones in front).
8
+ */
9
+ hold<T>(key: string, work: () => Promise<T>, signal?: AbortSignal): Promise<T>;
10
+ }
@@ -0,0 +1,23 @@
1
+ /** The time limits and retry budget of direct delivery: the production values, and how a caller overrides them. */
2
+ export interface ConnectorLimits {
3
+ /** One request's timeout. */
4
+ readonly requestTimeoutMs: number;
5
+ /** A typing indicator is cosmetic and holds up the messages behind it: its request and its whole send. */
6
+ readonly typingTimeoutMs: number;
7
+ /** One send and up to three retries on 429, 5xx and network errors. */
8
+ readonly maxAttempts: number;
9
+ /** The first backoff, doubled after every failure. */
10
+ readonly backoffMs: number;
11
+ /** A longer Retry-After is not waited for: the queue takes the message instead. */
12
+ readonly maxRetryAfterMs: number;
13
+ /** Everything one send does (token, requests, waits) together, enforced, not just checked. */
14
+ readonly sendDeadlineMs: number;
15
+ /** A new 1:1 conversation: one try and one retry (a person waits for the card behind it). */
16
+ readonly openAttempts: number;
17
+ readonly openRequestTimeoutMs: number;
18
+ /** Everything one createConversation does together. */
19
+ readonly openDeadlineMs: number;
20
+ /** A conversation stays on the queue until it has been quiet this long (the relay's cold start was 15-44 s). */
21
+ readonly queueStickyMs: number;
22
+ }
23
+ export declare const DEFAULT_LIMITS: ConnectorLimits;
@@ -0,0 +1,97 @@
1
+ /**
2
+ * Direct delivery to the Bot Connector, with the outbound queue (the relay Function) as the fallback.
3
+ *
4
+ * - Order: one conversation's sends are serialised in this process, first come first sent, and a retry holds the line.
5
+ * - Nothing is lost: a send Teams does not take (token unavailable, retries or the overall deadline used up, a refusal,
6
+ * an address the policy refuses) is handed to the queue, and the conversation stays on the queue until it has been
7
+ * quiet for `queueStickyMs`, so a later message cannot overtake one the relay is still delivering.
8
+ * - At least once: a request that timed out or was answered with a 5xx may have reached Teams; the retry or the queue
9
+ * hand-off can then post the message twice.
10
+ * - A delete is never handed to the queue (the relay has no delete): one Teams does not take throws DeleteUnsupportedError.
11
+ *
12
+ * Secrets and bodies are never logged: one line per send with the operation, status and latency, and the target
13
+ * conversation's id and the activity's kind (`outboundLogFields`).
14
+ */
15
+ import { type Clock, type Logger } from "@primusclaw/personal-agent";
16
+ import { type JsonObject } from "../cards/json.js";
17
+ import { type ConnectorMember, type Delivered, type DirectOutbox, type Outbox, type PublishOptions, type TeamsEnvelope } from "../outbound/outbox.js";
18
+ import { type ServiceUrlPolicy } from "./hosts.js";
19
+ import { type ConnectorLimits } from "./limits.js";
20
+ import { type Sleep } from "./retry.js";
21
+ import type { TokenSource } from "./tokens/cached.js";
22
+ export interface ConnectorOutboxOptions {
23
+ /** The bot's token source (IMDS or federated); it also fetches what a user attached. */
24
+ readonly tokens: TokenSource;
25
+ /** The outbound queue: where a send Teams did not take goes. Closed by whoever made it. */
26
+ readonly fallback: Outbox;
27
+ readonly clock: Clock;
28
+ readonly fetch?: typeof fetch;
29
+ /** The backoff wait; default `clock.sleep`. */
30
+ readonly sleep?: Sleep;
31
+ readonly logger?: Logger;
32
+ /** Where the bot's token may go; default Microsoft's Bot Connector hosts (the release gate injects its own). */
33
+ readonly policy?: ServiceUrlPolicy;
34
+ /** The activity without its reply-style extras, for a second try after a 400 (default `plainDecorations`). */
35
+ readonly plain?: (activity: JsonObject) => JsonObject | undefined;
36
+ readonly limits?: Partial<ConnectorLimits>;
37
+ }
38
+ export declare class ConnectorOutbox implements DirectOutbox {
39
+ private readonly options;
40
+ private readonly fallback;
41
+ private readonly clock;
42
+ private readonly logger;
43
+ private readonly policy;
44
+ private readonly plain;
45
+ private readonly limits;
46
+ private readonly client;
47
+ private readonly lanes;
48
+ /** conversation -> until when (monotonic ms) its sends go to the queue. */
49
+ private readonly onQueueUntil;
50
+ constructor(options: ConnectorOutboxOptions);
51
+ /** The bot's token source, which also fetches what a user attached. */
52
+ get tokens(): TokenSource;
53
+ /** How many conversations hold or wait for their line just now (0 once every send is over). */
54
+ get lanesInUse(): number;
55
+ /**
56
+ * Deliver one envelope to Teams. Delivered: Teams has it. undefined: the queue has it (or, for a typing indicator that
57
+ * could not be sent, it was dropped: nobody waits for one). An aborted `options.signal` sends nothing more and
58
+ * rejects with its reason: no retry, no queue.
59
+ */
60
+ publish(envelope: TeamsEnvelope, options?: PublishOptions): Promise<Delivered | undefined>;
61
+ private whileOnQueue;
62
+ private direct;
63
+ private plainRetry;
64
+ private notDelivered;
65
+ /** The whole of one send is bounded: a server that answers slowly, or a token source that hangs, cannot hold the line. */
66
+ private deliver;
67
+ /** Whatever goes to the queue keeps its conversation there for `queueStickyMs` more. */
68
+ private stayOnQueue;
69
+ /** Milliseconds the conversation stays on the queue (0 or less: it does not). */
70
+ private queuedFor;
71
+ /**
72
+ * One request of a Teams stream: sent once, directly, in the conversation's order, never handed to the queue (the
73
+ * relay cannot carry a stream, and a retry would break the stream's one-request-a-second limit). Throws
74
+ * StreamRefusedError when Teams did not take it, or when the conversation is on the queue just now.
75
+ */
76
+ publishStream(envelope: TeamsEnvelope, options?: PublishOptions): Promise<Delivered>;
77
+ private streamRefused;
78
+ /**
79
+ * `request` (built inside the deadline) with up to `attempts` tries under one overall deadline: the stream's
80
+ * (`send`, the send deadline) or createConversation's (`open`). Throws UndeliverableError or DeadlineError.
81
+ */
82
+ private once;
83
+ /**
84
+ * The bot's 1:1 conversation with `userId` (a `29:` id from a group activity), created if it does not exist yet.
85
+ * Throws ConversationNotOpenedError, with the status Teams answered (never a body). There is no queue fallback.
86
+ */
87
+ openPersonal(serviceUrl: string, userId: string, tenantId: string, botId: string): Promise<string>;
88
+ private notOpened;
89
+ /**
90
+ * The members of a group chat the bot is in, each as the Bot Connector gives it. One request and one retry on a
91
+ * rejected token. Throws UnaddressableError for an address the policy refuses and UndeliverableError when Teams did
92
+ * not answer. There is no queue fallback.
93
+ */
94
+ listMembers(serviceUrl: string, conversationId: string): Promise<ConnectorMember[]>;
95
+ /** Closes the token source; the fallback outbox is closed by whoever made it. */
96
+ close(): Promise<void>;
97
+ }
@@ -0,0 +1,10 @@
1
+ /** `quote(text, safe=safe)`: UTF-8, `%XX` upper case; letters, digits, `_.-~` and the `safe` characters stay. */
2
+ export declare function pyQuote(text: string, safe?: string): string;
3
+ /** `float(text)`, or undefined where Python raises ValueError. */
4
+ export declare function pyFloat(text: string): number | undefined;
5
+ /** `int(value)` for a JSON value, or undefined where Python raises (ValueError, TypeError, OverflowError). */
6
+ export declare function pyInt(value: unknown): number | undefined;
7
+ /** Python's truthiness of a JSON value. */
8
+ export declare function pyTruthy(value: unknown): boolean;
9
+ /** `text.rstrip("/")`. */
10
+ export declare function rstripSlash(text: string): string;
@@ -0,0 +1,21 @@
1
+ import { type JsonObject } from "../cards/json.js";
2
+ import { type ServiceUrlPolicy } from "./hosts.js";
3
+ export interface ConnectorRequest {
4
+ readonly method: "GET" | "POST" | "PUT" | "DELETE";
5
+ readonly url: string;
6
+ /** undefined: the request has no body (a delete, a read). */
7
+ readonly payload: JsonObject | undefined;
8
+ }
9
+ /**
10
+ * The Connector call for one outbox envelope. `send` posts a new activity, `reply` posts into the thread of the
11
+ * reference's activity, `update` replaces the activity `activity_id`, `delete` removes it (no body). Throws
12
+ * UnaddressableError for an envelope that cannot be addressed or a serviceUrl the policy refuses.
13
+ */
14
+ export declare function buildRequest(envelope: JsonObject, policy?: ServiceUrlPolicy): ConnectorRequest;
15
+ /**
16
+ * The Connector call that creates (or returns) the bot's 1:1 conversation with one user: POST {serviceUrl}/v3/conversations
17
+ * with the user as the only member. The answer's `id` is the conversation to post into.
18
+ */
19
+ export declare function buildCreateConversation(serviceUrl: string, userId: string, tenantId: string, botId: string, policy?: ServiceUrlPolicy): ConnectorRequest;
20
+ /** GET {serviceUrl}/v3/conversations/{id}/members. */
21
+ export declare function buildListMembers(serviceUrl: string, conversationId: string, policy?: ServiceUrlPolicy): ConnectorRequest;
@@ -0,0 +1,9 @@
1
+ import { type JsonObject } from "../cards/json.js";
2
+ /** The `id` of an answer, or undefined when it has none. */
3
+ export declare function answerId(text: string): string | undefined;
4
+ /** The Connector's error code (for example BotNotInConversationRoster), at most 60 characters; "" when there is none. */
5
+ export declare function errorCode(text: string): string;
6
+ /** A Retry-After in milliseconds; undefined for none, an HTTP date or junk (the backoff then applies). */
7
+ export declare function retryAfterMs(header: string | null): number | undefined;
8
+ /** The member objects of a member list answer; undefined when it is not JSON. */
9
+ export declare function memberList(text: string): JsonObject[] | undefined;
@@ -0,0 +1,57 @@
1
+ /**
2
+ * One Bot Connector request with its retries: the bot's token, the request under its own timeout, one fresh token after
3
+ * a 401, a retry with doubling backoff (or the server's Retry-After) on 429, 5xx, a network error or a busy token
4
+ * source, within an attempt budget and an overall deadline. Throws UndeliverableError when Teams did not take it.
5
+ */
6
+ import { type Clock, type Logger } from "@primusclaw/personal-agent";
7
+ import type { ConnectorLimits } from "./limits.js";
8
+ import type { ConnectorRequest } from "./request.js";
9
+ import type { TokenSource } from "./tokens/cached.js";
10
+ export type Sleep = (ms: number, signal?: AbortSignal) => Promise<void>;
11
+ export interface ClientDeps {
12
+ readonly tokens: TokenSource;
13
+ readonly fetch: typeof fetch;
14
+ readonly clock: Clock;
15
+ readonly sleep: Sleep;
16
+ readonly logger: Logger;
17
+ readonly limits: ConnectorLimits;
18
+ }
19
+ /** What Teams answered: the `id` of the answer, the status, the number of requests made. */
20
+ export interface Answer {
21
+ readonly id: string | undefined;
22
+ readonly status: number;
23
+ readonly attempts: number;
24
+ }
25
+ export interface ExecuteOptions {
26
+ readonly maxAttempts: number;
27
+ readonly timeoutMs: number;
28
+ /** A retry whose wait would end after this budget is not made. */
29
+ readonly budgetMs: number;
30
+ /** Ends every wait and request: the overall deadline, combined with the caller's signal. */
31
+ readonly deadline: AbortSignal;
32
+ /** The caller's own signal: once it aborts, the call rejects with its reason and nothing is retried. */
33
+ readonly cancel?: AbortSignal | undefined;
34
+ /** The number of the request in progress, readable when the deadline cuts the call off. */
35
+ readonly progress: {
36
+ attempts: number;
37
+ };
38
+ }
39
+ /** One request's outcome: an answer, or a network failure (the request may or may not have reached Teams). */
40
+ export type Exchange = {
41
+ readonly status: number;
42
+ readonly text: string;
43
+ readonly retryAfter: string | null;
44
+ } | {
45
+ readonly network: string;
46
+ };
47
+ export declare class ConnectorClient {
48
+ private readonly deps;
49
+ constructor(deps: ClientDeps);
50
+ /** One request as it is, with no retry: what Teams answered, or the network failure. */
51
+ send(request: ConnectorRequest, token: string, timeoutMs: number, signal?: AbortSignal): Promise<Exchange>;
52
+ /** The request with its retries; throws UndeliverableError, or the deadline's or the caller's reason when they end it. */
53
+ execute(request: ConnectorRequest, options: ExecuteOptions): Promise<Answer>;
54
+ private attempt;
55
+ /** The error to end the call with: the caller's reason, the deadline, or `error` itself when neither stopped it. */
56
+ private stopped;
57
+ }
@@ -0,0 +1,18 @@
1
+ /**
2
+ * Time limits as AbortSignals on the injected Clock: a timer that aborts its signal after a while (a request's timeout,
3
+ * an operation's overall deadline), and a race that ends a wait the moment a signal aborts, whether or not the thing
4
+ * waited for listens to the signal.
5
+ */
6
+ import type { Clock } from "@primusclaw/personal-agent";
7
+ export interface Timer {
8
+ /** Aborts with a DeadlineError when the time is up, or with the parent's reason when the parent aborts first. */
9
+ readonly signal: AbortSignal;
10
+ /** Stop the timer (the time it waits for is no longer needed). */
11
+ dispose(): void;
12
+ }
13
+ /** A signal that aborts after `ms` of `clock`, or when `parent` does. Dispose it once the work it limits is over. */
14
+ export declare function startTimer(clock: Clock, ms: number, reason: string, parent?: AbortSignal): Timer;
15
+ /** `work`, ended with the signal's reason as soon as `signal` aborts (the work may keep running; its result is dropped). */
16
+ export declare function raceAbort<T>(signal: AbortSignal, work: Promise<T>): Promise<T>;
17
+ /** The error a signal aborted with. */
18
+ export declare function reasonOf(signal: AbortSignal): Error;
@@ -0,0 +1,38 @@
1
+ /**
2
+ * The client assertion of workload identity federation: the RSA key that signs it, its key id (the RFC 7638 thumbprint
3
+ * the published JWKS carries), and the signed RS256 JWT itself (`iss`/`sub` as registered in the identity's federated
4
+ * credential, audience api://AzureADTokenExchange).
5
+ */
6
+ import { type KeyObject } from "node:crypto";
7
+ /** The audience a federated identity credential accepts. */
8
+ export declare const ASSERTION_AUDIENCE = "api://AzureADTokenExchange";
9
+ export declare const ASSERTION_TYPE = "urn:ietf:params:oauth:client-assertion-type:jwt-bearer";
10
+ /** 10 minutes in all, back-dated by ASSERTION_SKEW_SECONDS for clock skew. */
11
+ export declare const ASSERTION_LIFETIME_SECONDS = 600;
12
+ export declare const ASSERTION_SKEW_SECONDS = 60;
13
+ /** The key is not an unencrypted RSA private key in PEM (Python's ValueError). */
14
+ export declare class AssertionKeyError extends Error {
15
+ name: string;
16
+ }
17
+ export interface AssertionKey {
18
+ readonly key: KeyObject;
19
+ /** The RFC 7638 thumbprint of the public key: the `kid`. */
20
+ readonly kid: string;
21
+ }
22
+ /** The signing key and its key id; throws AssertionKeyError for anything but an unencrypted RSA private key in PEM. */
23
+ export declare function loadAssertionKey(pem: string | Uint8Array): AssertionKey;
24
+ /** The RFC 7638 SHA-256 thumbprint of an RSA public key given as its JWK members (base64url, no leading zero bytes). */
25
+ export declare function jwkThumbprint(jwk: {
26
+ readonly n: string;
27
+ readonly e: string;
28
+ }): string;
29
+ export interface AssertionClaims {
30
+ readonly issuer: string;
31
+ readonly subject: string;
32
+ /** Wall-clock seconds since the epoch. */
33
+ readonly now: number;
34
+ /** The token id; a fresh UUID by default: an assertion is never reused. */
35
+ readonly jti?: string;
36
+ }
37
+ /** A fresh signed assertion, valid ASSERTION_LIFETIME_SECONDS in all (back-dated for clock skew). */
38
+ export declare function signAssertion(signer: AssertionKey, claims: AssertionClaims): string;
@@ -0,0 +1,33 @@
1
+ import type { Clock } from "@primusclaw/personal-agent";
2
+ /** A token is replaced this long before it expires. */
3
+ export declare const TOKEN_REFRESH_MARGIN_MS = 300000;
4
+ /** What the outbox needs of the bot's token source. */
5
+ export interface TokenSource {
6
+ /** The bearer token; throws TokenError. With `signal`, the wait and the fetch end when it aborts. */
7
+ get(signal?: AbortSignal): Promise<string>;
8
+ /** Forget `token` (the Connector refused it). A newer one another caller already fetched is kept. */
9
+ invalidate(token: string): void;
10
+ close(): Promise<void>;
11
+ }
12
+ export declare abstract class CachedTokenProvider implements TokenSource {
13
+ protected readonly clock: Clock;
14
+ private token;
15
+ private expiresAt;
16
+ private readonly lock;
17
+ protected constructor(clock: Clock);
18
+ get(signal?: AbortSignal): Promise<string>;
19
+ /** Milliseconds the cached token is still handed out for (0 when there is none). */
20
+ validForMs(): number;
21
+ invalidate(token: string): void;
22
+ close(): Promise<void>;
23
+ private fresh;
24
+ /** Cache `token` for `expiresIn` seconds less the margin (half its life when it is short). */
25
+ protected keep(token: string, expiresIn: number): void;
26
+ /** Fetch a token, `keep` it and return it; throws TokenError. */
27
+ protected abstract fetchToken(signal?: AbortSignal): Promise<string>;
28
+ }
29
+ /** The token and its lifetime in seconds from a token endpoint's JSON answer, or undefined when it has no usable token. */
30
+ export declare function parseTokenAnswer(text: string): {
31
+ token: string;
32
+ expiresIn: number;
33
+ } | undefined;
@@ -0,0 +1,41 @@
1
+ import { type Clock, type Logger } from "@primusclaw/personal-agent";
2
+ import { CachedTokenProvider } from "./cached.js";
3
+ export declare const ENTRA_TOKEN_HOST = "https://login.microsoftonline.com";
4
+ export declare const BOT_CONNECTOR_SCOPE = "https://api.botframework.com/.default";
5
+ export declare const ENTRA_TIMEOUT_MS = 10000;
6
+ export interface FederatedOptions {
7
+ readonly clientId: string;
8
+ readonly tenantId: string;
9
+ /** The PEM of the RSA key that signs the assertion. */
10
+ readonly keyPem: string | Uint8Array;
11
+ /** The https issuer registered in the federated credential. */
12
+ readonly issuer: string;
13
+ readonly subject: string;
14
+ readonly clock: Clock;
15
+ readonly fetch?: typeof fetch;
16
+ readonly logger?: Logger;
17
+ /** The token endpoint; default Entra ID's for the tenant. */
18
+ readonly url?: string;
19
+ readonly scope?: string;
20
+ }
21
+ export declare class FederatedTokenProvider extends CachedTokenProvider {
22
+ private readonly options;
23
+ readonly source = "federated";
24
+ readonly scope: string;
25
+ private readonly signer;
26
+ private readonly fetch;
27
+ private readonly logger;
28
+ private readonly url;
29
+ /** Throws (AssertionKeyError for the key, Error for a missing or non-https setting) rather than at the first token. */
30
+ constructor(options: FederatedOptions);
31
+ get keyId(): string;
32
+ get clientId(): string;
33
+ /** A fresh signed assertion. */
34
+ assertion(): string;
35
+ protected fetchToken(signal?: AbortSignal): Promise<string>;
36
+ }
37
+ /**
38
+ * " (error: AADSTS1,AADSTS2)" from an Entra error answer: its `error` and up to three `error_codes`, which say what did
39
+ * not match and carry nothing secret. "" when it has neither or is not the expected JSON.
40
+ */
41
+ export declare function entraCodes(text: string): string;