Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
49 commits
Select commit Hold shift + click to select a range
ed2d9b8
feat: integrate Mastra Code native TUI with guarded history restore
Oct 11, 2026
2ebab7b
fix: use native millisecond timeout for Mastra lifecycle hooks
Oct 11, 2026
1d321c5
fix: reconcile Mastra activity from current rendered viewport
Oct 11, 2026
0410977
fix: return a decision conflict for occupied native composers
Oct 11, 2026
a15edfd
fix: address Mastra CI findings and isolate serialized input admission
Oct 11, 2026
eb2c2f2
fix: observe Mastra restore identity through native plugin runtime
Oct 11, 2026
047c50e
fix: refresh only AO plugin instructions on native Mastra restore
Oct 11, 2026
14fedd5
fix: require native Mastra approvals for default AO permissions
Oct 11, 2026
e3876b5
docs: keep mastra-code audit evidence with its integration PR
Oct 12, 2026
eb73fd1
fix: reconcile mastra-code integration with main
Oct 12, 2026
6db4eca
chore: provide source-pinned Linux harness proof artifact
Oct 12, 2026
ec76699
fix: preserve mastra-code migration beside main artifact history
Oct 12, 2026
c5a6dda
test: allow full ACP replay burst to drain under race instrumentation
Oct 12, 2026
988c661
test: preserve mastra-code evidence while applying ACP replay CI budget
Oct 12, 2026
2ee473d
fix: render the official Mastra avatar
nikhilachale Oct 14, 2026
e873f8e
chore: reconcile Mastra integration with current main
nikhilachale Oct 14, 2026
787eaa7
test: handle Vite inline Mastra logo assets
nikhilachale Oct 14, 2026
618483e
docs: preserve Mastra UI journey and failed restore control
Oct 15, 2026
89e8eec
chore: reconcile mastra with current main
Oct 15, 2026
24dc3ce
docs: publish mastra evidence with incomplete gates
Oct 15, 2026
554c03f
fix: address Mastra Code review and reconcile main
nikhilachale Oct 17, 2026
1cb9705
fix: satisfy Mastra Code lint checks
nikhilachale Oct 17, 2026
acd074c
fix: reconcile Mastra migration with canonical awake schema
Oct 18, 2026
c23ef21
fix: reconcile Mastra integration with current main
Oct 18, 2026
8d711b9
Merge commit '55b02b848dd3f05f4d010fc5d603d5e9e6217669' into work/acp…
Oct 18, 2026
7556672
fix: reconcile Mastra setup and schema regression coverage
Oct 18, 2026
5a64f5a
merge: reconcile Mastra with current main lifecycle
Oct 19, 2026
e620e7c
Merge remote-tracking branch 'refs/remotes/canonical/main' into work/…
Oct 19, 2026
c7402e0
fix: fence Mastra restore and repair prior migration ledger
Oct 19, 2026
cf8e2c0
feat: add gated Mastra SDK Chat driver and exact native replay
Oct 19, 2026
f934d84
test: exercise Mastra candidate ports and immediate cancellation
Oct 19, 2026
2c0d17f
Merge remote-tracking branch 'refs/remotes/canonical/main' into work/…
Oct 19, 2026
a735212
fix: connect Mastra SDK candidate to AO launch context
Oct 19, 2026
adb2226
Merge remote-tracking branch 'refs/remotes/canonical/main' into work/…
Oct 19, 2026
290ff0a
fix: align Mastra login and authentication with native SDK
nikhilachale Oct 23, 2026
5f58768
fix: honor native model entry in task composer
nikhilachale Oct 23, 2026
5dce563
fix: match native auth routing and isolate probe startup
nikhilachale Oct 23, 2026
934907e
fix: reject incomplete native inference auth results
nikhilachale Oct 23, 2026
481de06
Merge remote-tracking branch 'preserved-harness-audit/main' into fix/…
nikhilachale Oct 23, 2026
dc08462
fix: resolve candidate driver lint findings
nikhilachale Oct 23, 2026
dcc2ce5
fix: keep native login accessible when auth is unknown
nikhilachale Oct 23, 2026
6585c10
fix: distinguish configured credentials from verified access
nikhilachale Oct 23, 2026
765dc53
fix: recognize native Mastra structured inference results
nikhilachale Oct 23, 2026
d75df3d
fix: default Mastra tasks to native permissions
nikhilachale Oct 23, 2026
30b4e72
test: check installer inventory against canonical harnesses
nikhilachale Oct 23, 2026
0772781
Merge commit 'b13b9514126c936a06e2b3f692495d9a95ba420e' into fix/pr65…
nikhilachale Oct 23, 2026
010b5cf
fix: satisfy native auth test types and lint
nikhilachale Oct 23, 2026
504638d
Merge main into Mastra Code PR and reconcile with current main
nikhilachale Nov 14, 2026
3b47ef6
fix(mastra-code): renumber harness migration above main and restore l…
nikhilachale Nov 14, 2026
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 14 additions & 0 deletions .github/workflows/go.yml
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,17 @@ env:
GOFLAGS: -gcflags=modernc.org/...=-race=false

jobs:
mastra-sdk-contract:
runs-on: ubuntu-latest
timeout-minutes: 10
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: "24"
- name: Test candidate Mastra SDK lifecycle and native history contract
run: node --test backend/internal/adapters/chatdriver/mastrasdk/*.test.mjs

backend-core:
runs-on: ubuntu-latest
timeout-minutes: 20
Expand Down Expand Up @@ -131,6 +142,9 @@ jobs:
- name: Test Windows PowerShell installers
run: go test -race -count=1 -v -run '^TestRunInstallScriptPowerShell' ./internal/adapters/systemexec/

- name: Test Mastra native history and Windows lock liveness
run: go test -race -count=1 -timeout=10m ./internal/adapters/agent/mastracode

- name: Test native Goose identity
run: go test -race -count=1 -timeout=10m ./internal/adapters/agent/binaryutil ./internal/adapters/agent/goose

Expand Down
2 changes: 2 additions & 0 deletions backend/internal/adapters/agent/activitydispatch/dispatch.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ import (
"github.com/aoagents/agent-orchestrator/backend/internal/adapters/agent/gemini"
"github.com/aoagents/agent-orchestrator/backend/internal/adapters/agent/kimchi"
"github.com/aoagents/agent-orchestrator/backend/internal/adapters/agent/kiro"
"github.com/aoagents/agent-orchestrator/backend/internal/adapters/agent/mastracode"
"github.com/aoagents/agent-orchestrator/backend/internal/adapters/agent/memcode"
"github.com/aoagents/agent-orchestrator/backend/internal/adapters/agent/mimocode"
"github.com/aoagents/agent-orchestrator/backend/internal/adapters/agent/muse"
Expand All @@ -48,6 +49,7 @@ var Derivers = map[string]DeriveFunc{
// deriver; the rest share the name-only StandardDeriveActivityState.
"claude-code": claudecode.DeriveActivityState,
"command-code": commandcode.DeriveActivityState,
"mastra-code": mastracode.DeriveActivityState,
"grok": claudecode.DeriveActivityState,
"muse": muse.DeriveActivityState,
"omp": omp.DeriveActivityState,
Expand Down
150 changes: 150 additions & 0 deletions backend/internal/adapters/agent/mastracode/activity.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,150 @@
package mastracode

import (
"errors"
"strings"

"github.com/aoagents/agent-orchestrator/backend/internal/adapters/agent/terminalui"
"github.com/aoagents/agent-orchestrator/backend/internal/domain"
"github.com/aoagents/agent-orchestrator/backend/internal/ports"
)

// ValidateTerminalMessage refuses pending native decisions and user drafts.
func (p *Plugin) ValidateTerminalMessage(output, message string) error {
if err := validateTask(message); err != nil {
return err
}
if !p.ComposerIsEmpty(output) {
return errors.Join(ports.ErrTerminalMessageNotReady, errors.New("mastra-code requires an initialized empty composer; resolve native decisions or submit/clear your draft in the terminal"))
}
return nil
}

// DeriveActivityState maps native callbacks without inferring process exit from
// conversation-end or an interrupt acknowledgement.
func DeriveActivityState(event string, _ []byte) (domain.ActivityState, bool) {
switch event {
case "session-start", "stop":
return domain.ActivityIdle, true
case "user-prompt-submit", "agent-start", "permission-result":
return domain.ActivityActive, true
case "permission-request":
return domain.ActivityWaitingInput, true
default:
return "", false
}
}

// ExitDetectionMode delegates CLI exit ownership to AO's existing supervisor.
func (*Plugin) ExitDetectionMode() ports.AgentExitDetectionMode {
return ports.AgentExitDetectionSupervisor
}

// ContinuouslyDetectTerminalActivity samples current rendered native chrome.
func (*Plugin) ContinuouslyDetectTerminalActivity() bool { return true }

func pendingDecision(output string) bool {
lines := strings.Split(output, "\n")
// The active input/dialog frame is directly above the native footer.
footer := len(lines)
for i := len(lines) - 1; i >= 0; i-- {
if strings.HasPrefix(strings.TrimSpace(lines[i]), "▐") && strings.Contains(lines[i], "▌") {
footer = i
break
}
}
// Native tool approval replaces the input region with an unframed panel.
// Match its complete chrome rather than decision words in transcript text.
title, tool, arguments := false, false, false
for _, line := range lines[max(0, footer-24):footer] {
text := strings.TrimSpace(line)
switch {
case text == "⚠ Tool Approval Required":
title = true
case title && strings.HasPrefix(text, "Tool: "):
tool = true
case tool && text == "Arguments:":
arguments = true
case arguments && strings.HasPrefix(text, "Allow? ") && strings.Contains(text, "Yolo"):
return true
}
}
start := -1
for i := footer - 1; i >= 0; i-- {
if strings.HasPrefix(strings.TrimSpace(lines[i]), "╭─") {
start = i
break
}
}
if start < 0 {
return false
}
for _, line := range lines[start:footer] {
for _, marker := range []string{"Tool Approval Required", "Allow?", "Grant sandbox access", "Enter to select", "Enter select", "Enter to confirm", "Enter to submit", "Enter to add", "Esc to skip", "Esc reject"} {
if strings.Contains(line, marker) {
return true
}
}
}
return false
}

// ComposerIsEmpty requires the native framed composer and model footer. It
// refuses native decisions and ordinary draft content, including wrapped rows.
func (*Plugin) ComposerIsEmpty(output string) bool {
plain := terminalui.PlainTerminalText(output)
if pendingDecision(plain) {
return false
}
lines := strings.Split(plain, "\n")
footer := -1
for i := len(lines) - 1; i >= 0; i-- {
if strings.HasPrefix(strings.TrimSpace(lines[i]), "▐") && strings.Contains(lines[i], "▌") {
footer = i
break
}
}
if footer < 3 {
return false
}
bottom := strings.TrimSpace(lines[footer-1])
if !strings.HasPrefix(bottom, "╰─") || !strings.HasSuffix(bottom, "╯") {
return false
}
for i := footer - 2; i >= 0 && i >= footer-12; i-- {
line := strings.TrimSpace(lines[i])
if strings.HasPrefix(line, "╭─") {
return false
}
if !strings.HasPrefix(line, "│") || !strings.HasSuffix(line, "│") {
return false
}
content := strings.TrimSpace(strings.TrimSuffix(strings.TrimPrefix(line, "│"), "│"))
if strings.HasPrefix(content, "›") {
return strings.TrimSpace(strings.TrimPrefix(content, "›")) == "" && i > 0 && strings.HasPrefix(strings.TrimSpace(lines[i-1]), "╭─")
}
if content != "" {
return false
}
}
return false
}

// DetectTerminalActivity never treats an old ring tail as current UI evidence.
func (p *Plugin) DetectTerminalActivity(output string) (domain.ActivityState, bool) {
plain := terminalui.PlainTerminalText(output)
if pendingDecision(plain) {
return domain.ActivityWaitingInput, true
}
if p.ComposerIsEmpty(output) {
return domain.ActivityIdle, true
}
lines := strings.Split(plain, "\n")
start := max(0, len(lines)-8)
for _, line := range lines[start:] {
if strings.HasPrefix(strings.TrimSpace(line), "│ •") {
return domain.ActivityActive, true
}
}
return "", false
}
123 changes: 123 additions & 0 deletions backend/internal/adapters/agent/mastracode/auth-probe.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,123 @@
// This process emits only an authored verdict. Provider text, keys and native
// account paths remain inside the native SDK boundary.
import { createRequire } from 'node:module';
import { readFileSync, realpathSync } from 'node:fs';
import { dirname, join, resolve, sep } from 'node:path';
import { pathToFileURL } from 'node:url';

for (const method of ['log', 'info', 'warn', 'error', 'debug']) console[method] = () => {};
let status = 'unknown';
let code = 'mastra_sdk_unsupported';
let provider = '';
let httpStatus = 0;
const emit = () => process.stdout.write(JSON.stringify({ status, code, provider, httpStatus }));
function packageRoot(entry) {
const executable = realpathSync(entry);
const candidates = [dirname(executable),
join(dirname(executable), 'node_modules', 'mastracode'),
join(dirname(executable), '..', 'lib', 'node_modules', 'mastracode')];
for (const candidate of candidates) {
let root = resolve(candidate);
for (;;) {
let metadata;
try { metadata = JSON.parse(readFileSync(join(root, 'package.json'), 'utf8')); } catch {}
if (metadata?.name === 'mastracode') {
if (metadata.version !== '0.45.0') throw new Error('unsupported native version');
return root;
}
const parent = dirname(root);
if (root === parent) break;
root = parent;
}
}
throw new Error('native package unavailable');
}
function exportedPackage(req, name, version) {
const metadataPath = req.resolve(name + '/package.json');
const metadata = JSON.parse(readFileSync(metadataPath, 'utf8'));
if (metadata.name !== name || metadata.version !== version) throw new Error('unsupported package');
const root = dirname(metadataPath);
const target = subpath => {
let value = metadata.exports?.[subpath] ?? metadata.exports?.['./*'];
while (value && typeof value === 'object') value = value.import ?? value.default;
if (typeof value !== 'string' || !value.startsWith('./')) throw new Error('unsupported export');
const file = resolve(root, value.replace('*', subpath.slice(2)));
if (!file.startsWith(root + sep)) throw new Error('invalid export');
return pathToFileURL(file).href;
};
return { target, req: createRequire(metadataPath) };
}
try {
const native = packageRoot(process.argv[1]);
process.env.MASTRA_APP_DATA_DIR = process.argv[2];
const sdk = exportedPackage(createRequire(join(native, 'package.json')), '@mastra/code-sdk', '1.11.0');
const core = exportedPackage(sdk.req, '@mastra/core', '1.75.0');
const { AuthStorage } = await import(sdk.target('./auth/storage'));
const settingsModule = await import(sdk.target('./onboarding/settings'));
const { PROVIDER_REGISTRY } = await import(core.target('./llm'));
const storage = new AuthStorage();
const settings = settingsModule.loadSettings();
const envNames = {};
for (const [id, config] of Object.entries(PROVIDER_REGISTRY)) {
envNames[id] = Array.isArray(config.apiKeyEnvVar) ? config.apiKeyEnvVar[0] : config.apiKeyEnvVar;
}
storage.loadStoredApiKeysIntoEnv(envNames);
const custom = settings.customProviders ?? [];
const configured = storage.list().some(id => id.startsWith('apikey:')
? Boolean(storage.getStoredApiKey(id.slice(7))?.trim())
: ['oauth', 'api_key'].includes(storage.get(id)?.type)) ||
Object.values(PROVIDER_REGISTRY).some(config => (Array.isArray(config.apiKeyEnvVar)
? config.apiKeyEnvVar : [config.apiKeyEnvVar]).some(name => name && process.env[name]?.trim())) ||
custom.some(item => item.apiKey?.trim());
if (!configured) { code = 'credential_missing'; }
else {
status = 'configured';
code = 'mastra_model_unselected';
// Match native headless/build startup, including active built-in/custom
// packs and per-pack overrides. Raw modeDefaults can be empty or stale.
// AO replaces inherited MASTRACODE_MODEL_ID per session.
code = 'mastra_sdk_unsupported';
const { listBuiltinModePacks } = await import(sdk.target('./onboarding/packs'));
const defaults = settingsModule.resolveModelDefaults(settings, listBuiltinModePacks());
code = 'mastra_model_unselected';
const modelId = defaults?.build;
if (typeof modelId === 'string' && modelId.includes('/')) {
code = 'provider_unsupported';
const normalized = settingsModule.stripMastraCodeCustomProviderPrefix(modelId, custom);
const selected = normalized.split('/')[0];
provider = /^[a-zA-Z0-9._-]{1,64}$/.test(selected) ? selected : '';
const model = await import(sdk.target('./agents/model'));
const { generateText } = await import(pathToFileURL(sdk.req.resolve('ai')).href);
try {
const result = await generateText({ model: model.resolveModel(modelId), prompt: 'Reply OK.',
maxOutputTokens: 16, maxRetries: 0, abortSignal: AbortSignal.timeout(15000) });
// A bounded reasoning-only response still proves provider access.
// A missing/malformed SDK result does not.
// The native V2 router can retain V3/V4 provider result fields through
// AI SDK 6's compatibility wrapper. Read only their documented values.
const finishReason = typeof result?.finishReason === 'string'
? result.finishReason : result?.finishReason?.unified;
const outputTokens = typeof result?.usage?.outputTokens === 'number'
? result.usage.outputTokens : result?.usage?.outputTokens?.total;
const inference = (typeof result?.text === 'string' && result.text.trim() !== '') ||
(Number.isFinite(outputTokens) && outputTokens > 0);
if (typeof result?.response?.modelId === 'string' && result.response.modelId.trim() &&
result.usage && typeof result.usage === 'object' &&
['stop', 'length', 'content-filter', 'tool-calls', 'other'].includes(finishReason) && inference) {
status = 'authorized'; code = 'provider_accepted';
}
} catch (error) {
// Read only typed status fields, never classify or return raw messages.
const responseStatus = error?.statusCode ?? error?.cause?.statusCode;
httpStatus = Number.isInteger(responseStatus) && responseStatus >= 100 && responseStatus <= 599 ? responseStatus : 0;
const providerCode = error?.data?.error?.code ?? error?.data?.error?.type;
const quota = ['insufficient_quota', 'quota_exceeded', 'billing_hard_limit_reached', 'insufficient_balance'].includes(providerCode);
if (quota || httpStatus === 402) code = 'provider_quota_exhausted';
else if (httpStatus === 401 || httpStatus === 403) {status = 'unauthorized';code = 'provider_rejected';}
else if (httpStatus === 429) code = 'provider_rate_limited';
else code = 'provider_unreachable';
}
}
}
} catch { /* Missing/incompatible SDK stays unknown or configured, never signed out. */ }
emit();
Loading
Loading