Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
d22b1ff1d2 | ||
|
|
275353ac1e | ||
|
|
52eab84f9a | ||
|
|
6dc2859292 |
@@ -128,7 +128,7 @@ Every run also gets `RequestScopeNote` (`src/data/harness-prompts.ts`): the user
|
||||
- Handler `src/bots-queue/index.ts`: separate reply/task slots, heartbeat, a per-attempt deadline for replies (`AppData.BotJobAttemptTimeoutMs`; a task run has none, since its script may run for hours, and Stop ends it), one task per computer and one reply per session (`createKeyLock`). Work in `run-bot-job.ts` -> `run-bot-reply.ts` / `run-bot-task.ts`. Throw `BotJobFatalError` for failures retrying can't fix. A computer that's down (`isComputerDown`: failed, dead, exited) is one: `queueBotTask` (a reply's `send_reply` work, or `start_task`) refuses it and a task run on it fails at once.
|
||||
- Every model turn is a step in `bots_queue_updates` (tool names, never arguments; `describe-job-step.ts`, labels in `JobStepToolLabels`), pushed as `server:bot-job-update` by the live relay only. Steps feed the live working row alone: the `clear-job-steps` cron deletes them `AppData.BotJobStepsKeepMs` after the job ends, however it ended, keeping their count on `bots_queue.steps`. Never delete them the moment a job ends (the relay would miss the last ones).
|
||||
- **A task run plans before it starts:** `planBotTask` (from `run-bot-task`) spends one turn, no tools, on the very system prompt the run then sends, so the provider's cache serves it and it costs little more than the plan. The answer is a bounded JSON plan (`BotTaskPlanSchema`, caps in `AppData.BotTaskPlan*`) that opens the run as `taskPlanNote` and shows as its first step line; `shouldPlanBotTask` keeps it off short runs (`AppData.BotTaskPlanMinSteps`). A plan that can't be written or read starts the run unplanned, never blocks it. **The wrap up is told what is on disk:** a task run passes `Params.wrap_up_note`, which runs `worktreeSummary` over the run's folders (`git status --porcelain` and `git diff --stat` per repository, nested ones included, at most 5) and puts the machine's own account in front of the wrap-up prompt, so the report is written from the tree and not from the run's memory of writing it. **The files the brief names are checked once, before the run starts** (`namedFilesNote`, over `namedFiles`): a path that isn't on the computer but is still in the bot's files is handed over as its `[file:ID]` with `export_file`, and one with no copy anywhere says plainly not to go looking through the machine or the user's accounts. It is the app's answer, not the run's guess: a source a rebuild took off the computer once cost a run thirty turns probing the container and then the user's own accounts for a copy the app was holding the whole time.
|
||||
- **A reply ends with `send_reply`:** a reply run's answer is not its prose. The last turn must be `send_reply({status:"done"|"working"|"blocked", work?})` with the message beside it, and assistant text with no tool call is a draft the loop returns to the model (`replyDraftNote`, up to `AppData.HarnessReplyDraftsMax`) rather than a message the user sees, though a message written in the turn just before is taken as the one beside `send_reply` when it carries none (models that think the text travels with the call wrote the answer there), and a run that still ends with no message fails saying so rather than that its answer was wrong (`unsentAnswerMessage`). `status:"working"` must queue `work` (`{title,instructions,computer_id?,separate?,max_steps?}`, through `queueBotTask`, the same guards and brief as `start_task`) or follow a run already started from this reply, so a message that says work is running can only exist when the job does; `done` and `blocked` carry no work, and `work` beside either is refused. `start_task` is not a reply tool (it stays in task runs for a hand-off), `send_reply` is a closing tool beside `ask_user`/`suggest_next_steps`, and a task report ends the same way. If the run never closes, the job fails honestly and the thread offers Retry; work queued earlier in the run is cancelled with the unsent message. The review reads the status: a `done`/`blocked` message that says work is under way is faulted even when some unrelated run is open, and `hasOpenWork` takes the current `job_id` (`exclude_job_id`) so a task report can't count its own job as open work.
|
||||
- **A reply ends with `send_reply`:** a reply run's answer is not its prose. The last turn must be `send_reply({status:"done"|"working"|"blocked", work?})` with the message beside it, and assistant text with no tool call is a draft the loop returns to the model (`replyDraftNote`, up to `AppData.HarnessReplyDraftsMax`) rather than a message the user sees. A bare `send_reply` does not ship that draft on the first pass (`replyNoTextNote`): the model writes the whole message again in that turn, which is also the only turn that may call `suggest_next_steps` or `ask_user` beside it (any other tool is `replyClosingMixedNote` and unsent). A finished draft is carried only after that one reminder still gets no text (`draft_carried`); a draft that stops in a table, a fence or a bare marker (`unfinishedAnswerText`) is sent back once and never carried. A run that still ends with no message fails saying so rather than that its answer was wrong (`unsentAnswerMessage`). `status:"working"` must queue `work` (`{title,instructions,computer_id?,separate?,max_steps?}`, through `queueBotTask`, the same guards and brief as `start_task`) or follow a run already started from this reply, so a message that says work is running can only exist when the job does; `done` and `blocked` carry no work, and `work` beside either is refused. `start_task` is not a reply tool (it stays in task runs for a hand-off), `send_reply` is a closing tool beside `ask_user`/`suggest_next_steps`, and a task report ends the same way. If the run never closes, the job fails honestly and the thread offers Retry; work queued earlier in the run is cancelled with the unsent message. The review reads the status: a `done`/`blocked` message that says work is under way is faulted even when some unrelated run is open, and `hasOpenWork` takes the current `job_id` (`exclude_job_id`) so a task report can't count its own job as open work.
|
||||
- **A bot can't vouch for itself:** a run's tool calls (`tool_uses`, names and ok, never arguments) go to the wrap-up turn when steps run out and onto the result message as `bot_messages.tool_log`; history follows each recorded bot message with an `[App record: ...]` line (`botMessagesToHarness`), and copies of that line in an answer are stripped (`stripAppRecords`, which shares the line shape with `appRecordLines`). Before a reply or a task report goes out, `reviewBotReply` (the loop's `review`, wired for both by `reviewRunAnswer`) sends it back when it names a `[file:ID]`/`[task:ID]`/`[graphic:ID]` that doesn't exist for the user, a task named in plain prose (`task #16`, `mentionedTaskIds`) whose row is gone (a row the user cannot open is left alone), a `[setting:...]` ref the app can't resolve (`unresolvedSettingRefs`), a `[suggestion:ID]`/`[question:ID]`/`[plan:ID]` ref it wrote itself (`AppCardRefTools`: the app adds those from the tool that made the card, so a written one is made up or copied from an earlier message and the user reads "not available"), or says work is under way, that a report will follow, or that it is about to do the work ("Let me check", "I'll connect and inspect", "next I'll", "Starting the conversion run now") (`claimsWorkUnderWay`, which reads a promise only when its own sentence is the commitment, so an offer waiting on the user is left alone) with no run this reply started and nothing open from the session: bots wrote "I'm scanning now" plus made-up results in one answer, and a reply promising to check the articles and then starting nothing left the user waiting for a report nobody would send. It also faults the app's own state described from nothing (`replyAppStateClaims`, skipped when `read_message_usage`/`read_settings` answered): how the model "routing" resolves or which model the tool sends, a run "killed" or "stopped" (Stop is the user's), and the model rest called unlimited or restart-only, each written by a bot that had only an `HTTP 404` to go on and told the user a model and a mechanism nobody had configured. Review runs on every answer it writes, up to `AppData.HarnessReviewRewrites` rewrites (a repeat of the faulted message is told so, `repeatedAnswerNote`); past that the answer is never sent and the job fails instead (`review_note` -> `BotJobFatalError`, a reply and a task report alike; a rewrite that lands on the wrap up is reviewed there and refused, not sent on), since a model that kept writing the same thing sends the claim anyway. **A fault must be something the bot can stop making:** only a whole line in the app's own record shape naming tools this reply didn't call is a forgery (`unsupportedAppRecordLines`) - the same text quoted inside a sentence is the bot naming its mistake, and job #468 faulted three rewrites in a row for that quote alone, so the lie stayed and the correction never reached the user. No fault note may itself contain the shape it faults or a `claimsWorkUnderWay` phrase. Tool names copied into a list (`WorkStartingTools`, `AppCardRefToolNames`, `WritingToolNames`, `WrapUp*ToolNames`) are pinned to the tools the harness declares by `src/harness/tools/tool-name-lists.test.ts` (`ask_crew` outlived its rename to `ask_bot`, so a reply that really had asked the crew was faulted for saying so). A long bot message whose run called no tools shows "No tools used" (`MessageNoToolsChip`).
|
||||
- **A reply's `send_reply` work and `start_task`/`delegate_task` jobs are runs, not tasks:** their results say `Run #<job id>` and that `list_tasks` doesn't show them (bots sent users to the tracker for them). `queueBotTask` refuses a second open run in its session on the same computer unless `separate` (it would only wait behind it) and says how many runs are ahead on that computer. Its `max_steps` (`params.max_steps`) caps the run below the install's limit; the brief alone never did. Nothing wakes a bot when a run ends, so different follow-up work is queued at once with `separate`, never promised for later (`send_reply`'s work, `start_task`, `chatReplyNote`).
|
||||
- **Replies take in messages sent mid-run** (`incoming`, `IncomingMessagesNote`, redraft); separate requests are acknowledged with `send_message` (interim). A queued reply finishes silently only when a finished reply already read every user message (`hasUnansweredMessage`), never by who wrote last; a retry (`params.retry_of`) always runs. **Task runs take them in too** (`taskIncoming`, only runs the user follows: no routines, hook calls or rooms): everything the user wrote since the run was queued, at the start, between steps, past a report not yet out and by the wrap up (`incoming_notes`, `TaskIncomingNote`); a correction changes the work, anything else is left to the chat, and crew messages to the reply they wake. A reply is told which runs open in its session hear the user (`openRunsNote`), so a correction never starts a second run.
|
||||
@@ -212,7 +212,7 @@ A user's own running browser, reached over a browser MCP server they run beside
|
||||
|
||||
### Knowledgebases
|
||||
|
||||
A fourth extension kind (`ExtensionTables.knowledgebase`): `knowledgebases` given per bot (`bot_knowledgebases`), per workspace (`workspace_knowledgebases`) or every bot (`all_bots`), through the same add/remove/access/default paths as skills (`list_extensions` and `delete_extension` leave them out, and so do the proposal cards). Documents (`knowledgebase_documents`: an upload in private `media`, paradigm `knowledgebase-document`, or written `content`) are chunked into `knowledgebase_chunks` and embedded into the `knowledgebase_vectors` vec0 table by the file-ingest worker (`file_ingest_queue.document_id`, `ingestKnowledgebaseDocument`), always with the install's embedding model; old passages stay until the new ones are in, `embedding_model` records where vectors came from; whatever can change the install's model (default settings, a provider saved or deleted, the hourly catalog sync) calls `reindexAfterEmbeddingChange`, and Re-index reads a knowledgebase again by hand. Word search runs on `knowledgebase_chunks_fts`, an FTS5 table (`unicode61 remove_diacritics 2`) made by `ensureKnowledgebaseFts` (FTS5 can't be declared in the schema; sync leaves undeclared tables alone), backfilled at boot by `syncKnowledgebaseFts`, ranked by BM25 with a scored `LIKE` fallback for unspaced scripts (`knowledgebaseWordQuery`); every write and delete of `knowledgebase_chunks` updates it. Ingest jobs (`settleFailedIngestJob`) wait without spending an attempt while every embedding model rests, fail at once on an error retrying can't fix, and a document whose model refused keeps its new passages for word search (counted as needing re-index, not failed). Runs get `search_knowledgebase`/`read_knowledgebase_document` (`openBotKnowledgebases`, limited to the run's ones) and replies start with passages found for the unanswered messages (`grabKnowledgebaseContext`); passages are fenced (`knowledgebasePassageBlock`) and `KnowledgebasesNote` says they're never instructions. UI: Settings > Knowledgebases (super admin edits and fills; admins set access), a Knowledgebases group on bot/workspace settings, and the composer's own button beside Tools (`ComposerToolsModal` with `composerKnowledgebasesCopy`). Deleting one deletes its documents' vectors, chunks, media and links explicitly. **The coordinator manages them when the super admin asks for it in the chat:** `grabCoordinatorKnowledgebaseTools` (`src/harness/tools/bot/knowledgebases/`, pushed beside `grabCoordinatorExtensionTools` in `grab-bot-chat-tools.ts` and in the coordinator branch of `run-bot-task.ts`) gives `list_knowledgebases` in any of its runs, and `save_knowledgebase` (name, description, on/off, who gets it through `set_extension_access`), `add_knowledgebase_document` (`file_id` a saved file, `media_id` the user's own upload, `path` on a computer, or `text`), `delete_knowledgebase_document`, `delete_knowledgebase` and `reindex_knowledgebase` only in a reply or a task the user follows (`attended`: never a schedule, hook call or hidden session), each checking the super admin again. A document from a file is copied into private `media` first (`recordKnowledgebaseFile`, shared with `upload-document.ts`, and the same refusal in `knowledgebaseFileProblem`), so it stays after the computer or the file is gone; a task's own computer is the default for `path`. `AccessExtensionKindSchema` adds `knowledgebase` for access only: `ExtensionKindSchema` stays three kinds, since `delete_extension`'s last branch deletes a custom tool.
|
||||
A fourth extension kind (`ExtensionTables.knowledgebase`): `knowledgebases` given per bot (`bot_knowledgebases`), per workspace (`workspace_knowledgebases`) or every bot (`all_bots`), through the same add/remove/access/default paths as skills (`list_extensions` and `delete_extension` leave them out, and so do the proposal cards). Documents (`knowledgebase_documents`: an upload in private `media`, paradigm `knowledgebase-document`, or written `content`) are chunked into `knowledgebase_chunks` and embedded into the `knowledgebase_vectors` vec0 table by the file-ingest worker (`file_ingest_queue.document_id`, `ingestKnowledgebaseDocument`), always with the install's embedding model; old passages stay until the new ones are in, `embedding_model` records where vectors came from; whatever can change the install's model (default settings, a provider saved or deleted, the hourly catalog sync) calls `reindexAfterEmbeddingChange`, and Re-index reads a knowledgebase again by hand. Retry failed (`retryFailedDocuments`, the row menu's Retry failed and `retry_failed_documents`) queues only the documents with `ingest_error`, clearing it so the ten-minute sweep can pick them up too. Word search runs on `knowledgebase_chunks_fts`, an FTS5 table (`unicode61 remove_diacritics 2`) made by `ensureKnowledgebaseFts` (FTS5 can't be declared in the schema; sync leaves undeclared tables alone), backfilled at boot by `syncKnowledgebaseFts`, ranked by BM25 with a scored `LIKE` fallback for unspaced scripts (`knowledgebaseWordQuery`); every write and delete of `knowledgebase_chunks` updates it. Ingest jobs (`settleFailedIngestJob`) wait without spending an attempt while every embedding model rests, fail at once on an error retrying can't fix, and a document whose model refused keeps its new passages for word search (counted as needing re-index, not failed). Runs get `search_knowledgebase`/`read_knowledgebase_document` (`openBotKnowledgebases`, limited to the run's ones) and replies start with passages found for the unanswered messages (`grabKnowledgebaseContext`); passages are fenced (`knowledgebasePassageBlock`) and `KnowledgebasesNote` says they're never instructions. UI: Settings > Knowledgebases (super admin edits and fills; admins set access), a Knowledgebases group on bot/workspace settings, and the composer's own button beside Tools (`ComposerToolsModal` with `composerKnowledgebasesCopy`). Deleting one deletes its documents' vectors, chunks, media and links explicitly. **The coordinator manages them when the super admin asks for it in the chat:** `grabCoordinatorKnowledgebaseTools` (`src/harness/tools/bot/knowledgebases/`, pushed beside `grabCoordinatorExtensionTools` in `grab-bot-chat-tools.ts` and in the coordinator branch of `run-bot-task.ts`) gives `list_knowledgebases` in any of its runs, and `save_knowledgebase` (name, description, on/off, who gets it through `set_extension_access`), `add_knowledgebase_document` (`file_id` a saved file, `media_id` the user's own upload, `path` on a computer, or `text`), `delete_knowledgebase_document`, `delete_knowledgebase`, `retry_failed_documents` and `reindex_knowledgebase` only in a reply or a task the user follows (`attended`: never a schedule, hook call or hidden session), each checking the super admin again. A document from a file is copied into private `media` first (`recordKnowledgebaseFile`, shared with `upload-document.ts`, and the same refusal in `knowledgebaseFileProblem`), so it stays after the computer or the file is gone; a task's own computer is the default for `path`. `AccessExtensionKindSchema` adds `knowledgebase` for access only: `ExtensionKindSchema` stays three kinds, since `delete_extension`'s last branch deletes a custom tool.
|
||||
|
||||
sqlite-vec limits: metadata columns are NOT NULL; side-car columns can't be filtered with `MATCH` (filter in code). **Never pass `--vector` to `bunx bun-sqlite schema` in `entrypoint.sh`** (wipes vectors on boot). Changing `AppData.EmbeddingDimensions` needs a manual `--vector` run and a re-index.
|
||||
|
||||
@@ -230,7 +230,7 @@ Read-only browser of every volume (`src/utils/storage-volumes.ts`: bots, workspa
|
||||
- **Catalog:** `harness_models`, synced hourly. OpenRouter "free" means `:free` or `openrouter/free`, never zero prices. Auto picks: `rank-auto-models`. A custom provider's `/models` lists ids and nothing else, so its form takes a **context window** (`harness_providers.context_length`) and the sync writes it into every model that reports none of its own (`modelContextLength`); leaving it empty leaves them unknown and a run assumes `AppData.HarnessUnknownContextWindow`, since a model with no window at all gets 70% of that as its working context no matter what `harness_context_budget_tokens` says.
|
||||
- **Calling:** `resolveHarnessCandidates` -> `withCandidates` with process-wide cooldowns; errors are `HarnessError`. Order: the pick, the text setting's fallback models (`fallback_model_ids` in its options, up to `AppData.HarnessTextFallbackModelsMax`, any provider), then the free automatic picks (when `fallback` is on). Every failure is logged (`logCandidateFailure`) and benches its model (or provider, for a key or credits) for the model rest (app setting `harness_model_rest_seconds`, Settings > General run limits, default `AppData.HarnessModelRestMs`, or until the setting changes and the app restarts when the rest is unlimited; the bench lives on a `globalCache` slot (`cobble.harnessCooldowns`) so a run-limits save clears the copy the queue reads, and that save, like queue startup, wakes the jobs a rest had parked ahead of time (`releaseRestingBotJobs`)), never longer, even past a `Retry-After`: one failure once left every reply on a weak free model for an hour. A message answered by a model in place of the one ahead of it shows the fallback on its usage chip (`fell_back_from`/`resting` in `token_usages.settings`). A call that only reaches benched models records a failed-call row for each resting candidate (`recordHarnessFailure`, no re-log of the outage) so the message shows why nothing was tried, and its error names Settings > Models; a resting call says how long the wait is ("The next try is possible in 27s."), since told only "trying again shortly" a bot told the user the models were benched until a restart. A failure carries the model the candidate ran on, the request's method and address, and a hint when a 404/405 came back with an empty body (no endpoint there), so the tool's message names the pick instead of leaving the bot to guess it: with only "HTTP 404", a production bot invented a model and its routing. Entry points under `text/`, `media/`, `audio/`, `image/`, `embeddings/`. `run-text-loop.ts` sticks to one model (an automatic pick only until the pick or a fallback model has rested), caps steps (`grabHarnessMaxToolSteps`, `grabReplyMaxToolSteps`; routines and hook calls `grabUnattendedMaxToolSteps`, all unlimited by default, so a run's job deadline and its prompt-token budget are what end it; every run limit reads as `RunLimit` in `src/utils/run-limit.ts`, `number` or `"unlimited"`, saved as `-1` on the settings form and `"unlimited"` in `app_settings`; a run is told once, `stepsLowWarningLeft` steps before the wrap up, to save its report, and the wrap up keeps `WrapUpToolNames` (`write_file`, `import_file`, and `send_reply` for a reply's answer or `start_task` for work a task run can't finish: a 20-step reply used for research otherwise left the writing undone and the next reply had the same budget) for a saving-or-answer turn before the last turn with no tools, since runs measured to their last step with the report unwritten) and the prompt tokens one run may spend (`grabRunMaxPromptTokens`, 4M by default: at 40M one task run spent 195 turns and 30M tokens re-reading its own notes with the ceiling never in reach; a run is told once, a quarter in and only while it has produced nothing (`commitEarlyNote`, `isWritingTool`, `AppData.HarnessRunTokensCommitShare`), to land one piece of the work, then once at `AppData.HarnessRunTokensWarnShare` of it to land the rest, `tokensLowNote`, then the wrap up). Results are cut keeping their start and their end (`run-tool-call.ts`, `capToolOutput`), never the start alone: a `du`/`find` sweep's totals are its last lines. A read the run already made is answered from that answer (`RepeatableToolNames`, `repeatToolCallKey`, `alreadyRanToolNote`): calling `read_file`, `list_files`, `search_knowledgebase`, `list_tasks` and the like again with the same arguments returns a pointer to the output above instead of running again, and works. So a run whose brief can be wrong is told the tree wins over the brief, and told that handing the rest on with `start_task` is following the plan. `computer_bash` whose command provably only reads (`isReadOnlyCommand`: an allow-listed program and no redirect, no `tee`/`xargs`, no writing git subcommand) is a read here too; any other tool (a write, a bash command that isn't one) clears what was remembered, so a file read, edited and read again is read again. A call that failed is answered from that failure the same way, past one retry (`toolCallKey`, `AppData.HarnessSameFailureRetries`, `failedToolCallNote`): five identical failing commands once cost five turns, each resending the whole transcript. A turn that wrote a message and then called any other tool is told once that the message never went out (`answerNotSentNote`), since only the last one is sent: a run that doesn't know ends with the tail of an answer it already wrote.
|
||||
- **Token use:** every turn resends the system prompt, tool definitions and whole transcript, so a run's cost grows with its length squared (production lost 39M tokens on one routine run on a 1M-window model that never trimmed). Keep turns small: `fitTranscriptToContext` trims to the working context (`grabContextBudgetTokens`, never just the window), cutting in one block down to 60% so the cached prefix holds between cuts, and a trimmed tool result keeps its start and its end (`TrimmedKeepChars`) instead of being replaced whole: the old note said "call it again if you still need it", so runs did, paying twice for the same output; every `AppData.HarnessTrimNoteEvery` trimmed turns the run is told its earlier readings were cut (`contextTrimmedNote`, traced as `trimmed`), since trimming is otherwise invisible and a run re-reads what it thinks it never saw; the newest messages are never trimmed; **the user's own text is never trimmed** (a request can't be lost mid-run), so a run whose prompt is still over the working context after everything trimmable was cut is told once (`oversizedRequestNote`: work in pieces, don't paste more in, say what it could not reach), and `fitTranscriptToContext` reports it as `over_budget`; only the newest `browser_snapshot` and `browser_find` per browser stay (`supersedeToolOutputs`); browser results are capped lower (`HarnessBrowserResultMaxChars`); MCP and user-browser tools are `deferred` (listed by name in the prompt, loaded with `load_tools`) once their definitions pass `HarnessDeferToolsMinChars`, loaded ones appended last. Don't rewrite earlier transcript messages every turn (it breaks providers' prompt caches); `token_usages.cached_tokens` shows what was served from cache. Models that can't take an image/audio part get it read by vision/transcription first (`prepareMessagesForModel`, per candidate). Tool images (screenshots, `read_file` images) are never read by the tool: tools return `{ text, images }`, the loop shows them in a user turn after the results (`toolImagesTurn`, fenced as tool output), and `prepareMessagesForModel` decides. A text model looks at images itself (attachments too) only when its text setting has "Use the model's own media reading" on (`sees_images` in the text harness options, per default/bot/workspace row, `textSeesImages`) and it takes image input: the catalog's `input_modalities` decide, so a custom provider's bare model id gets `guessModelModalities`, which says text-only for anything it doesn't recognise and then `sees_images` reads nothing (the Models page says so under the checkbox, `HarnessSeesImagesNote`, since the setting is otherwise silently useless). Otherwise the vision harness reads them (with the tool's `focus` and `redact`; pixels a seeing model gets can't be redacted). Readings are kept across runs by `MediaReadings` (`HarnessMediaReadingsCached`), keyed by `imageReadingKey`, so the same image is read once rather than once per reply; a reading made to `redact` a secret is never kept there. Only the newest `AppData.HarnessToolImagesKept` stay (`dropOldToolImages`).
|
||||
- **Per-bot models:** workspace row > bot row > default; the coordinator always uses the defaults. Every entry point takes `bot_id` and passes it on. **Embeddings are install-wide** (`install_wide` in `Harnesses`, `isInstallWideHarness`): `grabHarnessSetting` ignores bot/workspace rows for them, the per-bot/workspace forms don't list them and saving one is refused, so every stored vector comes from one model. Shared form `settings/models/(partials)/harness-settings-form.tsx`. A provider that embeds a passage and a query differently (NVIDIA's asymmetric models) is told which through `input_type`, from `embedText`'s `purpose`; `embed.ts` finds that out on the first 400 that names the field and remembers it per provider and model for the process.
|
||||
- **Per-bot models:** workspace row > bot row > default; the coordinator always uses the defaults. Every entry point takes `bot_id` and passes it on. **Embeddings are install-wide** (`install_wide` in `Harnesses`, `isInstallWideHarness`): `grabHarnessSetting` ignores bot/workspace rows for them, the per-bot/workspace forms don't list them and saving one is refused, so every stored vector comes from one model. Shared form `settings/models/(partials)/harness-settings-form.tsx`. A provider that embeds a passage and a query differently (NVIDIA's asymmetric models) is told which through `input_type`, from `embedText`'s `purpose`; `embed.ts` finds that out on the first 400 that names the field and remembers it per provider and model for the process. A provider that caps a batch below `AppData.EmbeddingBatchSize` (Alibaba's Model Studio: "batch size is invalid, it should not be larger than 20") is answered by retrying the refused batch at the size it named, remembered per provider and model (`smaller-batch-limit.ts`), so one document's large batch no longer fails the whole ingest.
|
||||
- **Generation settings follow the model:** a model takes only the parameters its provider advertises (`modelAdvertisesParameter`, `src/dict/harness-parameter-dict.ts`); a custom provider's `/models` lists ids only, so its models take none and the form hides the Model settings target. The wire sends only advertised parameters (`grabChatParams`), never a value saved on another model. Switching the model or the provider clears the saved generation settings and voice (`nextHarnessModelValue` / `nextHarnessProviderValue`), so a temperature tuned for one model never rides to another that rejects it.
|
||||
- **Tools:** `HarnessTool` built per run; own tools validate with zod. `run-tool-call.ts` reports errors back to the model and caps each call at the tool's `timeout_ms` (its own, else `AppData.HarnessToolTimeoutMs`; `null` means no cap, as `computer_bash` has); a `computer_*`/`browser_*` call from a run without them (a reply) is told to use `send_reply` with work, or `start_task` in a task run (`unknownToolMessage`). Bot tools in `src/harness/tools/bot/` (memory, instructions, tasks, schedules, `read_settings`, `read_message_usage`, `send_reply`, `start_task`, `hand_over_task`, `update_requester` (an interim word to the bot that asked while a crew request is open), coordinator's crew management, `delegate_task` and `hand_over_schedule`, with results relayed back by `relayJobToRequester`).
|
||||
- **Extensions:** MCP servers (`mcp_servers`, remote or stdio), custom tools (`custom_tools`: http, script, prompt) and skills (`skills`, runbooks loaded with `load_skill`). Given per bot / per workspace (`botExtensionsSql`); `all_bots` only decides what new bots get. Templates `{{args.x}}`/`{{env.KEY}}` via `fillTemplate`; secrets redacted from results. A prompt-kind tool's filled template is the model's own input, so a secret env fills in as its `[KEY]` marker there, never its value (`runPromptTool`); http and script tools use secrets server-side, where the value never reaches the model. stdio servers run in a per-process pool. Skill body limits are app settings (`grabSkillBodyMaxChars`, `grabSkillBodyShownChars`). A skill proposal says what it changes (`skillProposalChanges`) to the bot and in the confirm outcome, takes no unknown keys (a misnamed `body` would re-propose the saved runbook) and is refused when it changes nothing.
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "cobble",
|
||||
"version": "0.24.7",
|
||||
"version": "0.24.8",
|
||||
"module": "index.ts",
|
||||
"type": "module",
|
||||
"private": true,
|
||||
|
||||
@@ -507,13 +507,13 @@ export const closingNoTextNote = `The card you just put up has no message beside
|
||||
* never queued. Bounded by `AppData.HarnessReplyDraftsMax`, then the run
|
||||
* fails honestly rather than sending it.
|
||||
*/
|
||||
export const replyDraftNote = `That message was not sent: a reply ends with send_reply, and text on its own is a draft. Write it again beside send_reply: status "done" when nothing is running after it, "working" with work (or after a run you already started) when something is, or "blocked" when it can't go on. The text beside the call is what the user reads.`;
|
||||
export const replyDraftNote = `That message was not sent: a reply ends with send_reply, and text on its own is a draft. Write the whole message again in the same turn as send_reply: status "done" when nothing is running after it, "working" with work (or after a run you already started) when something is, or "blocked" when it can't go on. A call with no text beside it sends nothing, and an earlier draft is not filled in for you. In that same turn, and only then, call suggest_next_steps or ask_user when one of them belongs with the answer. The text beside the call is what the user reads, so finish every table, list and code fence before you send it.`;
|
||||
|
||||
/**
|
||||
* Told when `send_reply` worked but the turn said nothing beside it: the
|
||||
* user would get an empty line, and the status alone is not a message.
|
||||
*/
|
||||
export const replyNoTextNote = `The send_reply call went through, but there is no message beside it, so the user would get an empty line. Write the message beside send_reply now and call it again: status "done", "working" (with work, or after a run you started) or "blocked".`;
|
||||
export const replyNoTextNote = `The send_reply call went through, but there is no message beside it, so nothing was sent. An earlier draft is not the message: write the whole message again beside send_reply and call it again, status "done", "working" (with work, or after a run you started) or "blocked". suggest_next_steps or ask_user may share that turn when one of them belongs with the answer. Finish every table, list and code fence in the text you write there.`;
|
||||
|
||||
/**
|
||||
* Told when a turn tried to end without `send_reply` at all: a card alone or
|
||||
@@ -527,7 +527,7 @@ export const replyClosingRequiredNote = `That turn ended without send_reply, so
|
||||
* can send the message, since the other calls' results go into the
|
||||
* conversation after it.
|
||||
*/
|
||||
export const replyClosingMixedNote = `send_reply has to be the only call in its turn: this turn also did other work, so the message was not sent. Call send_reply on its own with the message beside it, after the tools you still need have run.`;
|
||||
export const replyClosingMixedNote = `send_reply's turn can also call suggest_next_steps or ask_user, and nothing else: this turn did other work, so the message was not sent. Finish that work first, then call send_reply with the whole message beside it.`;
|
||||
|
||||
/**
|
||||
* Told when `send_reply` itself refused the turn (status "working" with
|
||||
|
||||
@@ -22,6 +22,7 @@ type ComputerLinkRow = BUN_SQLITE_COBBLE_HOST_DIRECTORY_COMPUTERS & {
|
||||
|
||||
type WorkspaceLinkRow = BUN_SQLITE_COBBLE_HOST_DIRECTORY_WORKSPACES & {
|
||||
workspace_name?: string | null;
|
||||
image_media_id?: number | null;
|
||||
};
|
||||
|
||||
type CheckRow = BUN_SQLITE_COBBLE_HOST_DIRECTORY_CHECKS;
|
||||
@@ -61,7 +62,8 @@ export default async function grabHostDirectories({
|
||||
values: filtered ? [host_directory_id] : [],
|
||||
}),
|
||||
BunSQLite.sql<WorkspaceLinkRow>({
|
||||
sql: `SELECT hdw.*, w.name AS workspace_name FROM host_directory_workspaces hdw
|
||||
sql: `SELECT hdw.*, w.name AS workspace_name, w.image_media_id AS image_media_id
|
||||
FROM host_directory_workspaces hdw
|
||||
LEFT JOIN workspaces w ON w.id = hdw.workspace_id
|
||||
${filtered ? "WHERE hdw.host_directory_id = ?" : ""}
|
||||
ORDER BY hdw.id ASC`,
|
||||
|
||||
@@ -8,8 +8,9 @@ type Params = {
|
||||
|
||||
/**
|
||||
* Reads every document of a knowledgebase again (after the install's
|
||||
* embedding model changed, or one failed). Each keeps its old passages
|
||||
* until its new ones are in. Returns how many were queued.
|
||||
* embedding model changed). Each keeps its old passages until its new
|
||||
* ones are in. Documents whose last read failed, and only those, are
|
||||
* `retryFailedDocuments`. Returns how many were queued.
|
||||
*/
|
||||
export default async function reindexKnowledgebase({ knowledgebase_id }: Params) {
|
||||
const knowledgebase = await grabKnowledgebase({ knowledgebase_id });
|
||||
|
||||
@@ -0,0 +1,44 @@
|
||||
import BunSQLite from "@moduletrace/bun-sqlite";
|
||||
import enqueueDocumentIngest from "@/src/file-ingest/enqueue-document-ingest";
|
||||
import grabKnowledgebase from "./grab-knowledgebase";
|
||||
|
||||
type Params = {
|
||||
knowledgebase_id: number | string;
|
||||
/**
|
||||
* One document. Left out, every document of the knowledgebase whose
|
||||
* last read failed.
|
||||
*/
|
||||
document_id?: number | string;
|
||||
};
|
||||
|
||||
/**
|
||||
* Queues the documents whose last read failed, and leaves the ones that
|
||||
* already succeeded. Clearing `ingest_error` lets `ingest-pending-files`
|
||||
* pick up one that was never read, if the queue write doesn't land.
|
||||
* Returns how many were queued.
|
||||
*/
|
||||
export default async function retryFailedDocuments({ knowledgebase_id, document_id }: Params) {
|
||||
const knowledgebase = await grabKnowledgebase({ knowledgebase_id });
|
||||
|
||||
const documents = await BunSQLite.sql<{ id: number }>({
|
||||
sql: `SELECT id FROM knowledgebase_documents
|
||||
WHERE knowledgebase_id = ? AND ingest_error IS NOT NULL AND (? IS NULL OR id = ?)`,
|
||||
values: [knowledgebase.id, document_id ?? null, document_id ?? null],
|
||||
});
|
||||
|
||||
const ids = (documents.payload || []).map((document) => document.id).filter(Boolean);
|
||||
|
||||
if (!ids.length) return 0;
|
||||
|
||||
await BunSQLite.sql({
|
||||
sql: `UPDATE knowledgebase_documents SET ingest_error = NULL, updated_at = ?
|
||||
WHERE knowledgebase_id = ? AND id IN (${ids.map(() => "?").join(", ")})`,
|
||||
values: [Date.now(), knowledgebase.id, ...ids],
|
||||
});
|
||||
|
||||
for (const id of ids) {
|
||||
await enqueueDocumentIngest({ document_id: id });
|
||||
}
|
||||
|
||||
return ids.length;
|
||||
}
|
||||
@@ -177,4 +177,67 @@ describe("embed asks for input_type when the model needs it", () => {
|
||||
).rejects.toThrow("model not found");
|
||||
expect(sent).toHaveLength(1);
|
||||
});
|
||||
});
|
||||
|
||||
describe("embed fits a provider's own batch cap", () => {
|
||||
/**
|
||||
* Alibaba's Model Studio compatible API: more than 20 texts in one batch
|
||||
* is refused whole, with the limit in the message.
|
||||
*/
|
||||
const alibaba: HarnessCandidate = {
|
||||
key: "20:qwen-embed",
|
||||
provider: {
|
||||
kind: "custom",
|
||||
base_url: "https://ws-test.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1",
|
||||
name: "Alibaba Cloud",
|
||||
},
|
||||
model: {
|
||||
slug: "qwen3.7-embedding",
|
||||
input_modalities: ["text"],
|
||||
output_modalities: ["text"],
|
||||
supports_tools: false,
|
||||
},
|
||||
source: "pinned",
|
||||
};
|
||||
|
||||
const capAtTwenty = (body: any) => {
|
||||
if (body.input.length > 20)
|
||||
throw new HarnessError({
|
||||
message:
|
||||
"Alibaba Cloud: <400> InternalError.Algo.InvalidParameter: Value error, batch size is invalid, it should not be larger than 20.: input.contents",
|
||||
status: 400,
|
||||
});
|
||||
|
||||
return {
|
||||
data: body.input.map((_: string, index: number) => ({ index, embedding: [1, index] })),
|
||||
};
|
||||
};
|
||||
|
||||
test("the refused batch is retried at the size named, and that size is kept", async () => {
|
||||
answer = capAtTwenty;
|
||||
|
||||
const many = Array.from({ length: 45 }, (_, i) => `chunk ${i}`);
|
||||
const first = await embed({ candidate: alibaba, input: many, purpose: "passage", signal });
|
||||
|
||||
expect(first.vectors).toHaveLength(45);
|
||||
expect(sent.map((body) => body.input.length)).toEqual([32, 20, 20, 5]);
|
||||
expect(first.vectors[44]).toEqual([1, 4]);
|
||||
|
||||
await embed({ candidate: alibaba, input: ["a", "b", "c"], purpose: "passage", signal });
|
||||
expect(sent.map((body) => body.input.length)).toEqual([32, 20, 20, 5, 3]);
|
||||
});
|
||||
|
||||
test("one text refused for its size is a failure, not a retry loop", async () => {
|
||||
answer = () => {
|
||||
throw new HarnessError({
|
||||
message: "Alibaba Cloud: Value error, batch size is invalid, it should not be larger than 0.",
|
||||
status: 400,
|
||||
});
|
||||
};
|
||||
|
||||
await expect(
|
||||
embed({ candidate: alibaba, input: ["a document's text"], purpose: "passage", signal }),
|
||||
).rejects.toThrow("batch size is invalid");
|
||||
expect(sent).toHaveLength(1);
|
||||
});
|
||||
});
|
||||
@@ -2,7 +2,8 @@ import { AppData } from "@/src/data/app-data";
|
||||
import HarnessError from "../../harness-error";
|
||||
import type { HarnessAdapter, HarnessCandidate } from "../../types";
|
||||
import grabProviderPreset from "../grab-provider-preset";
|
||||
import providerRequest from "./provider-request";
|
||||
import sendEmbeddingsBatch from "./send-embeddings-batch";
|
||||
import smallerBatchLimit from "./smaller-batch-limit";
|
||||
|
||||
/**
|
||||
* Providers that want `input_type` on every batch, by provider and model:
|
||||
@@ -13,6 +14,14 @@ import providerRequest from "./provider-request";
|
||||
*/
|
||||
const wantsInputType = new Set<string>();
|
||||
|
||||
/**
|
||||
* The largest batch a provider and model already refused a bigger one over.
|
||||
* Alibaba's Model Studio caps a batch at 20 and refuses the whole request, so
|
||||
* the size it named is remembered for the process: every later document goes
|
||||
* straight to a batch that fits instead of paying for the refusal again.
|
||||
*/
|
||||
const batchLimits = new Map<string, number>();
|
||||
|
||||
const inputTypeKey = ({ provider, model }: HarnessCandidate) =>
|
||||
`${provider.base_url}|${model.slug}`;
|
||||
|
||||
@@ -22,7 +31,7 @@ const inputTypeKey = ({ provider, model }: HarnessCandidate) =>
|
||||
* request the provider may refuse.
|
||||
*/
|
||||
const embed: HarnessAdapter["embed"] = async ({ candidate, input, purpose, signal }) => {
|
||||
const { provider, model } = candidate;
|
||||
const { provider } = candidate;
|
||||
const preset = grabProviderPreset({ kind: provider.kind });
|
||||
const key = inputTypeKey(candidate);
|
||||
const vectors: number[][] = [];
|
||||
@@ -33,49 +42,46 @@ const embed: HarnessAdapter["embed"] = async ({ candidate, input, purpose, signa
|
||||
let prompt_tokens = 0;
|
||||
|
||||
/**
|
||||
* Every OpenAI-compatible API puts embeddings at `/embeddings`.
|
||||
* The batch size in use: the install's, or the smaller one this provider
|
||||
* and model already made clear it wants.
|
||||
*/
|
||||
const path = "/embeddings";
|
||||
let limit = batchLimits.get(key) || AppData.EmbeddingBatchSize;
|
||||
|
||||
for (let start = 0; start < input.length; start += AppData.EmbeddingBatchSize) {
|
||||
for (let start = 0; start < input.length; ) {
|
||||
const batch = input
|
||||
.slice(start, start + AppData.EmbeddingBatchSize)
|
||||
.slice(start, start + limit)
|
||||
.map((text) => text.slice(0, AppData.EmbeddingMaxInputChars));
|
||||
|
||||
const body = { model: model.slug, input: batch };
|
||||
let res: Response;
|
||||
|
||||
try {
|
||||
res = await providerRequest({
|
||||
provider,
|
||||
path,
|
||||
json: wantsInputType.has(key) ? { ...body, input_type: purpose } : body,
|
||||
const sent = await sendEmbeddingsBatch({
|
||||
candidate,
|
||||
batch,
|
||||
purpose,
|
||||
signal,
|
||||
candidate_key: candidate.key,
|
||||
with_input_type: wantsInputType.has(key),
|
||||
});
|
||||
|
||||
if (sent.asked_input_type) wantsInputType.add(key);
|
||||
|
||||
res = sent.res;
|
||||
} catch (error) {
|
||||
/**
|
||||
* The provider says the model embeds a passage and a query
|
||||
* differently and wants to be told which. Ask again with it,
|
||||
* then remember: only the first batch per provider and model
|
||||
* pays for finding out. Any other refusal is the caller's to
|
||||
* classify.
|
||||
* A provider may cap a batch below the install's size (Alibaba's
|
||||
* Model Studio: "batch size is invalid, it should not be larger
|
||||
* than 20"). Nothing of this batch was stored, so retry it whole
|
||||
* at the smaller size, and keep that size for the rest of the
|
||||
* run. Only a size refusal is retried; anything else is the
|
||||
* caller's to classify.
|
||||
*/
|
||||
if (
|
||||
!(error instanceof HarnessError) ||
|
||||
error.status !== 400 ||
|
||||
!/input_type/i.test(error.message)
|
||||
)
|
||||
throw error;
|
||||
const smaller = smallerBatchLimit({ error, size: batch.length });
|
||||
|
||||
res = await providerRequest({
|
||||
provider,
|
||||
path,
|
||||
json: { ...body, input_type: purpose },
|
||||
signal,
|
||||
candidate_key: candidate.key,
|
||||
});
|
||||
wantsInputType.add(key);
|
||||
if (smaller === null) throw error;
|
||||
|
||||
limit = smaller;
|
||||
batchLimits.set(key, smaller);
|
||||
continue;
|
||||
}
|
||||
|
||||
const json = await res.json().catch(() => null);
|
||||
@@ -142,6 +148,8 @@ const embed: HarnessAdapter["embed"] = async ({ candidate, input, purpose, signa
|
||||
}
|
||||
vectors.push(vector);
|
||||
}
|
||||
|
||||
start += batch.length;
|
||||
}
|
||||
|
||||
return {
|
||||
|
||||
@@ -0,0 +1,60 @@
|
||||
import HarnessError from "../../harness-error";
|
||||
import type { HarnessCandidate } from "../../types";
|
||||
import providerRequest from "./provider-request";
|
||||
|
||||
type Params = {
|
||||
candidate: HarnessCandidate;
|
||||
batch: string[];
|
||||
purpose: "query" | "passage";
|
||||
signal: AbortSignal;
|
||||
/**
|
||||
* Ask with `input_type` from the first try (this provider already said
|
||||
* its model needs it).
|
||||
*/
|
||||
with_input_type: boolean;
|
||||
};
|
||||
|
||||
/**
|
||||
* One `/embeddings` request for a batch. A provider that says its model
|
||||
* embeds a passage and a query differently (NVIDIA's asymmetric ones) is
|
||||
* asked again with `input_type`, and the answer says it was, so the caller
|
||||
* can remember and skip the probe next time.
|
||||
*/
|
||||
export default async function sendEmbeddingsBatch({
|
||||
candidate,
|
||||
batch,
|
||||
purpose,
|
||||
signal,
|
||||
with_input_type,
|
||||
}: Params): Promise<{ res: Response; asked_input_type: boolean }> {
|
||||
const { provider, model } = candidate;
|
||||
const body = { model: model.slug, input: batch };
|
||||
const send = async (json: unknown) =>
|
||||
await providerRequest({
|
||||
provider,
|
||||
path: "/embeddings",
|
||||
json,
|
||||
signal,
|
||||
candidate_key: candidate.key,
|
||||
});
|
||||
|
||||
if (with_input_type) {
|
||||
return { res: await send({ ...body, input_type: purpose }), asked_input_type: true };
|
||||
}
|
||||
|
||||
try {
|
||||
return { res: await send(body), asked_input_type: false };
|
||||
} catch (error) {
|
||||
/**
|
||||
* Any other refusal is the caller's to classify.
|
||||
*/
|
||||
if (
|
||||
!(error instanceof HarnessError) ||
|
||||
error.status !== 400 ||
|
||||
!/input_type/i.test(error.message)
|
||||
)
|
||||
throw error;
|
||||
}
|
||||
|
||||
return { res: await send({ ...body, input_type: purpose }), asked_input_type: true };
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import HarnessError from "../../harness-error";
|
||||
import smallerBatchLimit from "./smaller-batch-limit";
|
||||
|
||||
const refusal = ({ message, status = 400 }: { message: string; status?: number }) =>
|
||||
new HarnessError({ message, status });
|
||||
|
||||
describe("smallerBatchLimit", () => {
|
||||
test("takes the limit the provider stated", () => {
|
||||
expect(
|
||||
smallerBatchLimit({
|
||||
error: refusal({
|
||||
message:
|
||||
"Alibaba Cloud: <400> InternalError.Algo.InvalidParameter: Value error, batch size is invalid, it should not be larger than 20.: input.contents",
|
||||
}),
|
||||
size: 32,
|
||||
}),
|
||||
).toBe(20);
|
||||
});
|
||||
|
||||
test("halves the batch when no number is named", () => {
|
||||
expect(
|
||||
smallerBatchLimit({ error: refusal({ message: "batch size is invalid" }), size: 32 }),
|
||||
).toBe(16);
|
||||
});
|
||||
|
||||
test("understands the other wordings providers use", () => {
|
||||
expect(
|
||||
smallerBatchLimit({ error: refusal({ message: "too many inputs in the batch" }), size: 10 }),
|
||||
).toBe(5);
|
||||
expect(
|
||||
smallerBatchLimit({ error: refusal({ message: "the batch size is at most 4" }), size: 10 }),
|
||||
).toBe(4);
|
||||
});
|
||||
|
||||
test("one text alone is never shrunk", () => {
|
||||
expect(
|
||||
smallerBatchLimit({
|
||||
error: refusal({ message: "batch size is invalid, it should not be larger than 0" }),
|
||||
size: 1,
|
||||
}),
|
||||
).toBeNull();
|
||||
});
|
||||
|
||||
test("a stated limit that doesn't shrink the batch still halves it", () => {
|
||||
expect(
|
||||
smallerBatchLimit({
|
||||
error: refusal({ message: "batch size is invalid, it should not be larger than 32" }),
|
||||
size: 32,
|
||||
}),
|
||||
).toBe(16);
|
||||
});
|
||||
|
||||
test("any other refusal is somebody else's to classify", () => {
|
||||
expect(
|
||||
smallerBatchLimit({ error: refusal({ message: "model not found" }), size: 32 }),
|
||||
).toBeNull();
|
||||
expect(
|
||||
smallerBatchLimit({
|
||||
error: refusal({ message: "batch size is invalid", status: 500 }),
|
||||
size: 32,
|
||||
}),
|
||||
).toBeNull();
|
||||
expect(smallerBatchLimit({ error: new Error("batch size is invalid"), size: 32 })).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,31 @@
|
||||
import HarnessError from "../../harness-error";
|
||||
|
||||
type Params = {
|
||||
error: unknown;
|
||||
/**
|
||||
* How many texts the refused request carried.
|
||||
*/
|
||||
size: number;
|
||||
};
|
||||
|
||||
/**
|
||||
* The batch size to try when a provider refused a batch for being too large.
|
||||
*
|
||||
* Alibaba's Model Studio compatible API answers "Value error, batch size is
|
||||
* invalid, it should not be larger than 20.: input.contents" and refuses the
|
||||
* whole request, so nothing is embedded until the batch fits. Returns the
|
||||
* limit the provider stated, else half the refused batch; null when the
|
||||
* refusal is something else, or when one text alone was still refused (that
|
||||
* is a real failure, not a size one).
|
||||
*/
|
||||
export default function smallerBatchLimit({ error, size }: Params): number | null {
|
||||
if (!(error instanceof HarnessError) || error.status !== 400) return null;
|
||||
|
||||
if (!/batch size/i.test(error.message) && !/too many inputs/i.test(error.message)) return null;
|
||||
|
||||
const stated = /(?:larger than|at most|maximum of|limit of)\s*(\d+)/i.exec(error.message);
|
||||
const stated_limit = stated ? Number(stated[1]) : 0;
|
||||
const next = stated_limit > 0 && stated_limit < size ? stated_limit : Math.floor(size / 2);
|
||||
|
||||
return next >= 1 && next < size ? next : null;
|
||||
}
|
||||
@@ -2,7 +2,7 @@ import { afterAll, describe, expect, mock, test } from "bun:test";
|
||||
import { z } from "zod";
|
||||
import { AppData } from "@/src/data/app-data";
|
||||
import { UnlimitedLimit } from "@/src/utils/run-limit";
|
||||
import { alreadyRanToolNote, answerNotSentNote, closingFailedNote, closingMixedNote, closingNoTextNote, contextTrimmedNote, DroppedToolImageNote, oversizedRequestNote, repeatedAnswerNote, replyClosingRequiredNote, replyDraftNote, replyNoTextNote, SupersededSnapshotNote, ToolImagesNote } from "@/src/data/harness-prompts";
|
||||
import { alreadyRanToolNote, answerNotSentNote, closingFailedNote, closingMixedNote, closingNoTextNote, contextTrimmedNote, DroppedToolImageNote, oversizedRequestNote, repeatedAnswerNote, replyClosingMixedNote, replyClosingRequiredNote, replyDraftNote, replyNoTextNote, SupersededSnapshotNote, ToolImagesNote } from "@/src/data/harness-prompts";
|
||||
import HarnessError from "../harness-error";
|
||||
import type { HarnessCandidate, HarnessTool } from "../types";
|
||||
import type { HarnessTrace } from "../trace/types";
|
||||
@@ -1933,14 +1933,38 @@ describe("runTextLoop required send_reply", () => {
|
||||
expect(seen[1]!.messages.at(-1)).toMatchObject({ role: "user", content: replyNoTextNote });
|
||||
});
|
||||
|
||||
test("a message written in the turn before goes out with send_reply", async () => {
|
||||
test("send_reply with no text does not ship the previous draft on the first pass", async () => {
|
||||
/**
|
||||
* A model that writes the answer, then calls send_reply with
|
||||
* nothing beside it, means the sentence it just wrote. Asked to
|
||||
* write it again it wrote nothing, and the run failed with the
|
||||
* answer sitting in the transcript.
|
||||
* The model spent its stop on the draft. The next turn only stamped
|
||||
* send_reply on it, and that draft went out mid-table with no turn
|
||||
* left for a follow-up. The first bare call is told to write the
|
||||
* message again.
|
||||
*/
|
||||
const { generate, seen } = scripted([
|
||||
{ text: "No, I didn't add it anywhere." },
|
||||
{ tool_calls: [{ id: "s1", name: "send_reply", arguments: `{"status":"done"}` }] },
|
||||
{
|
||||
text: "No, I didn't add it anywhere.",
|
||||
tool_calls: [{ id: "s2", name: "send_reply", arguments: `{"status":"done"}` }],
|
||||
},
|
||||
]);
|
||||
|
||||
const result = await runTextLoop({
|
||||
system: "s",
|
||||
messages: [{ role: "user", content: "Did you add a bot?" }],
|
||||
tools: [sendReply],
|
||||
generate,
|
||||
resolveCandidates,
|
||||
require_closing_answer: true,
|
||||
});
|
||||
|
||||
expect(result.text).toBe("No, I didn't add it anywhere.");
|
||||
expect(result.steps).toBe(3);
|
||||
expect(seen[2]!.messages.at(-1)).toMatchObject({ role: "user", content: replyNoTextNote });
|
||||
});
|
||||
|
||||
test("a finished draft goes out only after the one reminder still gets no text", async () => {
|
||||
const { generate } = scripted([
|
||||
{ text: "No, I didn't add it anywhere." },
|
||||
{ tool_calls: [{ id: "s1", name: "send_reply", arguments: `{"status":"done"}` }] },
|
||||
{ tool_calls: [{ id: "s2", name: "send_reply", arguments: `{"status":"done"}` }] },
|
||||
@@ -1956,12 +1980,11 @@ describe("runTextLoop required send_reply", () => {
|
||||
});
|
||||
|
||||
expect(result.text).toBe("No, I didn't add it anywhere.");
|
||||
expect(result.steps).toBe(2);
|
||||
expect(seen[1]!.messages.some((message) => message.content === replyNoTextNote)).toBe(false);
|
||||
expect(result.steps).toBe(3);
|
||||
});
|
||||
|
||||
test("the message still goes out when a tool turn comes between it and send_reply", async () => {
|
||||
const { generate } = scripted([
|
||||
test("a tool turn between the draft and send_reply still gets the one reminder", async () => {
|
||||
const { generate, seen } = scripted([
|
||||
{ text: "No, I didn't add it anywhere." },
|
||||
{ tool_calls: [{ id: "c1", name: "remember", arguments: `{"note":"checked"}` }] },
|
||||
{ tool_calls: [{ id: "s1", name: "send_reply", arguments: `{"status":"done"}` }] },
|
||||
@@ -1978,23 +2001,129 @@ describe("runTextLoop required send_reply", () => {
|
||||
});
|
||||
|
||||
expect(result.text).toBe("No, I didn't add it anywhere.");
|
||||
expect(result.steps).toBe(3);
|
||||
expect(result.steps).toBe(4);
|
||||
expect(seen[3]!.messages.at(-1)).toMatchObject({ role: "user", content: replyNoTextNote });
|
||||
});
|
||||
|
||||
test("a card is never paired with a message written earlier", async () => {
|
||||
asked.length = 0;
|
||||
test("send_reply and suggest_next_steps in one turn end the run and keep both", async () => {
|
||||
suggested.length = 0;
|
||||
const { generate } = scripted([
|
||||
{ text: "Which date rule?" },
|
||||
{
|
||||
text: "Both repos are scanned. Nothing was pulled in.",
|
||||
tool_calls: [
|
||||
{ id: "q1", name: "ask_user", arguments: `{"question":"Which date rule?"}` },
|
||||
{ id: "g1", name: "suggest_next_steps", arguments: `{"steps":["Pull email_frameworks.md in full"]}` },
|
||||
{ id: "s1", name: "send_reply", arguments: `{"status":"done"}` },
|
||||
],
|
||||
},
|
||||
]);
|
||||
|
||||
const result = await runTextLoop({
|
||||
system: "s",
|
||||
messages: [{ role: "user", content: "Scan the repos." }],
|
||||
tools: [suggestNextSteps, sendReply],
|
||||
generate,
|
||||
resolveCandidates,
|
||||
require_closing_answer: true,
|
||||
});
|
||||
|
||||
expect(result.text).toBe("Both repos are scanned. Nothing was pulled in.");
|
||||
expect(result.steps).toBe(1);
|
||||
expect(suggested).toEqual(["Pull email_frameworks.md in full"]);
|
||||
expect(result.tool_uses.map((use) => use.name)).toEqual(["suggest_next_steps", "send_reply"]);
|
||||
});
|
||||
|
||||
test("send_reply beside a research tool is still mixed and unsent", async () => {
|
||||
const { generate, seen } = scripted([
|
||||
{
|
||||
text: "Scanned.",
|
||||
tool_calls: [
|
||||
{ id: "c1", name: "remember", arguments: `{"note":"scanned"}` },
|
||||
{ id: "s1", name: "send_reply", arguments: `{"status":"done"}` },
|
||||
],
|
||||
},
|
||||
{
|
||||
text: "Scanned both repos.",
|
||||
tool_calls: [{ id: "s2", name: "send_reply", arguments: `{"status":"done"}` }],
|
||||
},
|
||||
]);
|
||||
|
||||
const result = await runTextLoop({
|
||||
system: "s",
|
||||
messages: [{ role: "user", content: "Scan the repos." }],
|
||||
tools: [remember, sendReply],
|
||||
generate,
|
||||
resolveCandidates,
|
||||
require_closing_answer: true,
|
||||
});
|
||||
|
||||
expect(result.text).toBe("Scanned both repos.");
|
||||
expect(seen[1]!.messages.at(-1)).toMatchObject({ role: "user", content: replyClosingMixedNote });
|
||||
});
|
||||
|
||||
test("a table that stops mid-row is sent back once, then goes out finished", async () => {
|
||||
const cut = ["| Skill | Focus |", "| **revops** | Lead routing"].join("\n");
|
||||
const whole = ["| Skill | Focus |", "| **revops** | Lead routing |"].join("\n");
|
||||
const { generate, seen } = scripted([
|
||||
{
|
||||
text: cut,
|
||||
tool_calls: [{ id: "s1", name: "send_reply", arguments: `{"status":"done"}` }],
|
||||
},
|
||||
{
|
||||
text: whole,
|
||||
tool_calls: [{ id: "s2", name: "send_reply", arguments: `{"status":"done"}` }],
|
||||
},
|
||||
]);
|
||||
|
||||
const result = await runTextLoop({
|
||||
system: "s",
|
||||
messages: [{ role: "user", content: "Scan the repos." }],
|
||||
tools: [sendReply],
|
||||
generate,
|
||||
resolveCandidates,
|
||||
require_closing_answer: true,
|
||||
});
|
||||
|
||||
expect(result.text).toBe(whole);
|
||||
expect(result.steps).toBe(2);
|
||||
expect(String(seen[1]!.messages.at(-1)!.content)).toContain("table row");
|
||||
});
|
||||
|
||||
test("a cut-off draft is never carried, even after the reminder", async () => {
|
||||
const cut = ["| Skill | Focus |", "| **revops** | Lead routing"].join("\n");
|
||||
const { generate } = scripted([
|
||||
{ text: cut },
|
||||
{ tool_calls: [{ id: "s1", name: "send_reply", arguments: `{"status":"done"}` }] },
|
||||
{ tool_calls: [{ id: "s2", name: "send_reply", arguments: `{"status":"done"}` }] },
|
||||
]);
|
||||
|
||||
const result = await runTextLoop({
|
||||
system: "s",
|
||||
messages: [{ role: "user", content: "Scan the repos." }],
|
||||
tools: [sendReply],
|
||||
generate,
|
||||
resolveCandidates,
|
||||
require_closing_answer: true,
|
||||
});
|
||||
|
||||
expect(result.text).toBe("");
|
||||
expect(result.review_note).toBe(replyNoTextNote);
|
||||
});
|
||||
|
||||
test("a card is never paired with a message written earlier", async () => {
|
||||
/**
|
||||
* The first bare send_reply is told to write the message again.
|
||||
* Writing nothing the second time must not fill the card's turn
|
||||
* with the earlier sentence: the card asked something else, and
|
||||
* that sentence is not its answer.
|
||||
*/
|
||||
asked.length = 0;
|
||||
const { generate, seen } = scripted([
|
||||
{ text: "I checked the date rules." },
|
||||
{ tool_calls: [{ id: "s0", name: "send_reply", arguments: `{"status":"done"}` }] },
|
||||
{
|
||||
tool_calls: [
|
||||
{ id: "q2", name: "ask_user", arguments: `{"question":"Which date rule?"}` },
|
||||
{ id: "s2", name: "send_reply", arguments: `{"status":"done"}` },
|
||||
{ id: "q1", name: "ask_user", arguments: `{"question":"Which date rule?"}` },
|
||||
{ id: "s1", name: "send_reply", arguments: `{"status":"done"}` },
|
||||
],
|
||||
},
|
||||
]);
|
||||
@@ -2010,6 +2139,8 @@ describe("runTextLoop required send_reply", () => {
|
||||
|
||||
expect(result.text).toBe("");
|
||||
expect(result.review_note).toBe(replyNoTextNote);
|
||||
expect(asked).toEqual(["Which date rule?"]);
|
||||
expect(seen[2]!.messages.some((message) => message.content === replyNoTextNote)).toBe(true);
|
||||
});
|
||||
|
||||
test("the wrap up still offers send_reply", async () => {
|
||||
|
||||
@@ -21,6 +21,7 @@ import {
|
||||
import { isUnlimitedLimit, type RunLimit, UnlimitedLimit } from "@/src/utils/run-limit";
|
||||
import sanitizeAnswerText from "@/src/utils/sanitize-answer-text";
|
||||
import repairAnswerText from "@/src/utils/repair-answer-text";
|
||||
import unfinishedAnswerText from "@/src/utils/unfinished-answer-text";
|
||||
import { logError } from "@/src/functions/backend/logger";
|
||||
import type { ReplyStatus } from "@/src/dict/reply-status-dict";
|
||||
import { ReplyStatuses } from "@/src/dict/reply-status-dict";
|
||||
@@ -505,6 +506,12 @@ export default async function runTextLoop({
|
||||
* the sentence that goes with it (`closingNoTextNote`).
|
||||
*/
|
||||
let told_closing_text = false;
|
||||
/**
|
||||
* A message that stopped inside a table, a fence or a bare marker has
|
||||
* been sent back once (`unfinishedAnswerText`). Past that the run
|
||||
* fails rather than shipping the cut-off text.
|
||||
*/
|
||||
let told_unfinished = false;
|
||||
/**
|
||||
* How many turns the run has spent retrying a closing card: a closing
|
||||
* call that failed, or a card put up beside other work. Bounded
|
||||
@@ -519,12 +526,11 @@ export default async function runTextLoop({
|
||||
*/
|
||||
let reply_drafts = 0;
|
||||
/**
|
||||
* The last message a turn wrote with nothing beside it, held for the
|
||||
* run: a model that writes the answer and then calls `send_reply` with
|
||||
* nothing beside it means the sentence it wrote, and dropping it made
|
||||
* the app ask again until the run failed with the answer sitting in the
|
||||
* transcript. Kept across turns, since the call came after another turn
|
||||
* often enough; a card's message is never taken from here.
|
||||
* The last message a turn wrote with nothing beside it. Held so the
|
||||
* note that asks for it again can point at it. It is not the reply:
|
||||
* `send_reply` with no text beside it used to ship this unchanged, and
|
||||
* a scan that stopped mid-table went out as the answer, with no turn
|
||||
* left for the follow-up (session 130, message 874).
|
||||
*/
|
||||
let draft_text = "";
|
||||
/**
|
||||
@@ -1124,6 +1130,13 @@ export default async function runTextLoop({
|
||||
*/
|
||||
const called_card = tool_calls.some((call) => isClosingTool({ name: call.name }));
|
||||
const called_send_reply = tool_calls.some((call) => call.name === SendReplyToolName);
|
||||
/**
|
||||
* A closing turn is `send_reply` plus the cards that belong under
|
||||
* that answer, and nothing else. `ask_user` and `suggest_next_steps`
|
||||
* are closing tools, so they share the turn. A research tool beside
|
||||
* `send_reply` is still mixed: its result arrives after the message,
|
||||
* and the message would describe work the turn had not finished.
|
||||
*/
|
||||
const closing = tool_calls.every((call) => isClosingTool({ name: call.name }));
|
||||
/**
|
||||
* A required closing answer needs `send_reply` itself, not just any
|
||||
@@ -1143,19 +1156,25 @@ export default async function runTextLoop({
|
||||
const closing_failed = closing_uses.some((use) => !use.ok);
|
||||
const closing_worked = closing && !closing_failed && closing_required;
|
||||
/**
|
||||
* The message this turn carries: its own, or the last one a turn
|
||||
* wrote with nothing beside it (`draft_text`). A model that writes
|
||||
* the answer and then calls `send_reply` with no text means that
|
||||
* sentence; asking for it again ended runs whose answer was already
|
||||
* in the transcript. A card is never paired with an older sentence:
|
||||
* "which date rule?" beside a message about something else is worse
|
||||
* than the note that asks for one.
|
||||
* The message this turn wrote beside the call. An earlier draft is
|
||||
* not filled in: the model spent its stop on that draft, and the
|
||||
* next turn only stamped `send_reply` on it, so a cut-off scan went
|
||||
* out with no follow-up. The draft is offered once, after the model
|
||||
* has been told to write it again and still sent nothing, and only
|
||||
* when that draft is a finished message.
|
||||
*/
|
||||
const written_text = (answer.text || "").trim();
|
||||
/**
|
||||
* A card is never paired with an older sentence: the card asked
|
||||
* something, and the draft was about something else. Filling it in
|
||||
* would put "I checked the date rules." under "Which date rule?".
|
||||
*/
|
||||
const asked_something = tool_calls.some(
|
||||
(call) => call.name !== SendReplyToolName && isClosingTool({ name: call.name }),
|
||||
);
|
||||
const message_text = written_text ? answer.text || "" : asked_something ? "" : draft_text;
|
||||
const carry_draft =
|
||||
told_closing_text && !asked_something && !unfinishedAnswerText({ text: draft_text });
|
||||
const message_text = written_text || (carry_draft ? draft_text : "");
|
||||
|
||||
if (called_card && (closing_failed || !closing || !closing_required)) {
|
||||
/**
|
||||
@@ -1242,19 +1261,41 @@ export default async function runTextLoop({
|
||||
/**
|
||||
* Checked before it goes out, as any reply is: a note comes
|
||||
* back and the answer is written again (the card stays on the
|
||||
* reply, its ref is already recorded). A message held from the
|
||||
* turn before went out with this call, which is what the model
|
||||
* meant by writing it there.
|
||||
* reply, its ref is already recorded). A draft carried after
|
||||
* the one reminder is said so, so the debug view shows why an
|
||||
* earlier turn's text went out.
|
||||
*/
|
||||
if (!written_text && message_text) {
|
||||
await traced({
|
||||
kind: "event",
|
||||
index,
|
||||
name: "draft_carried",
|
||||
text: "The message was written in an earlier turn, so it went out with this send_reply.",
|
||||
text: "The message was written in an earlier turn. send_reply had no text beside it after one reminder, so that finished draft went out.",
|
||||
});
|
||||
}
|
||||
|
||||
const unfinished = unfinishedAnswerText({ text: message_text });
|
||||
|
||||
if (unfinished) {
|
||||
if (!told_unfinished && !(wrap_up && !wrap_up_saving)) {
|
||||
told_unfinished = true;
|
||||
draft_text = "";
|
||||
pushUserTurn({ transcript, content: unfinished });
|
||||
await traced({ kind: "event", index, name: "unfinished", text: unfinished });
|
||||
continue;
|
||||
}
|
||||
|
||||
return {
|
||||
text: "",
|
||||
review_note: unfinished,
|
||||
messages: transcript,
|
||||
steps: index + 1,
|
||||
candidate: answer.candidate,
|
||||
usage,
|
||||
tool_uses,
|
||||
};
|
||||
}
|
||||
|
||||
const final_turn = wrap_up && !wrap_up_saving;
|
||||
const check = await checkAnswer({ text: message_text, index, status: reply_status, final: final_turn });
|
||||
|
||||
|
||||
@@ -39,6 +39,7 @@ describe("describeKnowledgebase", () => {
|
||||
expect(text).toContain("Handbook");
|
||||
expect(text).toContain("[bot:7]");
|
||||
expect(text).toContain("1 not read yet");
|
||||
expect(text).not.toContain("retry_failed_documents");
|
||||
expect(text).toContain("re-indexing fixes it");
|
||||
});
|
||||
|
||||
@@ -48,6 +49,12 @@ describe("describeKnowledgebase", () => {
|
||||
);
|
||||
});
|
||||
|
||||
test("names the retry for ones that failed", () => {
|
||||
const text = describeKnowledgebase({ knowledgebase: { ...knowledgebase, error_count: 2 } });
|
||||
|
||||
expect(text).toContain("2 failed (retry_failed_documents reads those again)");
|
||||
});
|
||||
|
||||
test("lists documents and says one failed", () => {
|
||||
const text = describeKnowledgebase({
|
||||
knowledgebase,
|
||||
|
||||
@@ -27,7 +27,9 @@ export default function describeKnowledgebase({ knowledgebase, documents }: Para
|
||||
lines.push(
|
||||
`Documents: ${knowledgebase.document_count}` +
|
||||
(knowledgebase.pending_count ? `, ${knowledgebase.pending_count} not read yet` : "") +
|
||||
(knowledgebase.error_count ? `, ${knowledgebase.error_count} failed` : "") +
|
||||
(knowledgebase.error_count
|
||||
? `, ${knowledgebase.error_count} failed (retry_failed_documents reads those again)`
|
||||
: "") +
|
||||
(knowledgebase.warning_count ? `, ${knowledgebase.warning_count} with a warning` : "") +
|
||||
(knowledgebase.stale_count
|
||||
? `, ${knowledgebase.stale_count} searchable by words only or read by another embedding model (re-indexing fixes it)`
|
||||
|
||||
@@ -13,6 +13,7 @@ describe("grabCoordinatorKnowledgebaseTools", () => {
|
||||
"add_knowledgebase_document",
|
||||
"delete_knowledgebase_document",
|
||||
"delete_knowledgebase",
|
||||
"retry_failed_documents",
|
||||
"reindex_knowledgebase",
|
||||
]);
|
||||
});
|
||||
|
||||
@@ -4,6 +4,7 @@ import deleteKnowledgebaseDocumentTool from "./delete-knowledgebase-document-too
|
||||
import deleteKnowledgebaseTool from "./delete-knowledgebase-tool";
|
||||
import listKnowledgebasesTool from "./list-knowledgebases-tool";
|
||||
import reindexKnowledgebaseTool from "./reindex-knowledgebase-tool";
|
||||
import retryFailedDocumentsTool from "./retry-failed-documents-tool";
|
||||
import saveKnowledgebaseTool from "./save-knowledgebase-tool";
|
||||
|
||||
type Params = {
|
||||
@@ -23,9 +24,9 @@ type Params = {
|
||||
};
|
||||
|
||||
/**
|
||||
* The coordinator's knowledgebase tools: list, fill, re-index, delete and
|
||||
* share out. Every one but the listing is only in an attended run, and each
|
||||
* checks the super admin itself.
|
||||
* The coordinator's knowledgebase tools: list, fill, retry the ones that
|
||||
* failed, re-index, delete and share out. Every one but the listing is only
|
||||
* in an attended run, and each checks the super admin itself.
|
||||
*/
|
||||
export default function grabCoordinatorKnowledgebaseTools({
|
||||
user_id,
|
||||
@@ -44,6 +45,7 @@ export default function grabCoordinatorKnowledgebaseTools({
|
||||
addKnowledgebaseDocumentTool({ user_id, bot_id, workspace_id, computer_id, attended }) as HarnessTool<unknown>,
|
||||
deleteKnowledgebaseDocumentTool({ user_id, attended }) as HarnessTool<unknown>,
|
||||
deleteKnowledgebaseTool({ user_id, attended }) as HarnessTool<unknown>,
|
||||
retryFailedDocumentsTool({ user_id, attended }) as HarnessTool<unknown>,
|
||||
reindexKnowledgebaseTool({ user_id, attended }) as HarnessTool<unknown>,
|
||||
];
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
import { z } from "zod";
|
||||
import grabKnowledgebase from "@/src/functions/backend/db/knowledgebases/grab-knowledgebase";
|
||||
import retryFailedDocuments from "@/src/functions/backend/db/knowledgebases/retry-failed-documents";
|
||||
import logEvent from "@/src/functions/backend/logger";
|
||||
import type { HarnessTool } from "../../../types";
|
||||
import assertSuperAdminRun from "../extensions/assert-super-admin-run";
|
||||
|
||||
type Params = {
|
||||
user_id: number | string;
|
||||
attended: boolean;
|
||||
};
|
||||
|
||||
type Args = {
|
||||
knowledgebase_id: number;
|
||||
document_id?: number;
|
||||
};
|
||||
|
||||
/**
|
||||
* Reads again the documents whose last read failed. The ones that already
|
||||
* succeeded are left as they are; reading every document again is
|
||||
* `reindex_knowledgebase`.
|
||||
*/
|
||||
export default function retryFailedDocumentsTool({ user_id, attended }: Params): HarnessTool<Args> {
|
||||
return {
|
||||
name: "retry_failed_documents",
|
||||
description: `Read again the documents of a knowledgebase whose last read failed (list_knowledgebases marks them failed). Documents that already succeeded are left as they are. With document_id, only that one, and only when it failed. Reading every document again, including the ones that succeeded, is reindex_knowledgebase.`,
|
||||
schema: z.object({
|
||||
knowledgebase_id: z.number().int().positive(),
|
||||
document_id: z.number().int().positive().optional(),
|
||||
}),
|
||||
run: async ({ args }) => {
|
||||
await assertSuperAdminRun({ user_id });
|
||||
|
||||
if (!attended) throw new Error(`Knowledgebases are only changed in a reply or a task the user follows.`);
|
||||
|
||||
const knowledgebase = await grabKnowledgebase({ knowledgebase_id: args.knowledgebase_id });
|
||||
const count = await retryFailedDocuments({
|
||||
knowledgebase_id: knowledgebase.id,
|
||||
document_id: args.document_id,
|
||||
});
|
||||
|
||||
await logEvent({
|
||||
title: "Knowledgebase failed documents retried",
|
||||
category: "system",
|
||||
user_id: Number(user_id),
|
||||
plain_text: `Queued ${count} failed documents of knowledgebase #${knowledgebase.id} (${knowledgebase.name}) to be read again.`,
|
||||
metadata: { knowledgebase_id: knowledgebase.id, document_id: args.document_id, documents: count },
|
||||
});
|
||||
|
||||
if (!count) {
|
||||
return args.document_id
|
||||
? `#${args.document_id} didn't fail, so it wasn't read again.`
|
||||
: `#${knowledgebase.id} ${knowledgebase.name} has no failed documents.`;
|
||||
}
|
||||
|
||||
return `Queued ${count} failed ${count == 1 ? "document" : "documents"} of #${knowledgebase.id} ${knowledgebase.name} to be read again. The ones that already succeeded were left as they are.`;
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -47,7 +47,7 @@ export default function askUserTool({
|
||||
|
||||
return {
|
||||
name: "ask_user",
|
||||
description: `Ask the user multiple-choice questions, shown as a card in the chat they answer in a click. Use it whenever what happens next is theirs to decide: when the request is ambiguous or leaves out something that changes the result (which target, which items, how far to go), before something that is hard to undo, costly or visible to others, and to offer the next step once you've answered or reported (the concrete next steps as options, your suggestion first). When you're unsure whether to ask, ask. Don't ask what they already told you, what you can find out yourself, or details that don't change the result. Put every question in one call (at most one per run). Their answers arrive as their next message${
|
||||
description: `Ask the user multiple-choice questions, shown as a card in the chat they answer in a click. Use it whenever what happens next is theirs to decide: when the request is ambiguous or leaves out something that changes the result (which target, which items, how far to go), before something that is hard to undo, costly or visible to others, and to offer the next step once you've answered or reported (the concrete next steps as options, your suggestion first). When you're unsure whether to ask, ask. Call it in the same turn as send_reply, with the message beside that call: a later turn cannot add the card, because that turn would replace the answer. Don't ask what they already told you, what you can find out yourself, or details that don't change the result. Put every question in one call (at most one per run). Their answers arrive as their next message${
|
||||
in_task
|
||||
? `. In a task, ask, then stop working on what you asked about and finish your report; the card goes out with it.`
|
||||
: `: after asking, end your reply and wait; don't act on what you asked about until they answer.`
|
||||
|
||||
@@ -60,7 +60,7 @@ export default function sendReplyTool({
|
||||
|
||||
return {
|
||||
name: "send_reply",
|
||||
description: `End every reply with this call. The message you wrote in this turn is what the user gets; this call only says what happens after it. status done: nothing runs once the message goes out, so the text must not say work is under way. status working: a run is carrying the work on and its result will be posted here; pass work to queue it now, or it must already be open. status blocked: the work cannot go on, and the text says why. Never write a message that says work is under way and end with done. A message sent without this call is a draft and never reaches the user. ${
|
||||
description: `End every reply with this call, in the same turn as the message. The text you write beside it is what the user gets; a call with no text sends nothing, and a message from an earlier turn is not filled in. This call only says what happens after it. status done: nothing runs once the message goes out, so the text must not say work is under way. status working: a run is carrying the work on and its result will be posted here; pass work to queue it now, or it must already be open. status blocked: the work cannot go on, and the text says why. Never write a message that says work is under way and end with done. In this same turn, and no other, you may also call suggest_next_steps or ask_user when one of them belongs with the answer. No other tool shares this turn. A message sent without this call is a draft and never reaches the user. Finish every table, list and code fence in the text. ${
|
||||
computers.length
|
||||
? `Computers you can use: ${listed}. Defaults to ${computers[0]!.id}, the one you're on.`
|
||||
: `You have no computer, so work that needs one can't run.`
|
||||
|
||||
@@ -28,16 +28,16 @@ type Args = {
|
||||
/**
|
||||
* Offers the user concrete next steps as buttons under the bot's answer.
|
||||
* Clicking one puts it in their input; nothing waits on it, unlike
|
||||
* `ask_user`. Once per run, so every suggestion lands in one row. It ends
|
||||
* the reply (`ClosingToolNames`): the buttons belong under the answer, and
|
||||
* a run that kept going would replace that answer with a later line.
|
||||
* `ask_user`. Once per run, so every suggestion lands in one row. It shares
|
||||
* the closing turn with `send_reply` (`ClosingToolNames`): the buttons
|
||||
* belong under that answer, and a later turn would replace it.
|
||||
*/
|
||||
export default function suggestNextStepsTool({ user_id, bot_id, session_id, workspace_id, onSuggest }: Params): HarnessTool<Args> {
|
||||
let suggested = false;
|
||||
|
||||
return {
|
||||
name: "suggest_next_steps",
|
||||
description: `Offer the user next steps they can take from here, shown as buttons under your answer: clicking one puts it in their input for them to send. Use it once the work is done or a reply is complete, to make follow-ups one click away (your best suggestion first). This never waits for a response: don't ask the user to pick one, don't put the answers on hold, and put it up in the same turn as the answer it belongs under. When their answer decides what you do next, use ask_user instead. Don't suggest what they already asked for, and don't repeat the steps in your text.`,
|
||||
description: `Offer the user next steps they can take from here, shown as buttons under your answer: clicking one puts it in their input for them to send. Call it in the same turn as send_reply, once the work is done, so the buttons belong to the message that turn sends (your best suggestion first). A later turn cannot add them: that turn would replace the answer. This never waits for a response: don't ask the user to pick one, don't put the answers on hold. When their answer decides what you do next, use ask_user in that same turn instead. Don't suggest what they already asked for, and don't repeat the steps in your text.`,
|
||||
schema: z.object({
|
||||
title: z
|
||||
.string()
|
||||
|
||||
@@ -161,9 +161,9 @@ Tell the bot your time zone once ("I'm in Lagos", "I'm on New York time") and it
|
||||
|
||||
If it's given and still misses:
|
||||
|
||||
- Open the knowledgebase's documents. A document still **being read** isn't searchable yet; one that **couldn't be read** names why (a scan with no text, a file too big). Write the text in instead, or upload a version with text in it.
|
||||
- Open the knowledgebase's documents. A document still **being read** isn't searchable yet; one that **couldn't be read** names why (a scan with no text, a file too big). Write the text in instead, or upload a version with text in it. The retry icon on that document, or Retry failed in the knowledgebase's menu, reads the failed ones again and leaves the ones that succeeded.
|
||||
- Bots search by meaning only with an embedding model, picked once for the whole install in **Settings, Models** under Embeddings. Without one they match words, which misses questions worded differently from the document. Picking or changing the model reads every document again on its own; a document shows **needs re-indexing** until it's done.
|
||||
- If a document still says it needs re-indexing, use the refresh icon on its knowledgebase's row to read them all again.`,
|
||||
- If a document still says it needs re-indexing, open the knowledgebase's menu and choose Re-index to read them all again.`,
|
||||
},
|
||||
{
|
||||
id: "connect-browser",
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
import { useContext } from "react";
|
||||
import type { LucideIcon } from "lucide-react";
|
||||
import HeaderMenuItem from "@/src/pages/admin/bots/[bot_id]/(partials)/header-menu-item";
|
||||
import { SettingsRowMenuClose } from "./settings-row-menu";
|
||||
|
||||
type Props = {
|
||||
icon: LucideIcon;
|
||||
title: string;
|
||||
description?: string;
|
||||
disabled?: boolean;
|
||||
loading?: boolean;
|
||||
onClick: () => void;
|
||||
};
|
||||
|
||||
/**
|
||||
* One action in a settings row's three-dot menu. It closes the menu, then
|
||||
* runs, so a confirm dialog or a modal is the only thing left open.
|
||||
*/
|
||||
export default function SettingsRowMenuItem({ icon, title, description, disabled, loading, onClick }: Props) {
|
||||
const close = useContext(SettingsRowMenuClose);
|
||||
|
||||
return (
|
||||
<HeaderMenuItem
|
||||
icon={icon}
|
||||
title={title}
|
||||
description={description}
|
||||
disabled={disabled}
|
||||
loading={loading}
|
||||
onClick={() => {
|
||||
close();
|
||||
onClick();
|
||||
}}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
import type { ReactNode } from "react";
|
||||
import Paper from "@moduletrace/twui/elements/Paper";
|
||||
import Stack from "@moduletrace/twui/layout/Stack";
|
||||
|
||||
type Props = {
|
||||
children: ReactNode;
|
||||
};
|
||||
|
||||
/**
|
||||
* The panel a settings row's three-dot menu opens: the same surface as
|
||||
* the conversation header's menu.
|
||||
*/
|
||||
export default function SettingsRowMenuPanel({ children }: Props) {
|
||||
return (
|
||||
<Paper
|
||||
role="menu"
|
||||
className="min-w-[220px] p-0! py-1 gap-0! items-stretch rounded-default bg-surface dark:bg-surface border-hairline dark:border-hairline shadow-popover! dark:shadow-popover!"
|
||||
>
|
||||
<Stack className="w-full gap-0! items-stretch">{children}</Stack>
|
||||
</Paper>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
import { createContext, useState, type ReactNode } from "react";
|
||||
import Dropdown from "@moduletrace/twui/elements/Dropdown";
|
||||
import Button from "@moduletrace/twui/layout/Button";
|
||||
import { EllipsisVertical } from "lucide-react";
|
||||
|
||||
/**
|
||||
* Closes the open menu. An item that then asks to confirm, or opens a
|
||||
* modal, calls it first so the menu never sits over that.
|
||||
*/
|
||||
export const SettingsRowMenuClose = createContext<() => void>(() => {});
|
||||
|
||||
type Props = {
|
||||
/**
|
||||
* What the button is called, for the tooltip and screen readers.
|
||||
*/
|
||||
title: string;
|
||||
disabled?: boolean;
|
||||
children: ReactNode;
|
||||
};
|
||||
|
||||
/**
|
||||
* The three-dot menu on a settings row. One icon stands in for the row's
|
||||
* actions, which open as a menu. An item closes it through
|
||||
* `SettingsRowMenuClose` before it confirms or opens a modal.
|
||||
*/
|
||||
export default function SettingsRowMenu({ title, disabled, children }: Props) {
|
||||
const [open, setOpen] = useState(false);
|
||||
|
||||
return (
|
||||
<SettingsRowMenuClose.Provider value={() => setOpen(false)}>
|
||||
<Dropdown
|
||||
position="bottom-right"
|
||||
externalOpen={open}
|
||||
externalSetOpen={setOpen}
|
||||
target={
|
||||
<Button
|
||||
title={title}
|
||||
aria-label={title}
|
||||
aria-haspopup="menu"
|
||||
type="button"
|
||||
variant="ghost"
|
||||
color="text"
|
||||
disabled={disabled}
|
||||
className="shrink-0 p-2! text-ink-secondary dark:text-ink-secondary hover:text-ink hover:dark:text-ink hover:bg-sunken hover:dark:bg-sunken rounded-default transition-colors duration-[var(--m-fast)] focus-visible:ring-2 focus-visible:ring-ink"
|
||||
>
|
||||
<EllipsisVertical size={16} aria-hidden />
|
||||
</Button>
|
||||
}
|
||||
>
|
||||
{children}
|
||||
</Dropdown>
|
||||
</SettingsRowMenuClose.Provider>
|
||||
);
|
||||
}
|
||||
+27
-3
@@ -24,6 +24,7 @@ function render({
|
||||
}) {
|
||||
return renderToString(
|
||||
<HostDirectoryLinkRow
|
||||
kind="computer"
|
||||
name="Main computer"
|
||||
href="/admin/settings/computers/1"
|
||||
access={access}
|
||||
@@ -51,10 +52,32 @@ describe("HostDirectoryLinkRow", () => {
|
||||
|
||||
expect(html).toContain("Main computer");
|
||||
expect(html).toContain("/admin/settings/computers/1");
|
||||
expect(html).toContain("Computer");
|
||||
expect(html).toContain("Read and write");
|
||||
expect(html).toContain("checked");
|
||||
});
|
||||
|
||||
test("a workspace wears its own picture and says it is a workspace", () => {
|
||||
const html = renderToString(
|
||||
<HostDirectoryLinkRow
|
||||
kind="workspace"
|
||||
name="Moduletrace"
|
||||
href="/admin/settings/workspaces/4"
|
||||
image_media_id={12}
|
||||
access="read-write"
|
||||
state="unknown"
|
||||
gate_deletes
|
||||
onAccess={() => {}}
|
||||
onDeletes={() => {}}
|
||||
onRemove={() => {}}
|
||||
/>,
|
||||
);
|
||||
|
||||
expect(html).toContain("Workspace");
|
||||
expect(html).toContain("/media/");
|
||||
expect(html).toContain("12");
|
||||
});
|
||||
|
||||
test("a folder the bots can't write in shows the command to run", () => {
|
||||
const html = render({
|
||||
state: "read-only",
|
||||
@@ -70,7 +93,7 @@ describe("HostDirectoryLinkRow", () => {
|
||||
|
||||
expect(html).toContain("Read only");
|
||||
expect(html).not.toContain("The bots can't write there yet");
|
||||
expect(html).toContain("Read and write");
|
||||
expect(html).not.toContain("Give access");
|
||||
});
|
||||
|
||||
test("a check that couldn't run says why", () => {
|
||||
@@ -104,10 +127,11 @@ describe("HostDirectoryLinkRow", () => {
|
||||
expect(html).not.toContain("setfacl");
|
||||
});
|
||||
|
||||
test("a link whose bots can't write offers to give them access again", () => {
|
||||
test("a link whose bots can't write keeps its check and its menu", () => {
|
||||
const html = render({ state: "partial", onGrant: () => {} });
|
||||
|
||||
expect(html).toContain("Give access");
|
||||
expect(html).toContain("Some bots can't write");
|
||||
expect(html).toContain("Main computer menu");
|
||||
});
|
||||
|
||||
test("a read-only link never offers to give access", () => {
|
||||
|
||||
@@ -1,23 +1,37 @@
|
||||
import { CircleAlert } from "lucide-react";
|
||||
import Link from "@moduletrace/twui/layout/Link";
|
||||
import Row from "@moduletrace/twui/layout/Row";
|
||||
import type { ReactNode } from "react";
|
||||
import { CircleAlert, KeyRound, Lock, RefreshCw, ShieldOff, Unlink } from "lucide-react";
|
||||
import Span from "@moduletrace/twui/layout/Span";
|
||||
import Stack from "@moduletrace/twui/layout/Stack";
|
||||
import ComputerIconTile from "@/src/components/general/computer-icon-tile";
|
||||
import WorkspaceAvatar from "@/src/components/general/workspace-avatar";
|
||||
import {
|
||||
HostDirectoryAccesses,
|
||||
type HostDirectoryAccess,
|
||||
type HostDirectoryCheckState,
|
||||
} from "@/src/dict/host-directory-dict";
|
||||
import SettingsRowAction from "../../(partials)/settings-row-action";
|
||||
import HostDirectoryCheckTag from "../../(partials)/host-directory-check-tag";
|
||||
import HostDirectoryCommandNote from "../../(partials)/host-directory-command-note";
|
||||
import SettingsListRow from "../../(partials)/settings-list-row";
|
||||
import SettingsRowMenu from "../../(partials)/settings-row-menu";
|
||||
import SettingsRowMenuItem from "../../(partials)/settings-row-menu-item";
|
||||
import SettingsRowMenuPanel from "../../(partials)/settings-row-menu-panel";
|
||||
|
||||
type Props = {
|
||||
/**
|
||||
* A computer, or a workspace. The picture is the workspace's own;
|
||||
* a computer always wears the monitor.
|
||||
*/
|
||||
kind: "computer" | "workspace";
|
||||
/**
|
||||
* The computer or workspace it is mounted in.
|
||||
*/
|
||||
name: string;
|
||||
href: string;
|
||||
/**
|
||||
* The workspace's picture. Left out for a computer, and for a
|
||||
* workspace that has none.
|
||||
*/
|
||||
image_media_id?: number | null;
|
||||
access: HostDirectoryAccess;
|
||||
state: HostDirectoryCheckState;
|
||||
checked_at?: number | null;
|
||||
@@ -57,11 +71,13 @@ type Props = {
|
||||
/**
|
||||
* One place a host directory is mounted: a computer, or a workspace (on
|
||||
* every computer it is on), what its bots can do there, and what the last
|
||||
* check found.
|
||||
* check found. The avatar says which kind it is.
|
||||
*/
|
||||
export default function HostDirectoryLinkRow({
|
||||
kind,
|
||||
name,
|
||||
href,
|
||||
image_media_id,
|
||||
access,
|
||||
state,
|
||||
checked_at,
|
||||
@@ -81,94 +97,101 @@ export default function HostDirectoryLinkRow({
|
||||
const access_title =
|
||||
HostDirectoryAccesses.find((item) => item.value == access)?.title ||
|
||||
"Read and write";
|
||||
const place = kind == "workspace" ? "Workspace" : "Computer";
|
||||
|
||||
const notes: ReactNode[] = [];
|
||||
|
||||
if (error) {
|
||||
notes.push(
|
||||
<Span key="error" role="alert" className="flex items-center gap-1.5 text-[12px] leading-4 text-ink">
|
||||
<CircleAlert size={14} aria-hidden className="shrink-0" />
|
||||
Couldn't check it: {error}
|
||||
</Span>,
|
||||
);
|
||||
}
|
||||
|
||||
if (stale && !error) {
|
||||
notes.push(
|
||||
<Span key="stale" role="status" className="flex items-center gap-1.5 text-[12px] leading-4 text-ink-secondary">
|
||||
<CircleAlert size={14} aria-hidden className="shrink-0" />
|
||||
A bot was added since the last check, so its account hasn't been tested. Check again.
|
||||
</Span>,
|
||||
);
|
||||
}
|
||||
|
||||
if (command) notes.push(<HostDirectoryCommandNote key="command" command={command} />);
|
||||
|
||||
return (
|
||||
<Stack className="w-full gap-1! items-stretch border-t border-solid border-hairline py-1.5 first:border-t-0">
|
||||
<Row className="w-full gap-x-2 gap-y-1! flex-wrap items-center">
|
||||
<Link
|
||||
href={href}
|
||||
title={name}
|
||||
className="min-w-0 truncate text-[13px] leading-[18px] text-ink hover:underline"
|
||||
>
|
||||
{name}
|
||||
</Link>
|
||||
<Span className="shrink-0 text-[12px] leading-4 text-ink-secondary">
|
||||
{access_title}
|
||||
</Span>
|
||||
<Stack className="w-full gap-1! items-stretch border-t border-solid border-hairline py-1 first:border-t-0">
|
||||
<SettingsListRow
|
||||
avatar={
|
||||
kind == "workspace" ? (
|
||||
<WorkspaceAvatar image_media_id={image_media_id} />
|
||||
) : (
|
||||
<ComputerIconTile />
|
||||
)
|
||||
}
|
||||
title={name}
|
||||
href={href}
|
||||
badge={place}
|
||||
subtitle={access_title}
|
||||
>
|
||||
<HostDirectoryCheckTag state={state} checked_at={checked_at} />
|
||||
<Row className="ml-auto shrink-0 gap-1! flex-nowrap">
|
||||
{onGrant && access == "read-write" && (stale || state == "partial" || state == "read-only") ? (
|
||||
<SettingsRowAction
|
||||
title="Give every bot that sees this folder access to it"
|
||||
label={granting ? "Giving access" : "Give access"}
|
||||
disabled={busy || checking || granting}
|
||||
onClick={onGrant}
|
||||
/>
|
||||
) : null}
|
||||
{onCheck ? (
|
||||
<SettingsRowAction
|
||||
title="Check that the bots can read and write it now"
|
||||
label={checking ? "Checking" : "Check"}
|
||||
<SettingsRowMenu title={`${name} menu`} disabled={busy || checking}>
|
||||
<SettingsRowMenuPanel>
|
||||
{onGrant && access == "read-write" && (stale || state == "partial" || state == "read-only") ? (
|
||||
<SettingsRowMenuItem
|
||||
icon={KeyRound}
|
||||
title={granting ? "Giving access" : "Give access"}
|
||||
description="Give every bot that sees this folder access to it"
|
||||
loading={granting}
|
||||
disabled={busy || checking || granting}
|
||||
onClick={onGrant}
|
||||
/>
|
||||
) : null}
|
||||
{onCheck ? (
|
||||
<SettingsRowMenuItem
|
||||
icon={RefreshCw}
|
||||
title={checking ? "Checking" : "Check"}
|
||||
description="Check that the bots can read and write it now"
|
||||
loading={checking}
|
||||
disabled={busy || checking}
|
||||
onClick={onCheck}
|
||||
/>
|
||||
) : null}
|
||||
<SettingsRowMenuItem
|
||||
icon={access == "read-write" ? Lock : KeyRound}
|
||||
title={access == "read-write" ? "Read only" : "Read and write"}
|
||||
description={
|
||||
access == "read-write"
|
||||
? "Mount it read only, so the bots can't change it"
|
||||
: "Let the bots write there"
|
||||
}
|
||||
disabled={busy || checking}
|
||||
onClick={onCheck}
|
||||
onClick={onAccess}
|
||||
/>
|
||||
) : null}
|
||||
<SettingsRowAction
|
||||
title={
|
||||
access == "read-write"
|
||||
? "Mount it read only, so the bots can't change it"
|
||||
: "Let the bots write there"
|
||||
}
|
||||
label={
|
||||
access == "read-write"
|
||||
? "Read only"
|
||||
: "Read and write"
|
||||
}
|
||||
disabled={busy || checking}
|
||||
onClick={onAccess}
|
||||
/>
|
||||
<SettingsRowAction
|
||||
title={
|
||||
gate_deletes
|
||||
? "Stop asking: the bots can delete in it without your approval"
|
||||
: "Ask you before a bot deletes anything in it"
|
||||
}
|
||||
label={
|
||||
gate_deletes ? "Ask before deletes" : "Delete freely"
|
||||
}
|
||||
disabled={busy || checking}
|
||||
onClick={onDeletes}
|
||||
/>
|
||||
<SettingsRowAction
|
||||
title={`Unmount it from ${name}`}
|
||||
label="Remove"
|
||||
disabled={busy || checking}
|
||||
onClick={onRemove}
|
||||
/>
|
||||
</Row>
|
||||
</Row>
|
||||
{error ? (
|
||||
<Span
|
||||
role="alert"
|
||||
className="flex items-center gap-1.5 text-[12px] leading-4 text-ink"
|
||||
>
|
||||
<CircleAlert size={14} aria-hidden className="shrink-0" />
|
||||
Couldn't check it: {error}
|
||||
</Span>
|
||||
) : null}
|
||||
{stale && !error ? (
|
||||
<Span
|
||||
role="status"
|
||||
className="flex items-center gap-1.5 text-[12px] leading-4 text-ink-secondary"
|
||||
>
|
||||
<CircleAlert size={14} aria-hidden className="shrink-0" />
|
||||
A bot was added since the last check, so its account
|
||||
hasn't been tested. Check again.
|
||||
</Span>
|
||||
) : null}
|
||||
{command ? (
|
||||
<HostDirectoryCommandNote command={command} />
|
||||
) : null}
|
||||
<SettingsRowMenuItem
|
||||
icon={gate_deletes ? ShieldOff : Lock}
|
||||
title={gate_deletes ? "Ask before deletes" : "Delete freely"}
|
||||
description={
|
||||
gate_deletes
|
||||
? "Stop asking: the bots can delete in it without your approval"
|
||||
: "Ask you before a bot deletes anything in it"
|
||||
}
|
||||
disabled={busy || checking}
|
||||
onClick={onDeletes}
|
||||
/>
|
||||
<SettingsRowMenuItem
|
||||
icon={Unlink}
|
||||
title="Remove"
|
||||
description={`Unmount it from ${name}`}
|
||||
disabled={busy || checking}
|
||||
onClick={onRemove}
|
||||
/>
|
||||
</SettingsRowMenuPanel>
|
||||
</SettingsRowMenu>
|
||||
</SettingsListRow>
|
||||
{notes.length ? <Stack className="w-full gap-1! items-stretch px-3 pb-2">{notes}</Stack> : null}
|
||||
</Stack>
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { useState } from "react";
|
||||
import { FolderTree } from "lucide-react";
|
||||
import { FolderTree, Pencil, Trash2 } from "lucide-react";
|
||||
import Span from "@moduletrace/twui/layout/Span";
|
||||
import Stack from "@moduletrace/twui/layout/Stack";
|
||||
import IconTile from "@/src/components/general/icon-tile";
|
||||
@@ -18,7 +18,9 @@ import hostDirectoryCheckStale from "@/src/utils/host-directory-check-stale";
|
||||
import hostDirectoryPermissionCommand from "@/src/utils/host-directory-permission-command";
|
||||
import InlineAddSelect from "@/src/components/general/inline-add-select";
|
||||
import SettingsListRow from "../../(partials)/settings-list-row";
|
||||
import SettingsRowAction from "../../(partials)/settings-row-action";
|
||||
import SettingsRowMenu from "../../(partials)/settings-row-menu";
|
||||
import SettingsRowMenuItem from "../../(partials)/settings-row-menu-item";
|
||||
import SettingsRowMenuPanel from "../../(partials)/settings-row-menu-panel";
|
||||
import HostDirectoryLinkRow from "./host-directory-link-row";
|
||||
|
||||
type Props = {
|
||||
@@ -41,8 +43,10 @@ type Props = {
|
||||
|
||||
type LinkView = {
|
||||
key: string;
|
||||
kind: "computer" | "workspace";
|
||||
name: string;
|
||||
href: string;
|
||||
image_media_id?: number | null;
|
||||
access: HostDirectoryAccess;
|
||||
state: HostDirectoryCheckState;
|
||||
checked_at?: number | null;
|
||||
@@ -177,6 +181,7 @@ export default function HostDirectoryRow({
|
||||
|
||||
return {
|
||||
key: `computer-${link.id}`,
|
||||
kind: "computer",
|
||||
name: link.computer_name || `Computer ${link.computer_id}`,
|
||||
href: `/admin/settings/computers/${link.computer_id}`,
|
||||
access,
|
||||
@@ -228,7 +233,9 @@ export default function HostDirectoryRow({
|
||||
|
||||
return {
|
||||
key: `workspace-${link.id}`,
|
||||
kind: "workspace",
|
||||
name: link.workspace_name || `Workspace ${link.workspace_id}`,
|
||||
image_media_id: link.image_media_id,
|
||||
href: `/admin/settings/workspaces/${link.workspace_id}`,
|
||||
access,
|
||||
state,
|
||||
@@ -314,26 +321,27 @@ export default function HostDirectoryRow({
|
||||
title={name}
|
||||
subtitle={source}
|
||||
>
|
||||
<SettingsRowAction
|
||||
title={`Edit ${name}`}
|
||||
label="Edit"
|
||||
disabled={Boolean(busy)}
|
||||
onClick={onEdit}
|
||||
/>
|
||||
<SettingsRowAction
|
||||
title={`Remove ${name}`}
|
||||
label="Remove"
|
||||
disabled={Boolean(busy)}
|
||||
onClick={remove}
|
||||
/>
|
||||
<SettingsRowMenu title={`${name} menu`} disabled={Boolean(busy)}>
|
||||
<SettingsRowMenuPanel>
|
||||
<SettingsRowMenuItem icon={Pencil} title="Edit" onClick={onEdit} />
|
||||
<SettingsRowMenuItem
|
||||
icon={Trash2}
|
||||
title="Remove"
|
||||
description="Its computers and workspaces stop seeing the folder. Nothing in the folder itself is deleted."
|
||||
onClick={remove}
|
||||
/>
|
||||
</SettingsRowMenuPanel>
|
||||
</SettingsRowMenu>
|
||||
</SettingsListRow>
|
||||
<Stack className="w-full gap-2! items-stretch px-3 pt-1 pb-3">
|
||||
{links.length ? (
|
||||
links.map((link) => (
|
||||
<HostDirectoryLinkRow
|
||||
key={link.key}
|
||||
kind={link.kind}
|
||||
name={link.name}
|
||||
href={link.href}
|
||||
image_media_id={link.image_media_id}
|
||||
access={link.access}
|
||||
state={link.state}
|
||||
checked_at={link.checked_at}
|
||||
|
||||
@@ -107,5 +107,14 @@ export default function useKnowledgebaseDocuments({ knowledgebase_id }: Params)
|
||||
await post({ path: "knowledgebases/delete-document", body: { document_id: document.id } });
|
||||
};
|
||||
|
||||
return { documents, busy, status, upload, saveText, remove };
|
||||
const retry = async ({ document }: { document: KnowledgebaseDocument }) => {
|
||||
if (busy || !window.confirm(`Read ${document.name} again? Documents that already succeeded stay as they are.`)) return;
|
||||
|
||||
await post({
|
||||
path: "knowledgebases/retry-failed-documents",
|
||||
body: { knowledgebase_id, document_id: document.id },
|
||||
});
|
||||
};
|
||||
|
||||
return { documents, busy, status, upload, saveText, remove, retry };
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { FileText, NotebookPen, Pencil, Trash2 } from "lucide-react";
|
||||
import { FileText, NotebookPen, Pencil, RotateCcw, Trash2 } from "lucide-react";
|
||||
import Row from "@moduletrace/twui/layout/Row";
|
||||
import IconTile from "@/src/components/general/icon-tile";
|
||||
import RowIconButton from "@/src/components/general/row-icon-button";
|
||||
@@ -17,6 +17,10 @@ type Props = {
|
||||
* can't edit.
|
||||
*/
|
||||
onEdit?: () => void;
|
||||
/**
|
||||
* Reads this document again. Given only when its last read failed.
|
||||
*/
|
||||
onRetry?: () => void;
|
||||
onDelete?: () => void;
|
||||
};
|
||||
|
||||
@@ -24,7 +28,7 @@ type Props = {
|
||||
* One document in a knowledgebase: what it is and how much of it bots can
|
||||
* search, or why it couldn't be read.
|
||||
*/
|
||||
export default function KnowledgebaseDocumentRow({ document, embedding_model, busy, onEdit, onDelete }: Props) {
|
||||
export default function KnowledgebaseDocumentRow({ document, embedding_model, busy, onEdit, onRetry, onDelete }: Props) {
|
||||
return (
|
||||
<SettingsListRow
|
||||
avatar={<IconTile Icon={document.source == "text" ? NotebookPen : FileText} />}
|
||||
@@ -44,6 +48,9 @@ export default function KnowledgebaseDocumentRow({ document, embedding_model, bu
|
||||
subtitle={knowledgebaseDocumentSummary({ document, embedding_model })}
|
||||
>
|
||||
<Row className="gap-0! flex-nowrap">
|
||||
{onRetry ? (
|
||||
<RowIconButton icon={RotateCcw} title={`Retry ${document.name}`} disabled={busy} onClick={onRetry} />
|
||||
) : null}
|
||||
{onEdit ? <RowIconButton icon={Pencil} title={`Edit ${document.name}`} disabled={busy} onClick={onEdit} /> : null}
|
||||
{onDelete ? (
|
||||
<RowIconButton icon={Trash2} title={`Delete ${document.name}`} disabled={busy} onClick={onDelete} />
|
||||
|
||||
+6
-1
@@ -34,7 +34,7 @@ type Props = {
|
||||
* done.
|
||||
*/
|
||||
export default function KnowledgebaseDocumentsModal({ knowledgebase, can_edit, embedding_model, onClose }: Props) {
|
||||
const { documents, busy, status, upload, saveText, remove } = useKnowledgebaseDocuments({
|
||||
const { documents, busy, status, upload, saveText, remove, retry } = useKnowledgebaseDocuments({
|
||||
knowledgebase_id: knowledgebase.id,
|
||||
});
|
||||
/**
|
||||
@@ -78,6 +78,11 @@ export default function KnowledgebaseDocumentsModal({ knowledgebase, can_edit, e
|
||||
embedding_model={embedding_model}
|
||||
busy={busy}
|
||||
onEdit={can_edit && document.source == "text" ? () => setWriting(document.id) : undefined}
|
||||
onRetry={
|
||||
can_edit && document.ingest_error && !document.indexing
|
||||
? () => retry({ document })
|
||||
: undefined
|
||||
}
|
||||
onDelete={can_edit ? () => remove({ document }) : undefined}
|
||||
/>
|
||||
))}
|
||||
|
||||
@@ -1,13 +1,14 @@
|
||||
import { useState } from "react";
|
||||
import Row from "@moduletrace/twui/layout/Row";
|
||||
import Stack from "@moduletrace/twui/layout/Stack";
|
||||
import { FileText, Library, Pencil, RefreshCw, Trash2, Users } from "lucide-react";
|
||||
import { FileText, Library, Pencil, RefreshCw, RotateCcw, Trash2, Users } from "lucide-react";
|
||||
import IconTile from "@/src/components/general/icon-tile";
|
||||
import RowIconButton from "@/src/components/general/row-icon-button";
|
||||
import postAdminApi from "@/src/layouts/bots/(functions)/post-admin-api";
|
||||
import type { ExtensionTargets, KnowledgebasesOverviewPayload, PublicKnowledgebase } from "@/src/types";
|
||||
import ExtensionAccessModal from "../../(partials)/extension-access-modal";
|
||||
import SettingsListRow from "../../(partials)/settings-list-row";
|
||||
import SettingsRowMenu from "../../(partials)/settings-row-menu";
|
||||
import SettingsRowMenuItem from "../../(partials)/settings-row-menu-item";
|
||||
import SettingsRowMenuPanel from "../../(partials)/settings-row-menu-panel";
|
||||
import extensionAccessLabel from "../../(utils)/extension-access-label";
|
||||
import updatedAgo from "../../(utils)/updated-ago";
|
||||
import knowledgebaseIndexState from "@/src/utils/knowledgebase-index-state";
|
||||
@@ -29,8 +30,9 @@ type Props = {
|
||||
|
||||
/**
|
||||
* One knowledgebase: how many documents it holds and how much of them is
|
||||
* searchable, and who gets it. Documents, Edit and Access open in a modal;
|
||||
* Re-index reads every document again with the install's embedding model.
|
||||
* searchable, and who gets it. Its actions live in the three-dot menu:
|
||||
* documents, who gets it, and for a super admin editing, retrying the
|
||||
* ones that failed, reading every document again, and deleting it.
|
||||
*/
|
||||
export default function KnowledgebaseRow({ knowledgebase, targets, embedding_model, onChanged, onError }: Props) {
|
||||
const [open, setOpen] = useState<"documents" | "edit" | "access">();
|
||||
@@ -93,54 +95,54 @@ export default function KnowledgebaseRow({ knowledgebase, targets, embedding_mod
|
||||
.filter(Boolean)
|
||||
.join(" · ")}
|
||||
>
|
||||
<Row className="gap-0! flex-nowrap">
|
||||
<RowIconButton
|
||||
icon={FileText}
|
||||
title={`Open the documents in ${knowledgebase.name}`}
|
||||
disabled={busy}
|
||||
onClick={() => setOpen("documents")}
|
||||
/>
|
||||
{targets.can_edit ? (
|
||||
<RowIconButton
|
||||
icon={Pencil}
|
||||
title={`Edit ${knowledgebase.name}`}
|
||||
disabled={busy}
|
||||
onClick={() => setOpen("edit")}
|
||||
/>
|
||||
) : null}
|
||||
<RowIconButton
|
||||
icon={Users}
|
||||
title={`Choose who gets ${knowledgebase.name}`}
|
||||
disabled={busy}
|
||||
onClick={() => setOpen("access")}
|
||||
/>
|
||||
{targets.can_edit && knowledgebase.document_count ? (
|
||||
<RowIconButton
|
||||
icon={RefreshCw}
|
||||
title={`Re-index ${knowledgebase.name}: read every document again`}
|
||||
disabled={busy}
|
||||
onClick={() =>
|
||||
post({
|
||||
path: "knowledgebases/reindex-knowledgebase",
|
||||
confirm: `Read every document in ${knowledgebase.name} again? Bots keep finding the old passages until the new ones are in.`,
|
||||
})
|
||||
}
|
||||
/>
|
||||
) : null}
|
||||
{targets.can_edit ? (
|
||||
<RowIconButton
|
||||
icon={Trash2}
|
||||
title={`Delete ${knowledgebase.name}`}
|
||||
disabled={busy}
|
||||
onClick={() =>
|
||||
post({
|
||||
path: "knowledgebases/delete-knowledgebase",
|
||||
confirm: `Delete ${knowledgebase.name} and every document in it? Bots lose it at once.`,
|
||||
})
|
||||
}
|
||||
/>
|
||||
) : null}
|
||||
</Row>
|
||||
<SettingsRowMenu title={`${knowledgebase.name} menu`} disabled={busy}>
|
||||
<SettingsRowMenuPanel>
|
||||
<SettingsRowMenuItem icon={FileText} title="Documents" onClick={() => setOpen("documents")} />
|
||||
{targets.can_edit ? (
|
||||
<SettingsRowMenuItem icon={Pencil} title="Edit" onClick={() => setOpen("edit")} />
|
||||
) : null}
|
||||
<SettingsRowMenuItem icon={Users} title="Who gets it" onClick={() => setOpen("access")} />
|
||||
{targets.can_edit && knowledgebase.warning_count ? (
|
||||
<SettingsRowMenuItem
|
||||
icon={RotateCcw}
|
||||
title="Retry failed"
|
||||
description={`Read again the ${knowledgebase.warning_count} ${knowledgebase.warning_count == 1 ? "document" : "documents"} that failed. The ones that already succeeded stay as they are.`}
|
||||
onClick={() =>
|
||||
post({
|
||||
path: "knowledgebases/retry-failed-documents",
|
||||
confirm: `Read again the ${knowledgebase.warning_count} ${knowledgebase.warning_count == 1 ? "document" : "documents"} in ${knowledgebase.name} that failed? The ones that already succeeded stay as they are.`,
|
||||
})
|
||||
}
|
||||
/>
|
||||
) : null}
|
||||
{targets.can_edit && knowledgebase.document_count ? (
|
||||
<SettingsRowMenuItem
|
||||
icon={RefreshCw}
|
||||
title="Re-index"
|
||||
description="Read every document again. Bots keep finding the old passages until the new ones are in."
|
||||
onClick={() =>
|
||||
post({
|
||||
path: "knowledgebases/reindex-knowledgebase",
|
||||
confirm: `Read every document in ${knowledgebase.name} again? Bots keep finding the old passages until the new ones are in.`,
|
||||
})
|
||||
}
|
||||
/>
|
||||
) : null}
|
||||
{targets.can_edit ? (
|
||||
<SettingsRowMenuItem
|
||||
icon={Trash2}
|
||||
title="Delete"
|
||||
description="Delete it and every document in it. Bots lose it at once."
|
||||
onClick={() =>
|
||||
post({
|
||||
path: "knowledgebases/delete-knowledgebase",
|
||||
confirm: `Delete ${knowledgebase.name} and every document in it? Bots lose it at once.`,
|
||||
})
|
||||
}
|
||||
/>
|
||||
) : null}
|
||||
</SettingsRowMenuPanel>
|
||||
</SettingsRowMenu>
|
||||
</SettingsListRow>
|
||||
{open == "documents" ? (
|
||||
<KnowledgebaseDocumentsModal
|
||||
|
||||
@@ -0,0 +1,67 @@
|
||||
import grabSuperAdminUser from "@/src/functions/backend/backups/grab-super-admin-user";
|
||||
import grabKnowledgebasesOverview from "@/src/functions/backend/db/knowledgebases/grab-knowledgebases-overview";
|
||||
import listKnowledgebaseDocuments from "@/src/functions/backend/db/knowledgebases/list-knowledgebase-documents";
|
||||
import retryFailedDocuments from "@/src/functions/backend/db/knowledgebases/retry-failed-documents";
|
||||
import logEvent, { grabRequestIP } from "@/src/functions/backend/logger";
|
||||
import { KnowledgebaseIdRequestSchema } from "@/src/schemas/knowledgebase-schema";
|
||||
import type { KnowledgebaseDocumentsPayload, KnowledgebasesOverviewPayload } from "@/src/types";
|
||||
import AppError from "@/src/utils/app-error";
|
||||
import parseWithSchema from "@/src/utils/parse-with-schema";
|
||||
import safeErrorMessage from "@/src/utils/safe-error-message";
|
||||
import type { APIResponseObject, BunextAPIRouteHandler } from "@moduletrace/bunext/types";
|
||||
import { z } from "zod";
|
||||
|
||||
const RequestSchema = KnowledgebaseIdRequestSchema.extend({
|
||||
/**
|
||||
* Set when the documents list retries one document; the answer is then
|
||||
* that list. Left out, the knowledgebase's row retries every failed
|
||||
* document and the answer is the overview.
|
||||
*/
|
||||
document_id: z.coerce.number().int().positive().optional(),
|
||||
});
|
||||
|
||||
/**
|
||||
* Super admin only: reads again the documents whose last read failed.
|
||||
* Ones that already succeeded stay as they are.
|
||||
*/
|
||||
export const handler: BunextAPIRouteHandler<
|
||||
APIResponseObject<KnowledgebasesOverviewPayload | KnowledgebaseDocumentsPayload>
|
||||
> = async ({ req, body }) => {
|
||||
try {
|
||||
if (req.method != "POST") {
|
||||
throw new AppError(`Method not allowed`);
|
||||
}
|
||||
|
||||
const user = await grabSuperAdminUser({ req });
|
||||
|
||||
if (!user?.id) {
|
||||
throw new AppError(`Only a super admin can do that.`);
|
||||
}
|
||||
|
||||
const { knowledgebase_id, document_id } = parseWithSchema({ schema: RequestSchema, data: body });
|
||||
const queued = await retryFailedDocuments({ knowledgebase_id, document_id });
|
||||
|
||||
await logEvent({
|
||||
title: "Knowledgebase failed documents retried",
|
||||
category: "system",
|
||||
user_id: user.id,
|
||||
plain_text: `User #${user.id} retried ${queued} failed ${queued == 1 ? "document" : "documents"} of the knowledgebase #${knowledgebase_id}.`,
|
||||
metadata: { knowledgebase_id, document_id, queued },
|
||||
ip_address: grabRequestIP(req),
|
||||
});
|
||||
|
||||
const msg = queued
|
||||
? `Reading ${queued} failed ${queued == 1 ? "document" : "documents"} again.`
|
||||
: "Nothing failed to read.";
|
||||
|
||||
return {
|
||||
success: true,
|
||||
msg,
|
||||
singleRes: document_id
|
||||
? await listKnowledgebaseDocuments({ knowledgebase_id })
|
||||
: await grabKnowledgebasesOverview({ user_id: user.id }),
|
||||
};
|
||||
} catch (error: unknown) {
|
||||
return { success: false, msg: safeErrorMessage({ error }) };
|
||||
}
|
||||
};
|
||||
@@ -436,6 +436,10 @@ export type HostDirectoryComputerLink = BUN_SQLITE_COBBLE_HOST_DIRECTORY_COMPUTE
|
||||
*/
|
||||
export type HostDirectoryWorkspaceLink = BUN_SQLITE_COBBLE_HOST_DIRECTORY_WORKSPACES & {
|
||||
workspace_name?: string | null;
|
||||
/**
|
||||
* The workspace's picture, for its row. Null means the workspace icon.
|
||||
*/
|
||||
image_media_id?: number | null;
|
||||
/**
|
||||
* The computers the workspace is on, where this folder is mounted.
|
||||
*/
|
||||
|
||||
@@ -0,0 +1,45 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import unfinishedAnswerText from "./unfinished-answer-text";
|
||||
|
||||
describe("unfinishedAnswerText", () => {
|
||||
test("a table row that stops after its label is unfinished", () => {
|
||||
const text = ["| Skill | Focus |", "|-------|-------|", "| **revops** | Lead routing"].join("\n");
|
||||
|
||||
expect(unfinishedAnswerText({ text }) ?? "").toContain("table row");
|
||||
});
|
||||
|
||||
test("a separator is not an open row", () => {
|
||||
expect(unfinishedAnswerText({ text: "| Skill | Focus |\n|-------|-------|" })).toBeNull();
|
||||
});
|
||||
|
||||
test("a table row whose last cell never closed is unfinished", () => {
|
||||
const text = "| **revops** | Lead routing, scoring";
|
||||
|
||||
expect(unfinishedAnswerText({ text })).toContain("table row");
|
||||
});
|
||||
|
||||
test("a finished table is a reply", () => {
|
||||
const text = ["| Skill | Focus |", "| **revops** | Lead routing |", "", "Want me to pull one in full?"].join("\n");
|
||||
|
||||
expect(unfinishedAnswerText({ text })).toBeNull();
|
||||
});
|
||||
|
||||
test("a fence left open is unfinished", () => {
|
||||
expect(unfinishedAnswerText({ text: "The script:\n\n```ts\nconst n = 1" })).toContain("code fence");
|
||||
});
|
||||
|
||||
test("a closed fence is a reply", () => {
|
||||
expect(unfinishedAnswerText({ text: "```ts\nconst n = 1\n```\n\nThat is the whole script." })).toBeNull();
|
||||
});
|
||||
|
||||
test("a heading or list marker with nothing under it is unfinished", () => {
|
||||
expect(unfinishedAnswerText({ text: "What I found\n\n##" })).toContain("heading");
|
||||
expect(unfinishedAnswerText({ text: "Next:\n\n-" })).toContain("heading");
|
||||
expect(unfinishedAnswerText({ text: "1." })).toContain("heading");
|
||||
});
|
||||
|
||||
test("a finished heading and a pipe in prose are replies", () => {
|
||||
expect(unfinishedAnswerText({ text: "## What I found\n\nTwo repos, nothing pulled yet." })).toBeNull();
|
||||
expect(unfinishedAnswerText({ text: "Use a | between the columns when you write it." })).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,83 @@
|
||||
/**
|
||||
* Why an answer stops inside a structure the model meant to finish, or
|
||||
* null when the text can stand as a reply. The check is structural: a
|
||||
* table row with no close, a fence left open, a heading or list marker
|
||||
* with nothing under it. It never decides that a follow-up was owed.
|
||||
* That is the model's call (`suggest_next_steps`), and reading it out of
|
||||
* prose is what `send_reply` exists to stop.
|
||||
*/
|
||||
export default function unfinishedAnswerText({ text }: { text: string }): string | null {
|
||||
const trimmed = text.trim();
|
||||
|
||||
if (!trimmed) return null;
|
||||
|
||||
if (openFence({ text: trimmed })) {
|
||||
return "The message stops inside a code fence that was never closed. Finish the fence, or take it out, and send the whole message again.";
|
||||
}
|
||||
|
||||
const last = lastContentLine({ text: trimmed });
|
||||
|
||||
if (openTableRow({ line: last })) {
|
||||
return "The message stops in the middle of a markdown table row. Finish that row and the table, or take the unfinished row out, and send the whole message again.";
|
||||
}
|
||||
|
||||
if (bareMarker({ line: last })) {
|
||||
return "The message stops on a heading or a list marker with nothing under it. Finish that part, or take the marker out, and send the whole message again.";
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* A fence is open when an odd number of fence lines remain. A fence line
|
||||
* is ``` or ~~~ with nothing but an optional language tag after it, so a
|
||||
* row of dashes in a table is not one.
|
||||
*/
|
||||
function openFence({ text }: { text: string }) {
|
||||
let open = false;
|
||||
|
||||
for (const line of text.split("\n")) {
|
||||
if (/^ {0,3}(`{3,}|~{3,})[^`~]*$/.test(line.trimEnd())) open = !open;
|
||||
}
|
||||
|
||||
return open;
|
||||
}
|
||||
|
||||
/**
|
||||
* The last line that holds something. Trailing blank lines are how a
|
||||
* model ends a paragraph, not how it ends a table.
|
||||
*/
|
||||
function lastContentLine({ text }: { text: string }) {
|
||||
const lines = text.split("\n");
|
||||
|
||||
for (let index = lines.length - 1; index >= 0; index--) {
|
||||
const line = lines[index]!.trim();
|
||||
|
||||
if (line) return line;
|
||||
}
|
||||
|
||||
return "";
|
||||
}
|
||||
|
||||
/**
|
||||
* A table row that opened and never closed: `| **revops** |` with the
|
||||
* rest of the cell on no line at all, or a row whose last cell is still
|
||||
* being written (`| **revops** | Lead routing`). A finished row ends with
|
||||
* `|`. A separator (`|---|---|`) is finished too. A line that merely
|
||||
* mentions a pipe in prose is left alone.
|
||||
*/
|
||||
function openTableRow({ line }: { line: string }) {
|
||||
if (!line.startsWith("|")) return false;
|
||||
if (line.endsWith("|")) return false;
|
||||
if (/^\|?\s*:?-{3,}:?\s*(\|\s*:?-{3,}:?\s*)+\|?\s*$/.test(line)) return false;
|
||||
|
||||
return (line.match(/\|/g) || []).length >= 1;
|
||||
}
|
||||
|
||||
/**
|
||||
* A heading, or a list marker, whose line holds nothing else. A heading
|
||||
* with its text, and a list item with its text, are finished lines.
|
||||
*/
|
||||
function bareMarker({ line }: { line: string }) {
|
||||
return /^#{1,6}$/.test(line) || /^[-*+]$/.test(line) || /^\d{1,3}[.)]$/.test(line);
|
||||
}
|
||||
Reference in New Issue
Block a user