@vellumai/assistant 0.10.11-dev.202607222129.31c06e5 → 0.10.11-dev.202607222325.35fc367

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 (29) hide show
  1. package/ARCHITECTURE.md +30 -21
  2. package/package.json +1 -1
  3. package/src/__tests__/channel-delivery-store.test.ts +141 -0
  4. package/src/__tests__/document-preview-surface-schema.test.ts +33 -0
  5. package/src/__tests__/dynamic-skill-background-guard.test.ts +102 -13
  6. package/src/__tests__/inline-skill-load-permissions.test.ts +29 -6
  7. package/src/__tests__/record-persisted-seq-lock-resilience.test.ts +95 -0
  8. package/src/__tests__/surface-type-registry-guard.test.ts +66 -0
  9. package/src/__tests__/tool-approval-handler.test.ts +25 -1
  10. package/src/__tests__/ui-choice-copy-surfaces.test.ts +26 -0
  11. package/src/api/events/bookmark-created.ts +37 -0
  12. package/src/api/events/bookmark-deleted.ts +20 -0
  13. package/src/api/index.ts +17 -0
  14. package/src/api/surfaces.ts +42 -5
  15. package/src/daemon/conversation-surfaces.ts +12 -4
  16. package/src/daemon/message-types/bookmarks.ts +9 -14
  17. package/src/messaging/providers/telegram-bot/send.test.ts +88 -0
  18. package/src/messaging/providers/telegram-bot/send.ts +43 -3
  19. package/src/messaging/providers/telegram-bot/transport.ts +26 -8
  20. package/src/permissions/checker.ts +18 -21
  21. package/src/permissions/confirmation-guardian-request.ts +17 -1
  22. package/src/permissions/prompter.ts +3 -0
  23. package/src/persistence/conversation-crud.ts +36 -8
  24. package/src/persistence/delivery-crud.ts +13 -1
  25. package/src/persistence/external-conversation-store.ts +22 -0
  26. package/src/runtime/routes/inbound-conversation.ts +19 -3
  27. package/src/runtime/routes/inbound-message-handler.ts +8 -5
  28. package/src/tools/permission-checker.ts +42 -9
  29. package/src/tools/tool-approval-handler.ts +24 -4
@@ -860,7 +860,24 @@ export async function check(
860
860
  signal,
861
861
  );
862
862
 
863
- const { level: risk, reason: riskReason } = classification;
863
+ const { level: classifiedRisk, reason: riskReason } = classification;
864
+
865
+ // Inline-command ("dynamic") skill loads execute embedded shell at load time
866
+ // via child_process.spawn, outside the tool-approval pipeline that the
867
+ // auto-approve threshold governs. Treat an uncovered one as High so the
868
+ // standard threshold decides it like any other high-risk action: it runs at
869
+ // Full access (autoApproveUpTo "high") and prompts below it. A covering user
870
+ // trust rule arrives as matchType
871
+ // "user_rule" with the risk already lowered (the escape hatch), so leave it
872
+ // untouched. The gateway classifier is authoritative and also returns High;
873
+ // this local elevation is defense-in-depth for the gateway-unreachable or
874
+ // under-classified path. The separate non-interactive denial (no human to
875
+ // approve embedded shell) lives in tools/permission-checker.ts.
876
+ const risk =
877
+ isDynamicSkillLoadInvocation(toolName, input) &&
878
+ getCachedAssessment(toolName, input)?.matchType !== "user_rule"
879
+ ? RiskLevel.High
880
+ : classifiedRisk;
864
881
 
865
882
  // Use gateway-provided sandboxAutoApprove instead of evaluating locally.
866
883
  const hasSandboxAutoApprove = classification.sandboxAutoApprove ?? false;
@@ -912,26 +929,6 @@ export async function check(
912
929
  }
913
930
  }
914
931
 
915
- // Inline-command ("dynamic") skill loads execute embedded shell commands
916
- // at load time, so a threshold-based allow is not enough: they run
917
- // without asking only when the user's own trust rule covers them (the
918
- // rule re-classifies the risk inside the gateway, arriving here as
919
- // matchType "user_rule"). Everything else prompts — at every threshold
920
- // and in every execution context. The non-interactive guardian gate in
921
- // tools/permission-checker.ts then converts the prompt into a denial
922
- // when no human is present to answer it.
923
- if (
924
- approvalDecision.decision === "allow" &&
925
- isDynamicSkillLoadInvocation(toolName, input) &&
926
- getCachedAssessment(toolName, input)?.matchType !== "user_rule"
927
- ) {
928
- approvalDecision = {
929
- decision: "prompt",
930
- reason:
931
- "Inline-command skill load: executes embedded commands, requires explicit approval",
932
- };
933
- }
934
-
935
932
  // Enrich the reason with the classifier's explanation when available.
936
933
  // For risk-based fallback decisions (prompt/deny from High/Medium risk),
937
934
  // incorporate the classifier reason so the user sees *why* the command
@@ -32,6 +32,20 @@ const log = getLogger("confirmation-guardian-request");
32
32
  export async function createGuardianRequestForConfirmation(
33
33
  msg: ServerMessage & { type: "confirmation_request" },
34
34
  conversationId: string,
35
+ opts?: {
36
+ /**
37
+ * Bind the request to the conversation's per-turn trust snapshot rather
38
+ * than the live context. Turn-emitted confirmations (PermissionPrompter)
39
+ * set this: the promotion runs fire-and-forget, and the live trustContext
40
+ * can mutate mid-promotion (e.g. a concurrent owner meta command), so the
41
+ * snapshot pins the actor and source-message provenance to the turn that
42
+ * emitted the confirmation — the executor's own snapshot semantics.
43
+ * Route-generated confirmations (ACP spawn/steer) leave this unset: their
44
+ * provenance is the conversation's live binding, not whatever unrelated
45
+ * turn happens to be in flight.
46
+ */
47
+ preferTurnSnapshot?: boolean;
48
+ },
35
49
  ): Promise<void> {
36
50
  try {
37
51
  const [
@@ -51,7 +65,9 @@ export async function createGuardianRequestForConfirmation(
51
65
  ]);
52
66
 
53
67
  const conversation = findConversation(conversationId);
54
- const trustContext = conversation?.trustContext;
68
+ const trustContext = opts?.preferTurnSnapshot
69
+ ? (conversation?.currentTurnTrustContext ?? conversation?.trustContext)
70
+ : conversation?.trustContext;
55
71
  const sourceChannel = trustContext?.sourceChannel ?? "vellum";
56
72
  const inputRecord = msg.input as Record<string, unknown>;
57
73
  const activityRaw =
@@ -180,10 +180,13 @@ export class PermissionPrompter {
180
180
 
181
181
  // Promote the confirmation to a guardian request so channel
182
182
  // guardian decisions (reactions, buttons, text) can resolve it.
183
+ // The prompter runs inside the emitting turn, so the request binds
184
+ // to that turn's trust snapshot.
183
185
  if (conversationId) {
184
186
  void createGuardianRequestForConfirmation(
185
187
  confirmationMsg,
186
188
  conversationId,
189
+ { preferTurnSnapshot: true },
187
190
  );
188
191
  }
189
192
 
@@ -45,7 +45,10 @@ import { getLogger } from "../util/logger.js";
45
45
  import { getLogsDbPath } from "../util/logs-db-path.js";
46
46
  import { getConversationsDir } from "../util/platform.js";
47
47
  import { createRowMapper, parseJsonNullable } from "../util/row-mapper.js";
48
- import { withSqliteRetry } from "../util/sqlite-retry.js";
48
+ import {
49
+ isRetryableSqliteError,
50
+ withSqliteRetry,
51
+ } from "../util/sqlite-retry.js";
49
52
  import {
50
53
  deleteOrphanAttachments,
51
54
  linkAttachmentToMessage,
@@ -2744,18 +2747,43 @@ export function getConversationPersistedSeq(id: string): number | null {
2744
2747
  * Monotonic: the `WHERE seq IS NULL OR seq < ?` guard makes the update raise
2745
2748
  * the high-water mark only, so out-of-order async commits never regress it.
2746
2749
  * Non-positive or non-finite `seq` values are ignored.
2750
+ *
2751
+ * Transient SQLite write contention (`SQLITE_BUSY`/`SQLITE_IOERR`) is swallowed
2752
+ * rather than thrown. This is a single, idempotent, monotonic UPDATE of a
2753
+ * snapshot↔stream anchor that every subsequent flush re-records with an
2754
+ * equal-or-higher seq, so a dropped write self-heals on the next flush — the
2755
+ * same self-healing property that lets the paired content write
2756
+ * (`persistLoopMessageContent`) swallow its final failure. `busy_timeout`
2757
+ * already made the statement wait for the lock before surfacing `SQLITE_BUSY`,
2758
+ * so this synchronous path cannot usefully back off and retry; it just must not
2759
+ * throw. Several callers are fire-and-forget bookkeeping in the agent loop
2760
+ * (`flushAccumulatedContent`, `handleMessageComplete`, tool events) where a
2761
+ * raw throw is fatal: the debounced partial flush becomes an unhandled
2762
+ * rejection, and `message_complete` is on `dispatchAgentEvent`'s re-throw
2763
+ * allowlist — either one takes down the daemon on lock contention. A
2764
+ * non-contention error (a genuine bug: bad SQL, missing column) still throws.
2747
2765
  */
2748
2766
  export function recordConversationPersistedSeq(id: string, seq: number): void {
2749
2767
  if (!Number.isFinite(seq) || seq <= 0) {
2750
2768
  return;
2751
2769
  }
2752
- rawRun(
2753
- "conversation:recordPersistedSeq",
2754
- "UPDATE conversations SET seq = ? WHERE id = ? AND (seq IS NULL OR seq < ?)",
2755
- seq,
2756
- id,
2757
- seq,
2758
- );
2770
+ try {
2771
+ rawRun(
2772
+ "conversation:recordPersistedSeq",
2773
+ "UPDATE conversations SET seq = ? WHERE id = ? AND (seq IS NULL OR seq < ?)",
2774
+ seq,
2775
+ id,
2776
+ seq,
2777
+ );
2778
+ } catch (err) {
2779
+ if (!isRetryableSqliteError(err)) {
2780
+ throw err;
2781
+ }
2782
+ log.warn(
2783
+ { err, conversationId: id, seq },
2784
+ "recordConversationPersistedSeq: transient SQLite contention; dropping this anchor advance (self-heals on the next flush)",
2785
+ );
2786
+ }
2759
2787
  }
2760
2788
 
2761
2789
  /**
@@ -37,6 +37,13 @@ export interface RecordInboundOptions {
37
37
  const SLACK_LEGACY_THREAD_EVIDENCE_BATCH_SIZE = 50;
38
38
  const SLACK_LEGACY_THREAD_EVIDENCE_MAX_SCAN = 500;
39
39
 
40
+ /**
41
+ * Channels where an inbound thread id scopes the conversation: a Slack thread
42
+ * or a Telegram private-chat topic each maps to its own conversation. A
43
+ * message without a thread id always resolves to the chat-level base key.
44
+ */
45
+ const THREAD_SCOPED_CHANNELS = new Set(["slack", "telegram"]);
46
+
40
47
  function buildScopedConversationKeyForAssistant(
41
48
  assistantId: string,
42
49
  sourceChannel: string,
@@ -44,7 +51,7 @@ function buildScopedConversationKeyForAssistant(
44
51
  sourceThreadId?: string | null,
45
52
  ): string {
46
53
  const threadId = sourceThreadId?.trim();
47
- if (sourceChannel === "slack" && threadId) {
54
+ if (THREAD_SCOPED_CHANNELS.has(sourceChannel) && threadId) {
48
55
  return `asst:${assistantId}:${sourceChannel}:${externalChatId}:thread:${threadId}`;
49
56
  }
50
57
  return `asst:${assistantId}:${sourceChannel}:${externalChatId}`;
@@ -137,6 +144,11 @@ function resolveInboundConversation(
137
144
  );
138
145
 
139
146
  const threadId = sourceThreadId?.trim();
147
+ // Flat→threaded aliasing applies only to Slack: a Slack thread may continue
148
+ // a conversation that lives on the flat channel key, so the alias path below
149
+ // checks for that evidence before minting a threaded conversation. Every
150
+ // other thread-scoped channel (Telegram topics) has no flat-key aliasing —
151
+ // a thread id always resolves the threaded key directly.
140
152
  if (sourceChannel !== "slack" || !threadId) {
141
153
  return getOrCreateConversation(threadedKey);
142
154
  }
@@ -262,6 +262,28 @@ export function deleteBindingByChannelChat(
262
262
  .run();
263
263
  }
264
264
 
265
+ /**
266
+ * Remove only the thread-less (chat-level) binding for a channel + chat,
267
+ * leaving bindings that carry an `externalThreadId` untouched. Used when
268
+ * resetting a chat's main conversation so sibling thread/topic conversations
269
+ * in the same chat keep their bindings.
270
+ */
271
+ export function deleteBindingByChannelChatNullThread(
272
+ sourceChannel: string,
273
+ externalChatId: string,
274
+ ): void {
275
+ const db = getDb();
276
+ db.delete(externalConversationBindings)
277
+ .where(
278
+ and(
279
+ eq(externalConversationBindings.sourceChannel, sourceChannel),
280
+ eq(externalConversationBindings.externalChatId, externalChatId),
281
+ isNull(externalConversationBindings.externalThreadId),
282
+ ),
283
+ )
284
+ .run();
285
+ }
286
+
265
287
  /**
266
288
  * Remove an external binding by channel + external chat ID + thread ID.
267
289
  */
@@ -1,5 +1,17 @@
1
1
  /**
2
- * Channel conversation deletion handler.
2
+ * Channel conversation reset handler.
3
+ *
4
+ * Channel-agnostic contract — two reset shapes, keyed on `sourceThreadId`:
5
+ *
6
+ * - **Thread-less reset** (no `sourceThreadId`): resets the chat's MAIN
7
+ * conversation only — deletes the base + legacy keys and the thread-less
8
+ * binding. Thread/topic conversations in the same chat (Slack threads,
9
+ * Telegram topics) are independent conversations and are never touched.
10
+ * - **Threaded reset** (`sourceThreadId` set): resets exactly that
11
+ * thread/topic's conversation — deletes its scoped key and its binding.
12
+ *
13
+ * Adapter-specific behavior stays inside the explicitly channel-gated
14
+ * branches below and must not leak into the shared contract.
3
15
  */
4
16
  import {
5
17
  deleteConversationKey,
@@ -7,7 +19,7 @@ import {
7
19
  } from "../../persistence/conversation-key-store.js";
8
20
  import { buildScopedConversationKey } from "../../persistence/delivery-crud.js";
9
21
  import {
10
- deleteBindingByChannelChat,
22
+ deleteBindingByChannelChatNullThread,
11
23
  deleteBindingByChannelChatThread,
12
24
  } from "../../persistence/external-conversation-store.js";
13
25
  import { BadRequestError } from "./errors.js";
@@ -38,8 +50,12 @@ export function handleDeleteConversation({ body = {} }: RouteHandlerArgs) {
38
50
  const legacyKey = `${sourceChannel}:${conversationExternalId}`;
39
51
  if (!normalizedThreadId) {
40
52
  deleteConversationKey(legacyKey);
41
- deleteBindingByChannelChat(sourceChannel, conversationExternalId);
53
+ deleteBindingByChannelChatNullThread(sourceChannel, conversationExternalId);
42
54
  } else {
55
+ // Slack adapter: eagerly re-mint a fresh conversation for the threaded
56
+ // key so mid-thread turns racing the reset land in the new conversation.
57
+ // Telegram deliberately skips this — a reset topic simply creates its
58
+ // fresh conversation on the next inbound message.
43
59
  if (sourceChannel === "slack") {
44
60
  getOrCreateConversation(scopedKey);
45
61
  }
@@ -674,12 +674,15 @@ export async function handleChannelInbound({
674
674
  typeof sourceMetadata?.messageId === "string"
675
675
  ? sourceMetadata.messageId
676
676
  : undefined;
677
- const slackThreadTs =
678
- sourceChannel === "slack" &&
677
+ // Thread id of the inbound message's external container (Slack thread ts,
678
+ // Telegram topic id). Scopes conversation resolution and the persisted
679
+ // binding for thread-scoped channels.
680
+ const channelThreadId =
679
681
  typeof sourceMetadata?.threadId === "string" &&
680
682
  sourceMetadata.threadId.trim().length > 0
681
683
  ? sourceMetadata.threadId.trim()
682
684
  : undefined;
685
+ const slackThreadTs = sourceChannel === "slack" ? channelThreadId : undefined;
683
686
 
684
687
  if (isEdit && !sourceMessageId) {
685
688
  throw new BadRequestError("sourceMetadata.messageId is required for edits");
@@ -692,7 +695,7 @@ export async function handleChannelInbound({
692
695
  conversationExternalId,
693
696
  externalMessageId,
694
697
  sourceMessageId,
695
- sourceThreadId: slackThreadTs,
698
+ sourceThreadId: channelThreadId,
696
699
  canonicalAssistantId,
697
700
  assistantId,
698
701
  content,
@@ -708,7 +711,7 @@ export async function handleChannelInbound({
708
711
  {
709
712
  sourceMessageId,
710
713
  assistantId: canonicalAssistantId,
711
- sourceThreadId: slackThreadTs,
714
+ sourceThreadId: channelThreadId,
712
715
  },
713
716
  );
714
717
 
@@ -723,7 +726,7 @@ export async function handleChannelInbound({
723
726
  sourceChannel,
724
727
  externalChatId: conversationExternalId,
725
728
  externalChatName: slackChannelName,
726
- externalThreadId: slackThreadTs ?? null,
729
+ externalThreadId: channelThreadId ?? null,
727
730
  externalUserId: canonicalSenderId ?? rawSenderId ?? null,
728
731
  displayName: body.actorDisplayName ?? null,
729
732
  username: body.actorUsername ?? null,
@@ -228,6 +228,44 @@ export class PermissionChecker {
228
228
  };
229
229
  }
230
230
 
231
+ // Inline-command ("dynamic") skill loads execute embedded shell at load
232
+ // time. The sensitive-tool gate (tools/tool-approval-handler.ts, lane A)
233
+ // already routes an uncovered one through the guardian-mediated capability
234
+ // floor, so a non-guardian is escalated there and never reaches this lane.
235
+ // The one thing that floor does not express is the absence of a human: an
236
+ // uncovered dynamic load in a non-interactive session is denied here,
237
+ // because embedded shell must never run unattended without a covering rule.
238
+ // (A covering trust rule, matchType "user_rule", is left to proceed.)
239
+ if (
240
+ context.isInteractive === false &&
241
+ isDynamicSkillLoadInvocation(name, input) &&
242
+ getCachedAssessment(name, input)?.matchType !== "user_rule"
243
+ ) {
244
+ log.info(
245
+ { toolName: name, riskLevel },
246
+ "Denying uncovered inline-command skill load in non-interactive session",
247
+ );
248
+ recordToolDenied({
249
+ conversationId: context.conversationId,
250
+ toolName: name,
251
+ input,
252
+ reason:
253
+ "Inline-command skill load requires human approval; no interactive client connected",
254
+ riskLevel,
255
+ durationMs: Date.now() - startTime,
256
+ wasPrompted: false,
257
+ });
258
+ return {
259
+ allowed: false,
260
+ decision: "denied",
261
+ riskLevel,
262
+ content: `Permission denied: tool "${name}" would load a skill containing inline command expansions, which execute shell commands at load time and require explicit human approval. No interactive client is connected. To allow this in non-interactive sessions, add a trust rule covering the skill via permission settings.`,
263
+ riskMeta,
264
+ ...mapApprovalProvenance("denied", {}),
265
+ riskThreshold,
266
+ };
267
+ }
268
+
231
269
  // Platform-hosted mode: auto-approve sandboxed bash for guardians.
232
270
  // The sandbox provides the security boundary — prompting is unnecessary
233
271
  // friction. host_bash is excluded because it runs unsandboxed on the
@@ -261,22 +299,17 @@ export class PermissionChecker {
261
299
  // is the owner - prompting makes no sense when there is no client.
262
300
  // Exception: requireFreshApproval tools cannot be auto-approved -
263
301
  // without a human present, bundle installation must be denied.
264
- // Exception: inline-command ("dynamic") skill loads must never be
265
- // silently auto-approved — they execute embedded commands and
266
- // require explicit human review or a pinned trust rule. A covering
267
- // trust rule lowers the classified risk upstream (check() then
268
- // returns "allow" before this branch), so any dynamic load that
269
- // reaches this prompt path is uncovered and must stay prompted.
302
+ // Inline-command ("dynamic") skill loads are already denied above for
303
+ // non-interactive sessions (embedded shell with no human to review it),
304
+ // so they never reach this branch uncovered.
270
305
  // Exception: tools above the configured background threshold are
271
306
  // denied — unattended sessions must not auto-approve operations that
272
307
  // could cause significant damage if triggered by prompt injection
273
308
  // from untrusted content.
274
- const isDynamicSkillLoad = isDynamicSkillLoadInvocation(name, input);
275
309
  if (
276
310
  context.isInteractive === false &&
277
311
  resolveCapabilities(context.trustClass).canSelfApproveTools &&
278
- !context.requireFreshApproval &&
279
- !isDynamicSkillLoad
312
+ !context.requireFreshApproval
280
313
  ) {
281
314
  // getAutoApproveThreshold returns from cache (populated by check() above).
282
315
  // Deferred inside the non-interactive branch so interactive prompts
@@ -7,6 +7,7 @@ import { isToolAllowedInChannel } from "../channels/permission-profiles.js";
7
7
  import type { ChannelId } from "../channels/types.js";
8
8
  import { getConfig } from "../config/loader.js";
9
9
  import type { AutoApproveThreshold } from "../permissions/approval-policy.js";
10
+ import { isDynamicSkillLoadInvocation } from "../permissions/checker.js";
10
11
  import {
11
12
  isUnparseableToolArgs,
12
13
  unparseableToolArgsMessage,
@@ -238,13 +239,17 @@ const UI_SURFACE_TOOLS = new Set(["ui_show", "ui_update", "ui_dismiss"]);
238
239
 
239
240
  /**
240
241
  * Tool-sensitivity predicate: does invoking this tool require an approval
241
- * decision at all? This is purely about the tool and where it executes —
242
- * actor identity never feeds in here (it enters the decision only through
243
- * the `CapabilitySet` floor, see {@link resolveSensitiveToolDecision}).
242
+ * decision at all? This is about the tool, where it executes, and — for
243
+ * `skill_load` — whether the invocation will execute embedded shell at load
244
+ * time (inline command expansions run outside the tool pipeline, so they must
245
+ * be gated like other code execution). Actor identity never feeds in here; it
246
+ * enters the decision only through the `CapabilitySet` floor, see
247
+ * {@link resolveSensitiveToolDecision}.
244
248
  */
245
249
  export function isSensitiveTool(
246
250
  toolName: string,
247
251
  executionTarget: ExecutionTarget,
252
+ input?: Record<string, unknown>,
248
253
  ): boolean {
249
254
  // UI surface tools are passive, user-visible operations (cards, forms,
250
255
  // tables). User input is voluntary and user-controlled — they are not
@@ -254,6 +259,21 @@ export function isSensitiveTool(
254
259
  return false;
255
260
  }
256
261
 
262
+ // An inline-command ("dynamic") skill_load executes embedded shell at load
263
+ // time. skill_load is not a side-effect tool, so without this it would skip
264
+ // the capability floor entirely. Routing it through the gate makes a
265
+ // non-guardian's dynamic load escalate to the guardian like any other code
266
+ // execution — the floor is deterministic, so neither Full access nor a
267
+ // covering trust rule lifts it. (The guardian self-approves; the trust-rule
268
+ // escape hatch still applies to the guardian's own load in the risk lane.)
269
+ if (
270
+ toolName === "skill_load" &&
271
+ input &&
272
+ isDynamicSkillLoadInvocation(toolName, input)
273
+ ) {
274
+ return true;
275
+ }
276
+
257
277
  // Side-effect tools are sensitive. Read-only host execution is too,
258
278
  // because it can leak sensitive local information (e.g. shell/file reads).
259
279
  return isSideEffectTool(toolName) || executionTarget === "host";
@@ -486,7 +506,7 @@ export class ToolApprovalHandler {
486
506
  | Parameters<typeof consumeGrantForInvocation>[0]
487
507
  | null = null;
488
508
 
489
- const sensitive = isSensitiveTool(name, executionTarget);
509
+ const sensitive = isSensitiveTool(name, executionTarget, input);
490
510
  const { sensitiveToolApproval } = resolveCapabilities(context.trustClass);
491
511
  // cellThreshold stays unresolved: the decision does not consult it
492
512
  // (the floor is deterministic), and resolving a live threshold here