@primusclaw/personal-agent-teams 0.2.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -4179,19 +4179,31 @@ function busNamespace(raw) {
4179
4179
  }
4180
4180
  return value;
4181
4181
  }
4182
+ function tokenSourceOf(env, secretSet) {
4183
+ const fallback = secretSet ? "secret" : "imds";
4184
+ return oneOf(env, "BOT_TOKEN_SOURCE", ["imds", "federated", "secret"], fallback);
4185
+ }
4182
4186
  function botFromEnv(env, mode) {
4183
- const tokenSource = oneOf(env, "BOT_TOKEN_SOURCE", ["imds", "federated"], "imds");
4187
+ const secretSet = get(env, "BOT_CLIENT_SECRET") !== "";
4188
+ const tokenSource = tokenSourceOf(env, secretSet);
4184
4189
  const federated = tokenSource === "federated";
4185
- if (federated && mode !== "direct")
4186
- throw new TeamsConfigError("BOT_TOKEN_SOURCE=federated needs OUTBOUND_MODE=direct");
4187
- return {
4190
+ const secret = tokenSource === "secret";
4191
+ if ((federated || secret) && mode !== "direct") {
4192
+ const what = get(env, "BOT_TOKEN_SOURCE") ? `BOT_TOKEN_SOURCE=${tokenSource}` : "BOT_CLIENT_SECRET";
4193
+ throw new TeamsConfigError(`${what} needs OUTBOUND_MODE=direct`);
4194
+ }
4195
+ const settings2 = {
4188
4196
  tokenSource,
4189
- msiClientId: mode === "direct" ? required(env, "BOT_MSI_CLIENT_ID") : "",
4190
- tenantId: federated ? required(env, "BOT_TENANT_ID") : get(env, "BOT_TENANT_ID"),
4197
+ msiClientId: mode === "direct" && !secret ? required(env, "BOT_MSI_CLIENT_ID") : get(env, "BOT_MSI_CLIENT_ID"),
4198
+ clientId: secret ? required(env, "BOT_CLIENT_ID") : get(env, "BOT_CLIENT_ID"),
4199
+ clientSecretIgnored: secretSet && !secret,
4200
+ tenantId: federated || secret ? required(env, "BOT_TENANT_ID") : get(env, "BOT_TENANT_ID"),
4191
4201
  assertionKeyFile: federated ? required(env, "BOT_ASSERTION_KEY_FILE") : get(env, "BOT_ASSERTION_KEY_FILE"),
4192
4202
  assertionIssuer: federated ? httpsIssuer(env) : "",
4193
4203
  assertionSubject: federated ? required(env, "BOT_ASSERTION_SUBJECT") : get(env, "BOT_ASSERTION_SUBJECT")
4194
4204
  };
4205
+ const clientSecret = secret ? required(env, "BOT_CLIENT_SECRET") : "";
4206
+ return Object.defineProperty(settings2, "clientSecret", { value: clientSecret, enumerable: false });
4195
4207
  }
4196
4208
  function wholeNumber(env, name, fallback) {
4197
4209
  const raw = get(env, name);
@@ -5057,7 +5069,7 @@ import {
5057
5069
 
5058
5070
  // packages/teams/src/assembly/outbound.ts
5059
5071
  import { readFileSync as readFileSync2 } from "node:fs";
5060
- import { silentLogger as silentLogger16 } from "@primusclaw/personal-agent";
5072
+ import { silentLogger as silentLogger17 } from "@primusclaw/personal-agent";
5061
5073
 
5062
5074
  // packages/teams/src/connector/outbox.ts
5063
5075
  import { pyStr as pyStr8, silentLogger as silentLogger12 } from "@primusclaw/personal-agent";
@@ -5613,8 +5625,72 @@ function buildRequestLazily(envelope2, policy) {
5613
5625
  return () => buildRequest(envelope2, policy);
5614
5626
  }
5615
5627
 
5616
- // packages/teams/src/connector/tokens/imds.ts
5628
+ // packages/teams/src/connector/tokens/client-secret.ts
5617
5629
  import { silentLogger as silentLogger13 } from "@primusclaw/personal-agent";
5630
+ var ClientSecretTokenProvider = class extends CachedTokenProvider {
5631
+ source = "secret";
5632
+ scope;
5633
+ clientId;
5634
+ tenantId;
5635
+ #secret;
5636
+ fetch;
5637
+ logger;
5638
+ url;
5639
+ /** Throws (an Error naming the missing setting, never a value) rather than at the first token. */
5640
+ constructor(options) {
5641
+ super(options.clock);
5642
+ const named = [
5643
+ ["client id", options.clientId],
5644
+ ["tenant id", options.tenantId],
5645
+ ["client secret", options.clientSecret]
5646
+ ];
5647
+ for (const [name, value] of named) {
5648
+ if (!value) throw new Error(`the client secret token needs the ${name}`);
5649
+ }
5650
+ this.clientId = options.clientId;
5651
+ this.tenantId = options.tenantId;
5652
+ this.#secret = options.clientSecret;
5653
+ this.fetch = options.fetch ?? globalThis.fetch;
5654
+ this.logger = options.logger ?? silentLogger13;
5655
+ this.url = options.url || `${ENTRA_TOKEN_HOST}/${pyQuote(options.tenantId, "")}/oauth2/v2.0/token`;
5656
+ this.scope = options.scope ?? BOT_CONNECTOR_SCOPE;
5657
+ }
5658
+ async fetchToken(signal) {
5659
+ const form = new URLSearchParams({
5660
+ grant_type: "client_credentials",
5661
+ client_id: this.clientId,
5662
+ client_secret: this.#secret,
5663
+ scope: this.scope
5664
+ });
5665
+ const { status, text: text4 } = await tokenRequest(
5666
+ { fetch: this.fetch, clock: this.clock },
5667
+ "Entra ID",
5668
+ this.url,
5669
+ { method: "POST", headers: { "content-type": "application/x-www-form-urlencoded" }, body: form.toString() },
5670
+ ENTRA_TIMEOUT_MS,
5671
+ signal
5672
+ );
5673
+ if (status !== 200) {
5674
+ throw new TokenError(`Entra ID answered ${String(status)}${entraCodes(text4)}`, status === 429 || status >= 500);
5675
+ }
5676
+ const answer = parseTokenAnswer(text4);
5677
+ if (answer === void 0) throw new TokenError("Entra ID answered without a usable token");
5678
+ this.keep(answer.token, answer.expiresIn);
5679
+ if (this.scope === BOT_CONNECTOR_SCOPE) {
5680
+ this.logger.info("bot connector token fetched with the client secret", { validForS: answer.expiresIn });
5681
+ } else {
5682
+ this.logger.info("token fetched with the client secret", {
5683
+ scope: this.scope,
5684
+ clientId: this.clientId,
5685
+ validForS: answer.expiresIn
5686
+ });
5687
+ }
5688
+ return answer.token;
5689
+ }
5690
+ };
5691
+
5692
+ // packages/teams/src/connector/tokens/imds.ts
5693
+ import { silentLogger as silentLogger14 } from "@primusclaw/personal-agent";
5618
5694
  var BOT_CONNECTOR_RESOURCE = "https://api.botframework.com";
5619
5695
  var IMDS_TOKEN_URL = "http://169.254.169.254/metadata/identity/oauth2/token";
5620
5696
  var IMDS_API_VERSION = "2018-02-01";
@@ -5625,7 +5701,7 @@ var ImdsTokenProvider = class extends CachedTokenProvider {
5625
5701
  this.clientId = clientId;
5626
5702
  if (!clientId) throw new Error("the managed identity's client id is required");
5627
5703
  this.fetch = options.fetch ?? globalThis.fetch;
5628
- this.logger = options.logger ?? silentLogger13;
5704
+ this.logger = options.logger ?? silentLogger14;
5629
5705
  this.url = options.url ?? IMDS_TOKEN_URL;
5630
5706
  }
5631
5707
  clientId;
@@ -5659,9 +5735,9 @@ var ImdsTokenProvider = class extends CachedTokenProvider {
5659
5735
  };
5660
5736
 
5661
5737
  // packages/teams/src/gate/no-queue.ts
5662
- import { silentLogger as silentLogger14 } from "@primusclaw/personal-agent";
5738
+ import { silentLogger as silentLogger15 } from "@primusclaw/personal-agent";
5663
5739
  var NoQueue = class {
5664
- constructor(logger = silentLogger14) {
5740
+ constructor(logger = silentLogger15) {
5665
5741
  this.logger = logger;
5666
5742
  }
5667
5743
  logger;
@@ -5754,7 +5830,7 @@ function azureBusClient(connection, lockRenewalMs) {
5754
5830
  }
5755
5831
 
5756
5832
  // packages/teams/src/servicebus/outbox.ts
5757
- import { errorName as errorName7, pyJsonDumps, silentLogger as silentLogger15 } from "@primusclaw/personal-agent";
5833
+ import { errorName as errorName7, pyJsonDumps, silentLogger as silentLogger16 } from "@primusclaw/personal-agent";
5758
5834
  var IDLE_REOPEN_MS = 24e4;
5759
5835
  var ServiceBusOutbox = class {
5760
5836
  constructor(client, queue, clock, logger) {
@@ -5763,7 +5839,7 @@ var ServiceBusOutbox = class {
5763
5839
  this.clock = clock;
5764
5840
  this.sender = client.sender(queue);
5765
5841
  this.usedAt = clock.monotonicMs();
5766
- this.logger = logger ?? silentLogger15;
5842
+ this.logger = logger ?? silentLogger16;
5767
5843
  }
5768
5844
  client;
5769
5845
  queue;
@@ -5812,8 +5888,23 @@ var StartupError = class extends Error {
5812
5888
  };
5813
5889
  function botTokenSource(settings2, deps) {
5814
5890
  const { bot } = settings2;
5815
- const logger = deps.logger ?? silentLogger16;
5891
+ const logger = deps.logger ?? silentLogger17;
5816
5892
  const base2 = { clock: deps.clock, logger, ...deps.fetch ? { fetch: deps.fetch } : {} };
5893
+ if (bot.clientSecretIgnored) {
5894
+ logger.warn("BOT_CLIENT_SECRET is set but not used: BOT_TOKEN_SOURCE names another source", {
5895
+ tokenSource: bot.tokenSource
5896
+ });
5897
+ }
5898
+ if (bot.tokenSource === "secret") {
5899
+ const provider = new ClientSecretTokenProvider({
5900
+ ...base2,
5901
+ clientId: bot.clientId,
5902
+ tenantId: bot.tenantId,
5903
+ clientSecret: bot.clientSecret
5904
+ });
5905
+ logger.info("bot token source: secret", { clientId: bot.clientId, tenantId: bot.tenantId });
5906
+ return provider;
5907
+ }
5817
5908
  if (bot.tokenSource !== "federated") {
5818
5909
  logger.info("bot token source: imds", { clientId: bot.msiClientId });
5819
5910
  return new ImdsTokenProvider(bot.msiClientId, base2);
@@ -5861,7 +5952,7 @@ function busConnections(settings2, credential) {
5861
5952
  function gateOutbound(gate, deps) {
5862
5953
  const tokens = new GateToken(gate.runId);
5863
5954
  const policy = onlyConnector(gate.connectorUrl);
5864
- (deps.logger ?? silentLogger16).warn("release gate test entry: outbound to the recording connector only; no queue", {
5955
+ (deps.logger ?? silentLogger17).warn("release gate test entry: outbound to the recording connector only; no queue", {
5865
5956
  runId: gate.runId
5866
5957
  });
5867
5958
  const outbox = new ConnectorOutbox({
@@ -5879,7 +5970,7 @@ function productionOutbound(settings2, outbound, deps) {
5879
5970
  if (settings2.outboundMode !== "direct") {
5880
5971
  return { outbox: queue, tokens: void 0, policy: DEFAULT_CONNECTOR_HOSTS, close: () => queue.close() };
5881
5972
  }
5882
- (deps.logger ?? silentLogger16).info("outbound mode: direct to the Bot Connector (the queue is the fallback)");
5973
+ (deps.logger ?? silentLogger17).info("outbound mode: direct to the Bot Connector (the queue is the fallback)");
5883
5974
  const tokens = botTokenSource(settings2, deps);
5884
5975
  const outbox = new ConnectorOutbox({
5885
5976
  tokens,
@@ -6231,7 +6322,7 @@ function runFollowUps(base2, errors) {
6231
6322
  }
6232
6323
  };
6233
6324
  }
6234
- function proactiveParts(base2, style, assistant, errors) {
6325
+ function proactiveParts(base2, style, assistant, errors, router) {
6235
6326
  const { store, claw, surface, settings: settings2 } = base2;
6236
6327
  const deps = {
6237
6328
  store,
@@ -6260,11 +6351,36 @@ function proactiveParts(base2, style, assistant, errors) {
6260
6351
  clock: base2.clock,
6261
6352
  logger: base2.logger,
6262
6353
  publicEvent: (event) => publicRunEvent(event, errors, (text4) => looksLikeServiceError(text4) || looksInternal(text4)),
6263
- botName: "Clawy"
6354
+ botName: "Clawy",
6355
+ ...router === void 0 ? {} : { identityAfterRefusal: identityAfterRefusal(base2, router) }
6264
6356
  };
6265
6357
  const proactive = new Proactive(deps);
6266
6358
  return { proactive, release: new Release(deps, proactive) };
6267
6359
  }
6360
+ function identityAfterRefusal(base2, router) {
6361
+ return async (userId, conversation, turn8) => {
6362
+ const { store } = base2;
6363
+ const once = `${IDENTITY_REFUSED_PREFIX}${userId}:${turn8}`;
6364
+ if (!turn8) return;
6365
+ const claim = store.idempotency.claimEvent(once);
6366
+ if (claim.state !== "claimed") return;
6367
+ let sent = false;
6368
+ try {
6369
+ const person = {
6370
+ id: userId,
6371
+ channelUserId: store.members.channelIdOf(userId) ?? "",
6372
+ name: store.members.memberName(userId) ?? "",
6373
+ email: ""
6374
+ };
6375
+ const r = router();
6376
+ sent = await r.ctx.credentials.identityAfterRefusal(r.chat(person, conversation));
6377
+ } finally {
6378
+ if (sent) store.idempotency.finishEvent(once);
6379
+ else store.idempotency.releaseEvent(once, claim.holder);
6380
+ }
6381
+ };
6382
+ }
6383
+ var IDENTITY_REFUSED_PREFIX = "identity-refused:";
6268
6384
  function proactiveHold(parts) {
6269
6385
  return {
6270
6386
  muted: (userId) => parts.proactive.muted(userId) ?? null,
@@ -6876,7 +6992,7 @@ function routerDeps(base2, built, errors) {
6876
6992
  connectionsText: whoamiConnections(plugins.integrations),
6877
6993
  reportView: (userId, scope) => w8.reportView(userId, scope),
6878
6994
  note: noteFactory,
6879
- subscriptions: subs === void 0 ? void 0 : { ensure: (u) => subs.ensure(u), remove: (u, key) => subs.remove(u, key) },
6995
+ subscriptions: subs === void 0 ? void 0 : { ensure: (u, credential) => subs.ensure(u, credential), remove: (u, key) => subs.remove(u, key) },
6880
6996
  handlers: built.handlers,
6881
6997
  integrations: plugins.integrations
6882
6998
  };
@@ -7002,7 +7118,7 @@ function buildFeatures(given) {
7002
7118
  hooks,
7003
7119
  reviewHandoff: (userId, event) => lateReview.handoff?.take(userId, event) ?? "dropped"
7004
7120
  });
7005
- const proactive = proactiveParts(base2, teams.style, assistant, errors);
7121
+ const proactive = proactiveParts(base2, teams.style, assistant, errors, get3);
7006
7122
  const reach = followReach(proactive, base2);
7007
7123
  const remote = remoteAgents(base2, { switches, guard, reach, errors, directChat: assistant.directChat, hooks });
7008
7124
  const w8 = w8Parts(base2, { briefEnabled: switches.brief, assistantOn: (userId) => assistant.chat.on(userId) });
@@ -7124,7 +7240,7 @@ function metricsRoutes(render) {
7124
7240
  }
7125
7241
 
7126
7242
  // packages/teams/src/assembly/inbound.ts
7127
- import { silentLogger as silentLogger18 } from "@primusclaw/personal-agent";
7243
+ import { silentLogger as silentLogger19 } from "@primusclaw/personal-agent";
7128
7244
 
7129
7245
  // packages/teams/src/activity/inbound/actions.ts
7130
7246
  import { cpHead as cpHead4, pyStr as pyStr11 } from "@primusclaw/personal-agent";
@@ -8108,7 +8224,7 @@ import {
8108
8224
  err as err4,
8109
8225
  ok as ok4,
8110
8226
  pyStr as pyStr19,
8111
- silentLogger as silentLogger17
8227
+ silentLogger as silentLogger18
8112
8228
  } from "@primusclaw/personal-agent";
8113
8229
  function wireReferenceOf(activity) {
8114
8230
  const ref = {
@@ -8140,7 +8256,7 @@ function base(activity, sender) {
8140
8256
  };
8141
8257
  }
8142
8258
  function messageOf(activity, sender, options) {
8143
- const logger = options.logger ?? silentLogger17;
8259
+ const logger = options.logger ?? silentLogger18;
8144
8260
  const personal = isPersonal(activity);
8145
8261
  const found = quotesOf(activity);
8146
8262
  const attached = inboundFiles(activity);
@@ -8212,7 +8328,7 @@ function text3(value) {
8212
8328
  return typeof value === "number" && value !== 0 ? String(value) : "";
8213
8329
  }
8214
8330
  function inboundHandler(parts) {
8215
- const logger = parts.logger ?? silentLogger18;
8331
+ const logger = parts.logger ?? silentLogger19;
8216
8332
  return async (body) => {
8217
8333
  if (body["type"] === DELIVERED) {
8218
8334
  const activityId = text3(body["activity_id"]);
@@ -8415,7 +8531,7 @@ import {
8415
8531
  pyStr as pyStr20,
8416
8532
  pyStrip as pyStrip20,
8417
8533
  SecretsUnavailable as SecretsUnavailable2,
8418
- silentLogger as silentLogger19
8534
+ silentLogger as silentLogger20
8419
8535
  } from "@primusclaw/personal-agent";
8420
8536
 
8421
8537
  // packages/teams/src/azure/keyvault-config.ts
@@ -8511,7 +8627,7 @@ var KeyVaultSecretSource = class {
8511
8627
  this.credential = credential;
8512
8628
  this.options = options;
8513
8629
  this.fetch = options.fetch ?? globalThis.fetch;
8514
- this.logger = options.logger ?? silentLogger19;
8630
+ this.logger = options.logger ?? silentLogger20;
8515
8631
  this.sleep = options.sleep ?? ((ms, signal) => options.clock.sleep(ms, signal));
8516
8632
  }
8517
8633
  url;
package/dist/main.js CHANGED
@@ -680,19 +680,31 @@ function busNamespace(raw) {
680
680
  }
681
681
  return value;
682
682
  }
683
+ function tokenSourceOf(env, secretSet) {
684
+ const fallback = secretSet ? "secret" : "imds";
685
+ return oneOf(env, "BOT_TOKEN_SOURCE", ["imds", "federated", "secret"], fallback);
686
+ }
683
687
  function botFromEnv(env, mode) {
684
- const tokenSource = oneOf(env, "BOT_TOKEN_SOURCE", ["imds", "federated"], "imds");
688
+ const secretSet = get(env, "BOT_CLIENT_SECRET") !== "";
689
+ const tokenSource = tokenSourceOf(env, secretSet);
685
690
  const federated = tokenSource === "federated";
686
- if (federated && mode !== "direct")
687
- throw new TeamsConfigError("BOT_TOKEN_SOURCE=federated needs OUTBOUND_MODE=direct");
688
- return {
691
+ const secret = tokenSource === "secret";
692
+ if ((federated || secret) && mode !== "direct") {
693
+ const what = get(env, "BOT_TOKEN_SOURCE") ? `BOT_TOKEN_SOURCE=${tokenSource}` : "BOT_CLIENT_SECRET";
694
+ throw new TeamsConfigError(`${what} needs OUTBOUND_MODE=direct`);
695
+ }
696
+ const settings2 = {
689
697
  tokenSource,
690
- msiClientId: mode === "direct" ? required(env, "BOT_MSI_CLIENT_ID") : "",
691
- tenantId: federated ? required(env, "BOT_TENANT_ID") : get(env, "BOT_TENANT_ID"),
698
+ msiClientId: mode === "direct" && !secret ? required(env, "BOT_MSI_CLIENT_ID") : get(env, "BOT_MSI_CLIENT_ID"),
699
+ clientId: secret ? required(env, "BOT_CLIENT_ID") : get(env, "BOT_CLIENT_ID"),
700
+ clientSecretIgnored: secretSet && !secret,
701
+ tenantId: federated || secret ? required(env, "BOT_TENANT_ID") : get(env, "BOT_TENANT_ID"),
692
702
  assertionKeyFile: federated ? required(env, "BOT_ASSERTION_KEY_FILE") : get(env, "BOT_ASSERTION_KEY_FILE"),
693
703
  assertionIssuer: federated ? httpsIssuer(env) : "",
694
704
  assertionSubject: federated ? required(env, "BOT_ASSERTION_SUBJECT") : get(env, "BOT_ASSERTION_SUBJECT")
695
705
  };
706
+ const clientSecret = secret ? required(env, "BOT_CLIENT_SECRET") : "";
707
+ return Object.defineProperty(settings2, "clientSecret", { value: clientSecret, enumerable: false });
696
708
  }
697
709
  function wholeNumber(env, name, fallback) {
698
710
  const raw = get(env, name);
@@ -4997,7 +5009,7 @@ import {
4997
5009
 
4998
5010
  // packages/teams/src/assembly/outbound.ts
4999
5011
  import { readFileSync as readFileSync2 } from "node:fs";
5000
- import { silentLogger as silentLogger16 } from "@primusclaw/personal-agent";
5012
+ import { silentLogger as silentLogger17 } from "@primusclaw/personal-agent";
5001
5013
 
5002
5014
  // packages/teams/src/connector/outbox.ts
5003
5015
  import { pyStr as pyStr8, silentLogger as silentLogger12 } from "@primusclaw/personal-agent";
@@ -5553,8 +5565,72 @@ function buildRequestLazily(envelope2, policy) {
5553
5565
  return () => buildRequest(envelope2, policy);
5554
5566
  }
5555
5567
 
5556
- // packages/teams/src/connector/tokens/imds.ts
5568
+ // packages/teams/src/connector/tokens/client-secret.ts
5557
5569
  import { silentLogger as silentLogger13 } from "@primusclaw/personal-agent";
5570
+ var ClientSecretTokenProvider = class extends CachedTokenProvider {
5571
+ source = "secret";
5572
+ scope;
5573
+ clientId;
5574
+ tenantId;
5575
+ #secret;
5576
+ fetch;
5577
+ logger;
5578
+ url;
5579
+ /** Throws (an Error naming the missing setting, never a value) rather than at the first token. */
5580
+ constructor(options) {
5581
+ super(options.clock);
5582
+ const named = [
5583
+ ["client id", options.clientId],
5584
+ ["tenant id", options.tenantId],
5585
+ ["client secret", options.clientSecret]
5586
+ ];
5587
+ for (const [name, value] of named) {
5588
+ if (!value) throw new Error(`the client secret token needs the ${name}`);
5589
+ }
5590
+ this.clientId = options.clientId;
5591
+ this.tenantId = options.tenantId;
5592
+ this.#secret = options.clientSecret;
5593
+ this.fetch = options.fetch ?? globalThis.fetch;
5594
+ this.logger = options.logger ?? silentLogger13;
5595
+ this.url = options.url || `${ENTRA_TOKEN_HOST}/${pyQuote(options.tenantId, "")}/oauth2/v2.0/token`;
5596
+ this.scope = options.scope ?? BOT_CONNECTOR_SCOPE;
5597
+ }
5598
+ async fetchToken(signal) {
5599
+ const form = new URLSearchParams({
5600
+ grant_type: "client_credentials",
5601
+ client_id: this.clientId,
5602
+ client_secret: this.#secret,
5603
+ scope: this.scope
5604
+ });
5605
+ const { status, text: text4 } = await tokenRequest(
5606
+ { fetch: this.fetch, clock: this.clock },
5607
+ "Entra ID",
5608
+ this.url,
5609
+ { method: "POST", headers: { "content-type": "application/x-www-form-urlencoded" }, body: form.toString() },
5610
+ ENTRA_TIMEOUT_MS,
5611
+ signal
5612
+ );
5613
+ if (status !== 200) {
5614
+ throw new TokenError(`Entra ID answered ${String(status)}${entraCodes(text4)}`, status === 429 || status >= 500);
5615
+ }
5616
+ const answer = parseTokenAnswer(text4);
5617
+ if (answer === void 0) throw new TokenError("Entra ID answered without a usable token");
5618
+ this.keep(answer.token, answer.expiresIn);
5619
+ if (this.scope === BOT_CONNECTOR_SCOPE) {
5620
+ this.logger.info("bot connector token fetched with the client secret", { validForS: answer.expiresIn });
5621
+ } else {
5622
+ this.logger.info("token fetched with the client secret", {
5623
+ scope: this.scope,
5624
+ clientId: this.clientId,
5625
+ validForS: answer.expiresIn
5626
+ });
5627
+ }
5628
+ return answer.token;
5629
+ }
5630
+ };
5631
+
5632
+ // packages/teams/src/connector/tokens/imds.ts
5633
+ import { silentLogger as silentLogger14 } from "@primusclaw/personal-agent";
5558
5634
  var BOT_CONNECTOR_RESOURCE = "https://api.botframework.com";
5559
5635
  var IMDS_TOKEN_URL = "http://169.254.169.254/metadata/identity/oauth2/token";
5560
5636
  var IMDS_API_VERSION = "2018-02-01";
@@ -5565,7 +5641,7 @@ var ImdsTokenProvider = class extends CachedTokenProvider {
5565
5641
  this.clientId = clientId;
5566
5642
  if (!clientId) throw new Error("the managed identity's client id is required");
5567
5643
  this.fetch = options.fetch ?? globalThis.fetch;
5568
- this.logger = options.logger ?? silentLogger13;
5644
+ this.logger = options.logger ?? silentLogger14;
5569
5645
  this.url = options.url ?? IMDS_TOKEN_URL;
5570
5646
  }
5571
5647
  clientId;
@@ -5599,9 +5675,9 @@ var ImdsTokenProvider = class extends CachedTokenProvider {
5599
5675
  };
5600
5676
 
5601
5677
  // packages/teams/src/gate/no-queue.ts
5602
- import { silentLogger as silentLogger14 } from "@primusclaw/personal-agent";
5678
+ import { silentLogger as silentLogger15 } from "@primusclaw/personal-agent";
5603
5679
  var NoQueue = class {
5604
- constructor(logger = silentLogger14) {
5680
+ constructor(logger = silentLogger15) {
5605
5681
  this.logger = logger;
5606
5682
  }
5607
5683
  logger;
@@ -5694,7 +5770,7 @@ function azureBusClient(connection, lockRenewalMs) {
5694
5770
  }
5695
5771
 
5696
5772
  // packages/teams/src/servicebus/outbox.ts
5697
- import { errorName as errorName7, pyJsonDumps, silentLogger as silentLogger15 } from "@primusclaw/personal-agent";
5773
+ import { errorName as errorName7, pyJsonDumps, silentLogger as silentLogger16 } from "@primusclaw/personal-agent";
5698
5774
  var IDLE_REOPEN_MS = 24e4;
5699
5775
  var ServiceBusOutbox = class {
5700
5776
  constructor(client, queue, clock, logger) {
@@ -5703,7 +5779,7 @@ var ServiceBusOutbox = class {
5703
5779
  this.clock = clock;
5704
5780
  this.sender = client.sender(queue);
5705
5781
  this.usedAt = clock.monotonicMs();
5706
- this.logger = logger ?? silentLogger15;
5782
+ this.logger = logger ?? silentLogger16;
5707
5783
  }
5708
5784
  client;
5709
5785
  queue;
@@ -5752,8 +5828,23 @@ var StartupError = class extends Error {
5752
5828
  };
5753
5829
  function botTokenSource(settings2, deps) {
5754
5830
  const { bot } = settings2;
5755
- const logger = deps.logger ?? silentLogger16;
5831
+ const logger = deps.logger ?? silentLogger17;
5756
5832
  const base2 = { clock: deps.clock, logger, ...deps.fetch ? { fetch: deps.fetch } : {} };
5833
+ if (bot.clientSecretIgnored) {
5834
+ logger.warn("BOT_CLIENT_SECRET is set but not used: BOT_TOKEN_SOURCE names another source", {
5835
+ tokenSource: bot.tokenSource
5836
+ });
5837
+ }
5838
+ if (bot.tokenSource === "secret") {
5839
+ const provider = new ClientSecretTokenProvider({
5840
+ ...base2,
5841
+ clientId: bot.clientId,
5842
+ tenantId: bot.tenantId,
5843
+ clientSecret: bot.clientSecret
5844
+ });
5845
+ logger.info("bot token source: secret", { clientId: bot.clientId, tenantId: bot.tenantId });
5846
+ return provider;
5847
+ }
5757
5848
  if (bot.tokenSource !== "federated") {
5758
5849
  logger.info("bot token source: imds", { clientId: bot.msiClientId });
5759
5850
  return new ImdsTokenProvider(bot.msiClientId, base2);
@@ -5801,7 +5892,7 @@ function busConnections(settings2, credential) {
5801
5892
  function gateOutbound(gate, deps) {
5802
5893
  const tokens = new GateToken(gate.runId);
5803
5894
  const policy = onlyConnector(gate.connectorUrl);
5804
- (deps.logger ?? silentLogger16).warn("release gate test entry: outbound to the recording connector only; no queue", {
5895
+ (deps.logger ?? silentLogger17).warn("release gate test entry: outbound to the recording connector only; no queue", {
5805
5896
  runId: gate.runId
5806
5897
  });
5807
5898
  const outbox = new ConnectorOutbox({
@@ -5819,7 +5910,7 @@ function productionOutbound(settings2, outbound, deps) {
5819
5910
  if (settings2.outboundMode !== "direct") {
5820
5911
  return { outbox: queue, tokens: void 0, policy: DEFAULT_CONNECTOR_HOSTS, close: () => queue.close() };
5821
5912
  }
5822
- (deps.logger ?? silentLogger16).info("outbound mode: direct to the Bot Connector (the queue is the fallback)");
5913
+ (deps.logger ?? silentLogger17).info("outbound mode: direct to the Bot Connector (the queue is the fallback)");
5823
5914
  const tokens = botTokenSource(settings2, deps);
5824
5915
  const outbox = new ConnectorOutbox({
5825
5916
  tokens,
@@ -6199,7 +6290,7 @@ function runFollowUps(base2, errors) {
6199
6290
  }
6200
6291
  };
6201
6292
  }
6202
- function proactiveParts(base2, style, assistant, errors) {
6293
+ function proactiveParts(base2, style, assistant, errors, router) {
6203
6294
  const { store, claw, surface, settings: settings2 } = base2;
6204
6295
  const deps = {
6205
6296
  store,
@@ -6228,11 +6319,36 @@ function proactiveParts(base2, style, assistant, errors) {
6228
6319
  clock: base2.clock,
6229
6320
  logger: base2.logger,
6230
6321
  publicEvent: (event) => publicRunEvent(event, errors, (text4) => looksLikeServiceError(text4) || looksInternal(text4)),
6231
- botName: "Clawy"
6322
+ botName: "Clawy",
6323
+ ...router === void 0 ? {} : { identityAfterRefusal: identityAfterRefusal(base2, router) }
6232
6324
  };
6233
6325
  const proactive = new Proactive(deps);
6234
6326
  return { proactive, release: new Release(deps, proactive) };
6235
6327
  }
6328
+ function identityAfterRefusal(base2, router) {
6329
+ return async (userId, conversation, turn8) => {
6330
+ const { store } = base2;
6331
+ const once = `${IDENTITY_REFUSED_PREFIX}${userId}:${turn8}`;
6332
+ if (!turn8) return;
6333
+ const claim = store.idempotency.claimEvent(once);
6334
+ if (claim.state !== "claimed") return;
6335
+ let sent = false;
6336
+ try {
6337
+ const person = {
6338
+ id: userId,
6339
+ channelUserId: store.members.channelIdOf(userId) ?? "",
6340
+ name: store.members.memberName(userId) ?? "",
6341
+ email: ""
6342
+ };
6343
+ const r = router();
6344
+ sent = await r.ctx.credentials.identityAfterRefusal(r.chat(person, conversation));
6345
+ } finally {
6346
+ if (sent) store.idempotency.finishEvent(once);
6347
+ else store.idempotency.releaseEvent(once, claim.holder);
6348
+ }
6349
+ };
6350
+ }
6351
+ var IDENTITY_REFUSED_PREFIX = "identity-refused:";
6236
6352
  function proactiveHold(parts) {
6237
6353
  return {
6238
6354
  muted: (userId) => parts.proactive.muted(userId) ?? null,
@@ -6844,7 +6960,7 @@ function routerDeps(base2, built, errors) {
6844
6960
  connectionsText: whoamiConnections(plugins.integrations),
6845
6961
  reportView: (userId, scope) => w8.reportView(userId, scope),
6846
6962
  note: noteFactory,
6847
- subscriptions: subs === void 0 ? void 0 : { ensure: (u) => subs.ensure(u), remove: (u, key) => subs.remove(u, key) },
6963
+ subscriptions: subs === void 0 ? void 0 : { ensure: (u, credential) => subs.ensure(u, credential), remove: (u, key) => subs.remove(u, key) },
6848
6964
  handlers: built.handlers,
6849
6965
  integrations: plugins.integrations
6850
6966
  };
@@ -6970,7 +7086,7 @@ function buildFeatures(given) {
6970
7086
  hooks,
6971
7087
  reviewHandoff: (userId, event) => lateReview.handoff?.take(userId, event) ?? "dropped"
6972
7088
  });
6973
- const proactive = proactiveParts(base2, teams.style, assistant, errors);
7089
+ const proactive = proactiveParts(base2, teams.style, assistant, errors, get3);
6974
7090
  const reach = followReach(proactive, base2);
6975
7091
  const remote = remoteAgents(base2, { switches, guard, reach, errors, directChat: assistant.directChat, hooks });
6976
7092
  const w8 = w8Parts(base2, { briefEnabled: switches.brief, assistantOn: (userId) => assistant.chat.on(userId) });
@@ -7092,7 +7208,7 @@ function metricsRoutes(render) {
7092
7208
  }
7093
7209
 
7094
7210
  // packages/teams/src/assembly/inbound.ts
7095
- import { silentLogger as silentLogger18 } from "@primusclaw/personal-agent";
7211
+ import { silentLogger as silentLogger19 } from "@primusclaw/personal-agent";
7096
7212
 
7097
7213
  // packages/teams/src/activity/inbound/actions.ts
7098
7214
  import { cpHead as cpHead4, pyStr as pyStr11 } from "@primusclaw/personal-agent";
@@ -8076,7 +8192,7 @@ import {
8076
8192
  err as err4,
8077
8193
  ok as ok4,
8078
8194
  pyStr as pyStr19,
8079
- silentLogger as silentLogger17
8195
+ silentLogger as silentLogger18
8080
8196
  } from "@primusclaw/personal-agent";
8081
8197
  function wireReferenceOf(activity) {
8082
8198
  const ref = {
@@ -8108,7 +8224,7 @@ function base(activity, sender) {
8108
8224
  };
8109
8225
  }
8110
8226
  function messageOf(activity, sender, options) {
8111
- const logger = options.logger ?? silentLogger17;
8227
+ const logger = options.logger ?? silentLogger18;
8112
8228
  const personal = isPersonal(activity);
8113
8229
  const found = quotesOf(activity);
8114
8230
  const attached = inboundFiles(activity);
@@ -8180,7 +8296,7 @@ function text3(value) {
8180
8296
  return typeof value === "number" && value !== 0 ? String(value) : "";
8181
8297
  }
8182
8298
  function inboundHandler(parts) {
8183
- const logger = parts.logger ?? silentLogger18;
8299
+ const logger = parts.logger ?? silentLogger19;
8184
8300
  return async (body) => {
8185
8301
  if (body["type"] === DELIVERED) {
8186
8302
  const activityId = text3(body["activity_id"]);
@@ -8383,7 +8499,7 @@ import {
8383
8499
  pyStr as pyStr20,
8384
8500
  pyStrip as pyStrip20,
8385
8501
  SecretsUnavailable as SecretsUnavailable2,
8386
- silentLogger as silentLogger19
8502
+ silentLogger as silentLogger20
8387
8503
  } from "@primusclaw/personal-agent";
8388
8504
 
8389
8505
  // packages/teams/src/azure/keyvault-config.ts
@@ -8479,7 +8595,7 @@ var KeyVaultSecretSource = class {
8479
8595
  this.credential = credential;
8480
8596
  this.options = options;
8481
8597
  this.fetch = options.fetch ?? globalThis.fetch;
8482
- this.logger = options.logger ?? silentLogger19;
8598
+ this.logger = options.logger ?? silentLogger20;
8483
8599
  this.sleep = options.sleep ?? ((ms, signal) => options.clock.sleep(ms, signal));
8484
8600
  }
8485
8601
  url;
@@ -3,7 +3,7 @@
3
3
  * become in the chat, what quiet hours and /pause hold and later release, approval cards sent again, and the two views of it
4
4
  * the router and the remote agents read (`ProactiveHold`, `FollowReach`).
5
5
  */
6
- import type { Conversation, ConversationRef, FollowReach, JsonObject, ProactiveHold, PublicErrors } from "@primusclaw/personal-agent";
6
+ import type { Conversation, ConversationRef, FollowReach, JsonObject, ProactiveHold, PublicErrors, Router } from "@primusclaw/personal-agent";
7
7
  import { Proactive, Release } from "@primusclaw/personal-agent";
8
8
  import type { Style } from "../config/style.js";
9
9
  import type { AssistantParts } from "./features-assistant.js";
@@ -15,7 +15,9 @@ export interface ProactiveParts {
15
15
  readonly proactive: Proactive;
16
16
  readonly release: Release;
17
17
  }
18
- export declare function proactiveParts(base: AssemblyBase, style: Style, assistant: Pick<AssistantParts, "receipts" | "directChat">, errors: PublicErrors): ProactiveParts;
18
+ export declare function proactiveParts(base: AssemblyBase, style: Style, assistant: Pick<AssistantParts, "receipts" | "directChat">, errors: PublicErrors, router?: () => Router): ProactiveParts;
19
+ /** The event claim key prefix of a turn whose identity card was sent (`identityAfterRefusal`). */
20
+ export declare const IDENTITY_REFUSED_PREFIX = "identity-refused:";
19
21
  /** What the router reads of quiet hours and /pause (`muted` as a word or null, `release` on /resume). */
20
22
  export declare function proactiveHold(parts: ProactiveParts): ProactiveHold;
21
23
  /**
@@ -5,10 +5,16 @@ export type Env = Readonly<Record<string, string | undefined>>;
5
5
  export declare class TeamsConfigError extends Error {
6
6
  name: string;
7
7
  }
8
- export type BotTokenSource = "imds" | "federated";
8
+ export type BotTokenSource = "imds" | "federated" | "secret";
9
9
  export interface BotSettings {
10
10
  readonly tokenSource: BotTokenSource;
11
11
  readonly msiClientId: string;
12
+ /** BOT_CLIENT_ID: the app registration's client id, with `secret`. */
13
+ readonly clientId: string;
14
+ /** BOT_CLIENT_SECRET, with `secret` ("" otherwise). Not enumerable: a dump of the settings does not show it. */
15
+ readonly clientSecret: string;
16
+ /** BOT_CLIENT_SECRET is set but BOT_TOKEN_SOURCE names another source, which wins (the worker warns at start). */
17
+ readonly clientSecretIgnored: boolean;
12
18
  readonly tenantId: string;
13
19
  readonly assertionKeyFile: string;
14
20
  readonly assertionIssuer: string;
@@ -0,0 +1,36 @@
1
+ /**
2
+ * A token from Entra ID for an app registration's client secret (the OAuth client credentials grant): the most common
3
+ * way to run a bot outside Azure, where neither a managed identity nor a federated credential is at hand. By default the
4
+ * scope is the bot's Bot Connector scope.
5
+ *
6
+ * The secret goes into the token request's form and nowhere else: it is never logged, never part of an error message,
7
+ * and hidden from `JSON.stringify` and `util.inspect` of the provider. A refusal by Entra (400/401: wrong tenant, client
8
+ * id or secret, an expired secret) is not transient; a 429, a 5xx or a network error is. Errors name the AADSTS codes
9
+ * only, never the description (it can echo the request).
10
+ */
11
+ import { type Clock, type Logger } from "@primusclaw/personal-agent";
12
+ import { CachedTokenProvider } from "./cached.js";
13
+ export interface ClientSecretOptions {
14
+ readonly clientId: string;
15
+ readonly tenantId: string;
16
+ readonly clientSecret: string;
17
+ readonly clock: Clock;
18
+ readonly fetch?: typeof fetch;
19
+ readonly logger?: Logger;
20
+ /** The token endpoint; default Entra ID's for the tenant. */
21
+ readonly url?: string;
22
+ readonly scope?: string;
23
+ }
24
+ export declare class ClientSecretTokenProvider extends CachedTokenProvider {
25
+ #private;
26
+ readonly source = "secret";
27
+ readonly scope: string;
28
+ readonly clientId: string;
29
+ readonly tenantId: string;
30
+ private readonly fetch;
31
+ private readonly logger;
32
+ private readonly url;
33
+ /** Throws (an Error naming the missing setting, never a value) rather than at the first token. */
34
+ constructor(options: ClientSecretOptions);
35
+ protected fetchToken(signal?: AbortSignal): Promise<string>;
36
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@primusclaw/personal-agent-teams",
3
- "version": "0.2.0",
3
+ "version": "0.3.0",
4
4
  "description": "The personal agent on Microsoft Teams: activities, Adaptive Cards, streams, Bot Connector, inbound queue, process assembly.",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -31,8 +31,8 @@
31
31
  "dependencies": {
32
32
  "@azure/core-auth": "^1.11.0",
33
33
  "@azure/service-bus": "^7.10.0",
34
- "@primusclaw/personal-agent": "0.2.0",
35
- "@primusclaw/personal-agent-runtime": "0.2.0",
34
+ "@primusclaw/personal-agent": "0.3.0",
35
+ "@primusclaw/personal-agent-runtime": "0.3.0",
36
36
  "zod": "^4.6.7"
37
37
  },
38
38
  "devDependencies": {