Commit Graph
1973 Commits
Author SHA1 Message Date
ntduc b428baf70b docs(hooks): document script context injection 2026-07-22 14:13:30 +07:00
ntduc 03a196e613 feat(hooks): add script context injection 2026-07-22 14:13:23 +07:00
ntduc e4e4bb33fb fix(feishu): preserve group context without sender name 2026-07-20 15:05:54 +07:00
SYNITYandDangTinh311 aa27354d16 fix(bitrix24): label quoted-media reply note from downloaded MIME [B24:2794] (#1444)
Follow-up to #1443. For a media-only quoted message, im.dialog.messages.get
frequently returns a blank type/name (observed live for a voice note), so the
reply note fell back to the generic "một tệp" even though the file was correctly
downloaded and tagged <media:audio>.

Build the note AFTER downloading and derive the kind label from the downloaded
file's MIME (reusing classifyMediaType), so it reads "một tin nhắn thoại" /
"một hình ảnh" / "một video" to match the <media:*> tag the agent receives.
Falls back to the Bitrix file type, then "tệp", when no download is available
(e.g. oversized). Also adopts the downloaded filename when messages.get omitted it.

Adds tests for the MIME-preference path and mediaKindVN.

Co-authored-by: DangTinh311 <dangtinh31193@gmail.com>
2026-07-16 11:25:20 +07:00
SYNITYandDangTinh311 2a23ad0c42 feat(bitrix24): recognize reply/quote context across all message types [B24:2794] (#1443)
Bitrix24 ships the quoted message inline on reply events via REPLY_MESSAGE,
but the channel parsed a non-existent REPLY_TO_MESSAGE_ID field, so the agent
never saw what a user was replying to. Recognize replies and feed their
context to the agent (Hybrid design):

- events.go: parse data[PARAMS][REPLY_MESSAGE][ID|AUTHOR_ID|MESSAGE] (form+json)
  with PARAMS[REPLY_ID] fallback into EventParams.ReplyMessage; drop the dead
  ReplyToMID field + bitrix_reply_to_mid meta.
- reply_context.go (new): resolveReplyContext prepends a short note and, for
  media-only originals, re-injects the quoted file(s) through the same download
  pipeline as a direct upload.
    text quote  -> sanitize BBCode + truncate, no API call.
    media quote -> im.dialog.messages.get (works for TYPE=bot bots, unlike the
      blocked imbot.v2.Chat.Message.get) to recover the attachment, bounded by
      media_max_mb; note-only fallback on any fetch/download failure.
- handle.go: wire resolveReplyContext into message assembly (prefix + extra media).

Covers text, image, audio, file, video quotes. Non-reply events are a no-op.
Adds unit tests for parse (form+json), sanitize, file-id extraction, result
parsing, the messages.get fetch, and both resolve branches.

Co-authored-by: DangTinh311 <dangtinh31193@gmail.com>
2026-07-16 10:56:32 +07:00
dc605b911e feat(mcp): expand CRUD server to near-complete CLI parity (#1440)
* feat(mcp): expand CRUD MCP server to near-complete CLI parity

Closes the CLI-vs-MCP tool coverage gap identified by auditing every
`goclaw` CLI command against the existing goclaw_* MCP tool set. Adds
skill grant/revoke, agent skill pin/unpin, and full CRUD/inspection
surfaces for memory, knowledge graph (including dedup/merge/prune),
tenants, providers, LLM traces, channel contacts, pending messages,
audit activity, system config, tenant storage (list/size/delete/move),
scoped agent config export/import, secure-CLI binary registry, and a
DB-backed health check.

Deliberately out of scope, documented inline where relevant:
- `goclaw credentials`: confirmed CLI-local (~/.goclaw/config.yaml +
  keychain), no server resource to wrap. goclaw_secure_cli_binaries_*
  covers the closest real, previously-uncovered server resource instead.
- Full tar-archive agent export/import (KG + workspace files): the CLI's
  version streams a multi-section archive with progress events, a shape
  that doesn't map to a single MCP tool call. Config + context files
  (the portable "brain") is covered.
- `kg extract` (LLM-driven text extraction): goclaw_kg_ingest accepts
  the same Entity/Relation shapes the extractor produces, so a caller
  can run extraction itself and hand off the result.

Wires 8 new store dependencies (Memory, KnowledgeGraph, Tracing,
Contacts, PendingMessages, Activity, SystemConfigs, SecureCLI) through
gateway.Server setters -> cmd/gateway.go -> CRUDDeps, following the
existing Providers/Tenants pattern. Storage and secure-CLI-binary
handlers duplicate internal/http's path-escape/symlink-hiding
validation logic (documented inline) since internal/http already
imports internal/mcp and the reverse would cycle.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>

* fix(mcp): return sessionKey in goclaw_chat_send response for persistent conversations

The goclaw_chat_send tool creates a new session internally when sessionKey is
empty, but never returned the key to the caller. This prevented using
goclaw_chat_history to fetch previous messages in the session.

Add SessionKey field to ChatSendResult so callers can:
1. Start a new agent chat without providing sessionKey
2. Receive the sessionKey back in the response
3. Use that sessionKey for follow-up messages and history queries

Fixes the training loop pattern: start chat → get sessionKey → call
goclaw_chat_history with that key → iterate skill based on actual failures.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>

* feat(mcp): add timing diagnostics to goclaw_chat_send for timeout troubleshooting

Log request arrival, processing duration, and errors with millisecond precision.
Helps identify whether timeouts occur at MCP client→goclaw, goclaw→ollama, or
during agent execution. Critical for production debugging.

Co-Authored-By: Claude Haiku 4.5 <noreply@anthropic.com>

* fix(gateway): add http.Server timeouts for defensive timeout handling

Set explicit timeouts in http.Server:
- ReadTimeout: 1h (allow large uploads, long-running agent operations)
- WriteTimeout: 1h (allow streaming responses to slow clients)
- IdleTimeout: 30s (close idle keep-alive connections quickly)

Provides defense-in-depth when Nginx/Traefik timeouts are misconfigured.
Matches Nginx timeout (3600s) to prevent race conditions.

Timeout chain: traefik 3600s = nginx 3600s = goclaw 3600s

Co-Authored-By: Claude Haiku 4.5 <noreply@anthropic.com>

---------

Co-authored-by: Bruno Clermont <bruno.clermont@gmail.com>
Co-authored-by: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-16 01:56:03 +07:00
SYNITYandDangTinh311 02249593a2 fix(packages): make .runtime group-writable for goclaw self-update [B24:2794] (#1439)
The entrypoint set /app/data/.runtime to root:goclaw 0750 so the root
pkg-helper can write apk-packages. But the gateway runs as goclaw and the
github-package self-update flow (running in-process as goclaw) must write
into .runtime: the scratch dir (.runtime/tmp/<pkg>-<tag>-<nanos>) and the
manifest (.runtime/github-packages.json[.tmp], updates-cache.json).

With 0750 the group has no write bit, so updating a github binary package
(e.g. goclaw v0.6.2 -> v0.8.0) fails with:
  create scratch dir: ... mkdir /app/data/.runtime/tmp: permission denied
and, if the scratch is worked around, later:
  manifest save failed: open .../github-packages.json.tmp: permission denied

Change the mode to 0770 so root keeps ownership (apk-packages still root)
while the goclaw group can create the scratch dir and rewrite the manifest.

Co-authored-by: DangTinh311 <dangtinh31193@gmail.com>
2026-07-15 17:55:27 +07:00
SYNITYandDangTinh311 c203d45811 fix(cron): guard nil job and tenant-consistent readback in cron create [B24:2794] (#1438)
Creating a cron job over a connection with no tenant in context
(gateway-token / CLI / master-scope UI session) panicked with a
nil-pointer dereference.

Root cause — tenant asymmetry between insert and readback:
- AddJob INSERT uses tenantIDForInsert(ctx), which falls back to
  MasterTenantID when the context has no tenant (row inserted OK).
- The readback (scanJob / GetJob) rejects a nil-tenant context with
  "tenant_id required", so GetJob returned (nil, false) and AddJob
  swallowed it as (nil, nil).
- handleCreate then dereferenced job.ID (UpdateJob patch) → panic.

Fix (defense-in-depth):
- handleCreate (internal/gateway/methods/cron.go): add a nil-job guard
  before any job.ID use; return ErrInternal instead of panicking. Apply
  the post-create stateless/command patch under a tenant-consistent
  context (WithTenantID(ctx, job.TenantID)) so lockCronJobForMutation
  finds the row for nil-tenant callers.
- AddJob (store/pg + store/sqlitestore cron_crud.go): read back under
  WithTenantID(ctx, tenantIDForInsert(ctx)) so insert and readback share
  the same tenant; return an explicit error if readback fails instead of
  swallowing it.

Tests:
- internal/store/sqlitestore/cron_crud_test.go: AddJob with a nil-tenant
  context returns a non-nil job + nil error (real SQLite DB).
- internal/gateway/methods/cron_test.go: handleCreate does not panic and
  skips UpdateJob when the store returns (nil, nil).

Co-authored-by: DangTinh311 <dangtinh31193@gmail.com>
2026-07-15 16:54:49 +07:00
293aa2a5e1 (feat) MCP Server (#1365)
* feat(hooks/observe): add structured output validation hook (ObserveHook)

- hooks/types.go: Add ObserveHook interface + BuiltInHookType enum
- hooks/dispatcher.go: HookDispatcher emits ObserveHook with PhaseResult payload
- pipeline/observe_stage.go: ObserveStage emits hook after ObserveResult built
- pipeline/substates.go: ObserveStageResult carries hook results + validation errors
- hooks/config.go: BuiltInHookTypeObserve added to BuiltInHookType enum

PhaseResult carries structured output, token usage, tool calls + validation errors
emitted post-ObserveStage. ObserveHook implementations can validate structured
output against schemas, detect tool-call loops, enforce token budgets, etc.

Hook fires after ObserveStage produces ObserveResult, before results propagate
to next stage. ValidationError returned by hook halts pipeline and propagates
error to caller without further stage execution.

Co-Authored-By: Claude <noreply@anthropic.com>

* ui(hooks): add post_model_response event to web UI

- Add event to Zod schema, filter dropdown, and form dialog
- Implement conditional test panel UI for model response payload
- Add translations (en/zh/vi) for new test panel fields
- Updated beta description to reference the new event

Co-Authored-By: Claude <noreply@anthropic.com>

* feat(mcp): add MCP CRUD server exposing goclaw resources at /api/mcp/ with Bearer token auth
and X-GoClaw-Tenant-Id header, default to master tenant

* feat(mcp): add goclaw_skills_write_file tool to edit skill files on disk

The CRUD MCP server's goclaw_skills_update only touched skill DB metadata,
with no way to edit a skill's SKILL.md/file content on the filesystem. Extract
the versioned write logic from the web UI's skill file editor
(SkillsHandler.handleWriteFile) into skills.WriteVersionedFile so both
surfaces share identical validation and versioning, and expose it as a new
MCP tool.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>

---------

Co-authored-by: Bruno Clermont <bruno.clermont@gmail.com>
Co-authored-by: Claude <noreply@anthropic.com>
2026-07-15 09:56:43 +07:00
4f558e2c3b fix(ollama): resolve context window per model via POST /api/show (#1437)
The Ollama integration never applied a correct context window, so agents
with real prompts (20k-100k tokens) were rejected with HTTP 400
exceed_context_size_error against a 4096-token default.

Three root causes fixed:

1. FetchOllamaModelContext issued a GET to /api/show, which Ollama answers
   with 405 (the endpoint is POST-only). Now POSTs {"model": "<name>"}.

2. The response parser expected a flat model_info.context_length, but a real
   Ollama server namespaces the key by architecture (gemma4.context_length,
   qwen3.context_length, ...). extractContextLength now matches "context_length"
   or any "*.context_length" key.

3. num_ctx was resolved once at startup for a hardcoded "llama3.3" model and
   never for the model an agent actually uses. Resolution now happens per
   request for the real model inside OllamaProvider.resolveNumCtx, cached under
   an RWMutex, with an explicit settings override winning and the fetched value
   bounded by OllamaDefaultNumCtx so an enormous advertised window (Qwen3.5
   reports 262144) cannot balloon the KV cache beyond VRAM.

Also classify Ollama's "exceed_context_size" 400 as a context-overflow error so
the pipeline's emergency-compaction+retry path (Issue 958) engages gracefully
instead of surfacing a raw error.

Co-authored-by: Bruno Clermont <bruno.clermont@gmail.com>
Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-15 08:24:31 +07:00
Syed Osama Ali Shah 6f91b937c1 fix(slack): don't double-emit trailing text on odd number of ``` fences (#1436)
extractCodeBlocks split on "```" and treated every odd-indexed part as a
closed code block. With an odd number of fences (>=3), Split returns an even
number of parts, so the final segment -- which follows an unpaired opening
fence and must stay literal -- landed on an odd index and was both emitted as
a \x00CB\x00 placeholder (later restored as ```seg```) AND re-appended
verbatim by the trailing len(parts)%2==0 block. The segment was therefore
duplicated in the rendered Slack message (and blocks gained a spurious entry).
Unclosed trailing fences are common in streamed LLM output.

Exclude the final unpaired part from the paired-scan loop. Add a regression
test covering the closed-block-then-unpaired-fence case.
2026-07-15 00:54:17 +07:00
Duc Nguyenandntduc 27f4b7743b fix(skills): preserve custom skills during bundled seeding (#1435)
Co-authored-by: ntduc <ntduc@cpp.ai.vn>
2026-07-15 00:25:07 +07:00
Clark Cant 1f5a6f0ef6 Merge pull request #1434 from tech-synity/b24-2794-agent-activity-indicator
feat(bitrix24): agent activity indicator via InputAction.notify
2026-07-14 17:24:05 +07:00
DangTinh311 af43c952ed feat(bitrix24): agent activity indicator via InputAction.notify [B24:2794]
Show an ephemeral "agent is working" indicator (thinking/searching/
generating/analyzing…) in Bitrix24 chat while the agent processes, so
users on this non-streaming channel aren't left staring at silence
until the final reply. Send behavior is unchanged; no LLM call, no DB.

Generic layer (internal/channels):
- New optional ActivityIndicatorChannel interface.
- HandleAgentEvent routes run.started->THINKING, tool.call->mapped
  status, tool.result->ANALYZING; static tool->status mapping.
- Conditional heartbeat ticker fills LLM-inference gaps (re-sends only
  when idle), 5s per-run throttle caps call rate; ticker stopped on
  terminal events AND in UnregisterRun (safety net for missed terminals).

Bitrix24 (internal/channels/bitrix24):
- OnActivityEvent calls imbot.v2.Chat.InputAction.notify best-effort,
  drop-on-limit (raw Client.Call, no retry) so cosmetic notifies never
  steal leaky-bucket capacity from real message sends.
- Per-channel activity_indicator toggle (default on).

Web UI + docs: dashboard toggle, i18n en/vi/zh, channels doc section.
Tests: 26 unit tests incl. UnregisterRun-stops-ticker regression.
2026-07-14 15:28:14 +07:00
SYNITYandDangTinh311 6167a53bbe fix(bitrix24): mount shared webhook route independent of bot readiness [B24:2794] (#1432)
/bitrix24/* only mounted when a bitrix24 Channel loaded successfully via
WebhookHandlers(), which requires portal + bot_code + bot_name already
set. But completing portal OAuth requires /bitrix24/install to be
reachable, and the UI won't let you pick an uninstalled portal when
creating a bot -- deadlock on any fresh deployment: no bot can load
until OAuth completes, OAuth can't complete without the route mounted.

Claim and mount the shared bitrix24.WebhookRouter() singleton directly
at boot, independent of whether any Channel loaded. ClaimWebhookRoute
is idempotent (first-claim-wins via CompareAndSwap), so this is a
no-op once a real Channel has already claimed the route.

Co-authored-by: DangTinh311 <dangtinh31193@gmail.com>
2026-07-13 08:25:59 +07:00
SYNITYandDangTinh311 143ed4a8a4 fix(bitrix24): make pending-portal delete button clickable in Radix Select [B24:2794] (#1431)
The delete affordance next to each pending portal in the channel-create
form was wired to onClick, but Radix Select closes the popover on the
SelectItem's own pointerdown handler. By the time the click event would
fire on the nested button, the popover — and the button — are gone.
onPointerDown on the button additionally called e.preventDefault(),
which further blocked the browser from synthesising the click at all.

Result: clicking the trash icon looked completely dead. Keyboard users
were already covered by the Delete/Backspace onKeyDown handler on the
SelectItem itself; only mouse users were locked out.

Fire setPendingDeleteName from onPointerDown (with stopPropagation +
preventDefault so the parent SelectItem doesn't also select the pending
portal), and keep the onClick handler so the button stays activatable by
Enter/Space when it takes focus. This mirrors the pattern Radix uses for
its own nested interactive elements (e.g. DropdownMenu.CheckboxItem).

Surface parity:
  - Gateway server: N/A because the change is UI-only.
  - API contract:  N/A because bitrix.portals.delete already exists.
  - Web UI:        the single component that owned the broken handler.
  - CLI/runtime:   N/A because no CLI reads this UI state.

Co-authored-by: DangTinh311 <dangtinh31193@gmail.com>
2026-07-13 07:23:49 +07:00
Huy Tran fec70a7910 📝 docs: prioritize Vietnamese language in README (#767) 2026-07-13 01:56:16 +07:00
Matt Van HornandMatt Van Horn e5b5d03e3d fix: persist explicit None TTS provider instead of dropping it (#1424)
Co-authored-by: Matt Van Horn <455140+mvanhorn@users.noreply.github.com>
2026-07-12 12:56:59 +07:00
SYNITYandDangTinh311 4ff7c56338 fix(bitrix24): normalize ws/wss scheme in public URL detection (#1425)
Co-authored-by: DangTinh311 <dangtinh31193@gmail.com>
2026-07-11 18:54:06 +07:00
SYNITY bfd86091c0 fix(whatsapp): add missing protobuf import breaking dev build [B24:2794] (#1426)
fix(whatsapp): add missing protobuf import breaking dev build (#1426)
2026-07-11 18:24:34 +07:00
Reski Rukmantiyo 5773eec167 feat: implement slash command handling and text feedback for WhatsApp channel (#819) 2026-07-11 15:26:12 +07:00
61993b4387 feat(i18n): add Russian (ru) language — full parity across backend, web & desktop (#1391)
* docs(i18n): design spec for Russian (ru) language support

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* feat(i18n): register ru locale constant and IsSupported

* feat(i18n): scaffold ru catalog (en placeholders)

* feat(i18n): translate ru backend catalog to Russian

* fix(i18n): polish ru catalog grammar per review

* feat(i18n): wire ru into system messages, config enum, parity test

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* feat(i18n): add ru to web language constants and system-message locales

* feat(i18n): scaffold ru web locale dir (en placeholders)

* feat(i18n): wire ru resources into web i18next config

* feat(i18n): translate ru web locale to Russian (41 namespaces)

* fix(i18n): normalize ru web terminology (арендатор, привязка)

* fix(i18n): restore dropped 'named' in ru setup OAuth hint

* feat(i18n): wire ru into desktop i18next and language pickers

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* feat(i18n): add ru desktop locale (Russian, 16 namespaces)

* test(i18n): extend traces/hooks locale guards to cover ru

* chore(deploy): add repeatable fork-dev local build+deploy tooling

Adds a one-command, idempotent way to run goclaw from a locally built
image that merges fresh upstream dev with un-merged fork features
(Telegram trigger-words PR #1383 + Russian locale), independent of the
published :latest image.

- scripts/deploy-forkdev.sh: fetch origin/dev -> merge feature branches
  into local/fork-dev worktree -> push fork/dev -> build -> up -d.
- docker-compose.forkdev.yml: overlay pinning image to goclaw:forkdev
  with pull_policy:never so :latest never silently replaces the build.
- .gitignore: track the deploy helper (past deploy-*.sh), ignore the
  ../.goclaw-forkdev integration worktree.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* feat(telegram): agent-callable message reaction (message action=react)

Adds a "react" action to the message tool so an agent can set an emoji
reaction on an existing message (e.g. mark its own status post 👍 once
fully paid). Mirrors the ChannelEditor wiring: ReactionSetter capability
-> Manager.ReactToMessage -> telegram Channel.ReactToMessage (validates
against Telegram's supported reaction set; ✅/❌ are rejected).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* fix(config): remove ignored session scoping controls (#1405)

Co-authored-by: Collective Developer <man@collective.dev>

* feat(telegram): agent-callable message reaction (message action=react) (#1407)

Adds a "react" action to the message tool so an agent can set an emoji
reaction on an existing message (e.g. mark its own status post 👍 once
fully paid). Mirrors the ChannelEditor wiring: ReactionSetter capability
-> Manager.ReactToMessage -> telegram Channel.ReactToMessage (validates
against Telegram's supported reaction set; ✅/❌ are rejected).

Co-authored-by: skensel <skensel@MacBook-Pro-skensel.local>
Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* ci: build & publish fork image to GHCR (temporary, pre-upstream)

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* fix(memory): use 'russian' FTS config for memory_chunks recall

Memory keyword search (memory_search.go FTS + the generated tsv column)
used the 'simple' text-search config, which does no stemming. Russian
grammatical cases therefore never matched: a genitive query token
("Дианы") could not hit the stored nominative token ("Диана"), so
memory_search returned nothing for natural queries even though the fact
was saved. This is the sole recall path on deployments without an
embedding provider (ChatGPT-OAuth/codex cannot embed), so recall was
effectively dead there.

Switch both sides to the Snowball 'russian' config so index and query
lexemes stem to the same root ("диан"), restoring case-insensitive
recall. Migration 000094 recreates the generated tsv column (a GENERATED
expression cannot be ALTERed in place; ADD COLUMN backfills all rows).

Surface parity: desktop/SQLite N/A — SQLite memory search uses LIKE, a
separate mechanism unaffected by the PG regconfig.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: skensel <skensel@MacBook-Pro-skensel.local>
Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Co-authored-by: ナム <namnhfreelancer@gmail.com>
Co-authored-by: Collective Developer <man@collective.dev>
2026-07-11 12:25:38 +07:00
Zezae Oh 2a6872ac84 fix: honor model override for sync subagents (#1423) 2026-07-11 11:54:18 +07:00
ナムandCollective Developer 0d588e05c1 fix(discord): qualify group titles across surfaces (#1422)
* fix(discord): qualify group titles across surfaces

* feat(ui): add searchable delivery target selectors

---------

Co-authored-by: Collective Developer <man@collective.dev>
2026-07-11 11:25:23 +07:00
thotam 0c1ededc92 feat(webhooks): return per-call usage breakdown with provider/model/cost (#1421)
feat(webhooks): per-call usage breakdown with provider/model/cost (#1421)
2026-07-10 22:56:05 +07:00
ナムandCollective Developer 6b738924d5 fix(discord): qualify group titles across surfaces (#1420)
Co-authored-by: Collective Developer <man@collective.dev>
2026-07-10 22:25:45 +07:00
Vũ Thanh Thiênandalethienvu2 244197c2db feat: add config cloudflared, env for db port (#708)
Co-authored-by: alethienvu2 <ale.thienvu@setel.com>
2026-07-10 21:26:34 +07:00
thotam e95851e690 fix(pipeline): aggregate cache tokens across agent turns (#1419)
ThinkStage folded each turn's usage into state.Think.TotalUsage but summed
only prompt/completion/total/thinking tokens, dropping CacheReadTokens,
CacheCreationTokens and the PromptTokensIncludeCachedSegments flag. The
aggregated RunResult.Usage is the source for webhook usage responses and
usage_events analytics, so async multi-turn agent runs reported zero cache
tokens even when traces showed heavy prompt-cache use (cache is read
per-response for spans, but never summed into the aggregate).

Sum cache read/creation across turns and OR the include-cached flag (a
provider-level property, consistent across a run). Restores correct cache
accounting for webhook usage and usage_events without any envelope change.
2026-07-10 20:25:06 +07:00
b459d40531 feat(sandbox): expose Workdir field in SandboxConfig (#853)
The internal sandbox.Config already supports a custom container Workdir
that doubles as the workspace mount target, but config.SandboxConfig
(the JSONB-backed per-agent config) did not expose it. Without this,
agents must use the hardcoded /workspace mount point even when their
scripts expect a different in-container path.

Adds an optional "workdir" JSON field that maps through to
sandbox.Config.Workdir. Backward compatible — existing agents without
workdir set fall back to the /workspace default.

Co-authored-by: tuannt23065 <tuannt23065@users.noreply.github.com>
Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-07-10 15:56:31 +07:00
SYNITY 641d4f8756 feat(bitrix24): ship per-user OAuth re-authorization flow (#1417)
feat(bitrix24): ship per-user OAuth re-authorization flow (#1417)
2026-07-10 10:56:45 +07:00
Zezae Oh 9be468edad feat(providers): add GPT-5.6 Codex models (#1416) 2026-07-10 06:55:30 +07:00
db69ccf882 tracing: nest tool calls under LLM spans, emit hook spans, fix usage_events FK (#1415)
- Reparent tool_call spans under their producing llm_call span via
  RunState.CurrentLLMSpanID so a model turn's trace visibly contains the
  tool calls it triggered.
- Wire internal/hooks EmitHookSpan into the dispatcher writeExec so every
  hook execution (pre/post tool use, etc.) produces a trace span with input,
  console output, decision, error, and duration for agent troubleshooting.
- Fix usage_events_span_id_fkey violations: usage events were inserted
  synchronously referencing a span flushed ~5s later, silently dropping
  token/cost data. Route them through the collector so they flush after
  spans in the same cycle. No schema migration; FK preserved.

Co-authored-by: Bruno Clermont <bruno.clermont@gmail.com>
Co-authored-by: Claude <noreply@anthropic.com>
2026-07-10 03:54:42 +07:00
ナムandCollective Developer d84576939d fix(kg): count newly inserted dedup candidates (#1413)
Co-authored-by: Collective Developer <man@collective.dev>
2026-07-10 01:54:25 +07:00
ナムandCollective Developer 84fab59226 fix(memory): guide recency recall tool calls (#1412)
* fix(memory): guide recency recall tool calls

* fix(tools): align memory and vault builtin visibility

---------

Co-authored-by: Collective Developer <man@collective.dev>
2026-07-10 01:24:39 +07:00
ナムandCollective Developer e2af8b5f15 feat(memory): add episodic time filters to search (#1411)
Co-authored-by: Collective Developer <man@collective.dev>
2026-07-10 00:55:13 +07:00
ナムandCollective Developer 97e316f460 fix(memory): surface passive channel episodic recall (#1410)
* fix(memory): surface passive channel episodic recall

* fix(memory): expose episodic key topics

---------

Co-authored-by: Collective Developer <man@collective.dev>
2026-07-09 23:55:11 +07:00
ナムandCollective Developer 12d5619cdc fix(graph): preserve knowledge graph node colors (#1409)
Co-authored-by: Collective Developer <man@collective.dev>
2026-07-09 23:24:42 +07:00
ナムandCollective Developer e9898be505 fix(discord): honor disabled group history limit (#1406)
Co-authored-by: Collective Developer <man@collective.dev>
2026-07-09 17:25:37 +07:00
2b7bfec504 feat(telegram): agent-callable message reaction (message action=react) (#1407)
Adds a "react" action to the message tool so an agent can set an emoji
reaction on an existing message (e.g. mark its own status post 👍 once
fully paid). Mirrors the ChannelEditor wiring: ReactionSetter capability
-> Manager.ReactToMessage -> telegram Channel.ReactToMessage (validates
against Telegram's supported reaction set; ✅/❌ are rejected).

Co-authored-by: skensel <skensel@MacBook-Pro-skensel.local>
Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-09 16:55:54 +07:00
ナムandCollective Developer fb28b72b27 fix(config): remove ignored session scoping controls (#1405)
Co-authored-by: Collective Developer <man@collective.dev>
2026-07-09 16:24:58 +07:00
ba621391c2 feat(telegram): trigger-words, channel posts, message edit & topic posting (#1383)
- Fix image_generation nil-pointer crash on codex agents: the sentinel now
  carries a name-only Function so the many sites reading td.Function.Name never
  nil-deref; codex_build still branches on Type.
- Agent-declared trigger words in IDENTITY.md wake the bot in groups without an
  @mention (whole-word, Cyrillic-aware; text + caption), cached per-agent 60s.
- channel_post support with a synthetic sender + a recover() guard so a
  malformed update can't crash the gateway.
- message tool action=edit (editMessageText + editMessageCaption fallback),
  targeting the replied-to message via reply_to_message_id.
- message tool topic=<name> posts into a named forum topic; topics learned from
  forum_topic_created into channel_contacts and resolved by name.

Co-authored-by: skensel <skensel@MacBook-Pro-skensel.local>
Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-09 12:28:18 +07:00
SYNITYandDangTinh311 51ed7845e2 fix(bitrix24): register newly-created portal in live router [B24:2794] (#1404)
bitrix.portals.create only persisted the DB row — it never called
Router.RegisterPortal, so a portal created while the gateway was
already running stayed invisible to PortalByDomain/PortalByKey until
the next full restart. The only other RegisterPortal call site is
BootstrapPortals, which runs once at boot. Result: the OAuth install
callback 404'd with "unknown portal" for any portal created through
the self-service UI mid-uptime — hit live on web1trang.bitrix24.com.

Fix: inject registerPortal/unregisterPortal func fields into
BitrixPortalsMethods (mirrors the existing gatewayPublicURL func()
pattern), defaulting to bitrix24.WebhookRouter() + NewPortal/
RegisterPortal (same construction path as BootstrapPortals) and
Router.UnregisterPortal respectively. handleCreate calls
registerPortal after a successful Create; handleDelete calls
unregisterPortal after a successful Delete for symmetry. Both are
best-effort — a registration failure is logged, not returned as an
RPC error, since the DB row is already valid either way.

Injected via func fields (not calling bitrix24.WebhookRouter()
inline) so tests can stub live-router registration without touching
that process-wide singleton, whose test-reset helper isn't exported
outside the bitrix24 package.

Tests: 4 new cases covering register-on-create, best-effort failure
handling, unregister-on-delete, and no-unregister-when-delete-blocked.
All 20 tests in bitrix_portals_test.go pass; go build (both PG and
sqliteonly tags) and go vet clean.

Co-authored-by: DangTinh311 <dangtinh31193@gmail.com>
2026-07-09 10:54:56 +07:00
SYNITYandDangTinh311 47068ad563 feat: add delete affordance for pending portals in channel creation form [B24:2794] (#1403)
- Add delete icon (X) to portal dropdown items for pending (not-yet-installed) Bitrix24 portals
- Support mouse click and keyboard delete key (Del/Backspace) for removing pending portals
- Implement portal removal handler in bitrix-portal-select component
- Add comprehensive tests for delete functionality
- Update i18n strings (en/vi/zh) with delete action labels

Co-authored-by: DangTinh311 <dangtinh31193@gmail.com>
2026-07-09 10:24:43 +07:00
Duc Nguyen ee37017e0e fix: warm Zalo group-approval cache + attach quoted-image content tag (#1402)
* fix: warm Zalo group-approval cache so forwards from non-group origins route correctly

send.go picks ThreadTypeGroup vs ThreadTypeUser for a target chat ID by
checking BaseChannel's approvedGroups cache (or an explicit "group_id"
metadata key). That cache is only ever populated from INBOUND group
traffic under the "pairing" group policy — under "allowlist" (this
integration's actual default) it stays empty for the whole process
lifetime unless something else populates it, and it's wiped on every
restart regardless (in-memory sync.Map, no persistence).

message.go's cross-target forward only attaches "group_id" metadata when
isGroupContext(ctx) is true, which reflects the ORIGIN session's peer
kind, not the destination target's. Forwarding from a DM (or any non-group
session) into a group therefore sends with no group_id metadata and an
empty approval cache, so Send() defaults to ThreadTypeUser — the message
goes out addressed as if to a user account, not the group, and is never
seen there. No error is returned anywhere in this path, so nothing in the
existing (or previously fixed) error-reporting surfaces it.

ListGroups now marks every returned group ID as approved via
MarkGroupApproved, and Channel.Start kicks off a best-effort ListGroups
call right after connecting so the cache is warm from process start, not
just after an explicit zalo_list_groups tool call.

* fix: expose a media tag for quote-forwarded images, not just vision access

extractQuoteMedia downloads the image attached to a quoted message so the
model can see it via vision, but the composed content only ever carried
the literal "[Quoted image]" placeholder text (from TQuote.Text()) — no
<media:image> tag was ever inserted for it. The later agent-side
enrichment (enrichImageIDs/enrichImagePaths) only fills id/path attributes
into a bare tag it finds already present in content; with no tag to find,
the downloaded file had no path reference the model could hand back to
message(MEDIA:<path>) to forward it elsewhere, even though the file was
sitting on disk the whole time. Symptom: asked to forward a quoted image
to another chat, the agent reported "the image is only a quote, no direct
file to attach" despite genuinely having already downloaded it.

buildQuoteMediaTag renders the same bare <media:image> tag a direct
(non-quoted) attachment gets, appended after the quote wrapper text in all
three call sites (handleDM, handleGroupMessage,
extractContentAndMediaWithQuote) — ordered after any of the current
message's own attachment tags to match the media slice's append order, so
positional id/path enrichment lines up correctly.
2026-07-09 07:55:02 +07:00
Bruno ClermontandBruno Clermont d856a58218 feat(providers): make provider request timeout configurable (default 30s) (#1400)
The provider verify call and the provider models-list call used hardcoded
timeouts (30s and 15s) that were too low for slow models. Introduce a
tenant-scoped, UI-editable setting `providers.request_timeout_sec`
(default 30) stored in system_configs, consumed by both handlers, and
overlaid from config.json like tts.timeout_ms. Adds a field to the System
Settings modal (all 4 locales) so operators can raise it without a
redeploy.

Co-authored-by: Bruno Clermont <bruno.clermont@gmail.com>
2026-07-09 04:54:15 +07:00
Bruno ClermontandBruno Clermont 951acad714 feat(tools): seed missing built-in tools into builtin_tools catalog (#1399)
Eleven built-in tools were registered in the runtime tool registry (and
thus appeared in agent system prompts and were subject to allow/deny) but
were absent from builtinToolSeedData(), so operators could not see or
toggle them in the agent allow/deny UI. Seed datetime, heartbeat,
memory_expand, list_group_members, zalo_list_groups, vault_search,
vault_read, delegate, workstation_exec, claude_remote, and mcp_tool_search
so the UI catalog reflects the actual registered tool set. telegram_manager
is intentionally excluded per existing test guard.

Co-authored-by: Bruno Clermont <bruno.clermont@gmail.com>
2026-07-09 04:24:19 +07:00
Syed Osama Ali Shah f9b07d0a9c fix(tools): avoid panic in StripToolPrefix on overlapping prefix+suffix (#1398)
When a tool_call_prefix template has both a prefix and a suffix
(e.g. "pre_{tool_name}_suf"), StripToolPrefix stripped the prefix and
then sliced off the suffix length without checking the two ends don't
overlap. A model-emitted name that satisfies both HasPrefix and
HasSuffix but is shorter than prefix+suffix (e.g. "pre_suf") produced a
negative slice length -> "slice bounds out of range [:-1]" panic. This
runs in the agent turn loop on LLM-controlled names
(resolveToolCallName -> StripToolPrefix), so a crafted/degenerate name
crashes the turn.

Guard with len(prefix)+len(suffix) <= len(name); overlapping names now
fall through to returning the name unchanged, consistent with the other
no-match fallbacks. Adds a regression row to the prefix test table.
2026-07-09 03:54:33 +07:00
Bruno ClermontandBruno Clermont d3c04ab3e5 feat(bootstrap): skip built-in USER.md for predefined agents with USER_PREDEFINED.md (#1397)
When a predefined agent has an operator-authored USER_PREDEFINED.md, the
built-in per-user USER.md template is no longer seeded or injected into the
system prompt. This gives operators full control over user-context in the
prompt and stops the per-turn name/timezone profile nag. Open agents and
predefined agents without USER_PREDEFINED.md are unaffected.

Co-authored-by: Bruno Clermont <bruno.clermont@gmail.com>
2026-07-09 03:24:15 +07:00
Bruno ClermontandBruno Clermont 6bafe54b08 fix(agent): filter per-tenant disabled tools from system prompt (#1396)
The system prompt's Tooling section previously listed tools even when
they were disabled for a tenant and already stripped from the API
tools parameter, confusing the LLM into thinking it could use them.

Co-authored-by: Bruno Clermont <bruno.clermont@gmail.com>
2026-07-09 02:23:46 +07:00
Duc Nguyen aa15317d5b fix: resolve Zalo group by name + notify origin on failed forward (#1395)
* fix: resolve Zalo group name to real chat ID, notify origin on failed forward

Two related root causes behind "forward message to group by name" silently
failing while the agent reports success:

1. No tool let the agent resolve a group's display name (e.g. "Ban Dieu
   Hanh") to the chat ID the message tool actually requires. sessions_list
   only exposes session keys (numeric group IDs), never human-readable
   names, so the agent had no reliable way to turn a name into a real
   target and ended up passing the display name itself as `target`.

   Adds zalo_list_groups, wrapping the already-used (dashboard picker)
   protocol.FetchGroups behind the same optional-interface pattern as
   list_group_members/GroupMemberProvider (GroupListProvider on
   channels.Manager, gated to zalo_personal via RequiredChannelTypes).

2. When the resulting send fails downstream (e.g. Zalo rejects a bad
   chat_id), dispatchOutbound only ever retried/notified media failures on
   the same (already-broken) destination, and dropped text-only failures
   entirely — even though message.go's own postCrossTargetNotice comment
   states forwards must never announce a fake delivery. Because the bus
   publish is fire-and-forget, the tool had already returned "sent" and
   announced success to the origin chat before the real send was even
   attempted.

   message.go now tags cross-target forwards with origin channel/chat in
   OutboundMessage.Metadata; dispatchOutbound uses it to notify the ORIGIN
   chat with the real failure instead of silently dropping it or retrying
   against the same invalid target.

* test: cover forward-origin metadata tagging and dispatch failure notice

Extracts dispatchOutbound's error branch into handleSendFailure so it can
be unit tested without driving the consumer loop/goroutine, and adds
coverage for: forward failures notifying the origin chat (not the broken
destination), pre-existing non-forward media/text-only behavior staying
unchanged, message.go tagging cross-target group forwards with origin
metadata alongside group_id, and the new zalo_list_groups tool/Manager
delegator.
2026-07-08 23:23:08 +07:00