fix(bridge): stall-based approval detection + known issues from deep debugging

- IDLE→stall detection: RUNNING+delta=0 for 6 polls (30s)
- lastModifiedTime-based thinking filter (partial)
- ResolveOutstandingSteps confirmed CANCELS steps (removed)
- HandleCascadeUserInteraction always socket hang up (removed)
- VS Code accept commands: silent success, no effect
- Hybrid approval: focus+all commands sequential, no break
- logToFile: console.log backup added
- Known issues: 4 critical findings documented
- better-antigravity reference added for future research
This commit is contained in:
2026-03-08 14:38:41 +09:00
parent 2574ce6f08
commit c97414cd37
23 changed files with 3516 additions and 280 deletions

View File

@@ -0,0 +1,2 @@
custom:
- https://github.com/Kanezal/better-antigravity#support

10
better-antigravity-main/.gitignore vendored Normal file
View File

@@ -0,0 +1,10 @@
GEMINI.md
node_modules/
dist/
out/
.env
*.vsix
*.bak
*.log
.DS_Store
Thumbs.db

View File

@@ -0,0 +1,12 @@
.env
publish-ovsx.mjs
.git/
.gitignore
node_modules/
out/
src/
build.mjs
tsconfig.json
*.bak
*.log
*.map

View File

@@ -0,0 +1,105 @@
# Fixes — Technical Details
Detailed root cause analysis and patch descriptions for each fix in Better Antigravity.
---
## Auto-Run Fix
**Status:** Working
**Affected versions:** 1.107.0+
**Files patched:** `workbench.desktop.main.js`, `jetskiAgent.js`
### The Problem
You set **Settings -> Agent -> Terminal Execution -> "Always Proceed"**, but Antigravity **still asks you to click "Run"** on every single terminal command. Every. Single. Time.
The setting saves correctly, Strict Mode is off -- it just doesn't work.
### Root Cause
Found in the source code: the `run_command` step renderer component has an `onChange` handler that auto-confirms commands when you switch the dropdown to "Always run" **on a specific step**. But there's **no `useEffect` hook** that checks the saved policy at mount time and auto-confirms **new steps**.
In other words: the UI reads your setting, displays the correct dropdown value, but never actually acts on it automatically.
```javascript
// What exists (only fires on dropdown CHANGE):
y = Mt(_ => {
setTerminalAutoExecutionPolicy(_),
_ === EAGER && confirm(true) // <- only when you manually switch
}, [])
// What's MISSING (should fire on component mount):
useEffect(() => {
if (policy === EAGER && !secureMode) confirm(true) // <- auto-confirm new steps
}, [])
```
### How the Patch Works
The patcher uses **structural regex matching** to find the `onChange` handler in the minified source. It matches the code by shape, not by variable names -- so it works even when Antigravity re-minifies on update.
**Step 1: Find the onChange handler**
Pattern: `<callback>=<useCallback>((<arg>)=>{<setFn>(<arg>),<arg>===<ENUM>.EAGER&&<confirm>(!0)},[...])`
This matches the handler structurally:
- An assignment to a variable
- A `useCallback` call
- Arrow function with one argument
- Two expressions: set state + check EAGER and confirm
**Step 2: Extract variable names from context**
From the surrounding 3000 characters, extract:
- `policyVar`: `<var>=<something>?.terminalAutoExecutionPolicy??<ENUM>.OFF`
- `secureVar`: `<var>=<something>?.secureModeEnabled??!1`
- `useEffectFn`: the most frequently used short-named function matching the `fn(()=>{...})` pattern (frequency analysis)
**Step 3: Generate and inject the patch**
```javascript
/*BA:autorun*/<useEffect>(()=>{<policyVar>===<ENUM>.EAGER&&!<secureVar>&&<confirm>(!0)},[])
```
The patch is injected immediately after the `onChange` handler's closing bracket.
### Example Output
```
Antigravity "Always Proceed" Auto-Run Fix
C:\Users\user\AppData\Local\Programs\Antigravity
Version: 1.107.0 (IDE 1.19.5)
[workbench] Found onChange at offset 12362782
callback=Mt, enum=Dhe, confirm=b
policyVar=u
secureVar=d
useEffect=mn (confidence: 30 hits)
[workbench] Patched (+43 bytes)
[jetskiAgent] Found onChange at offset 8388797
callback=ve, enum=rx, confirm=F
policyVar=d
secureVar=f
useEffect=At (confidence: 55 hits)
[jetskiAgent] Patched (+42 bytes)
Done! Restart Antigravity.
```
### Safety
- Original files are saved as `.ba-backup` before patching
- The patch marker `/*BA:autorun*/` prevents double-patching
- Only **adds** code, never removes existing logic
- `--revert` restores the original file from backup
- Async I/O in the extension prevents blocking the Extension Host
### Why two files?
The `run_command` step renderer exists in **two** bundles:
1. `workbench.desktop.main.js` -- the main workbench bundle (~15MB)
2. `jetskiAgent.js` -- the Cascade chat panel webview (~10MB)
Both contain the same bug with slightly different minified variable names. The structural matcher handles both transparently.

View File

@@ -0,0 +1,59 @@
# Legal Notice
## Disclaimer
This project is an unofficial, community-maintained collection of patches for
[Antigravity IDE](https://antigravity.dev). It is **not affiliated with,
endorsed by, or sponsored by Google LLC or any of its subsidiaries.**
## Nature of the Project
Better Antigravity provides **bugfix patches** that restore documented, expected
functionality in Antigravity IDE. Specifically:
- The "Always Proceed" terminal execution policy is documented to auto-execute
commands, but does not function as described. Our patch restores this behavior.
- All patches are non-destructive: they create automatic backups and can be
fully reverted at any time.
- No data is collected, transmitted, or shared with any party.
## Compliance
- This project **does not access** Google's backend servers, APIs, or
authentication systems.
- This project **does not extract** AI models, training data, or proprietary
algorithms.
- This project **does not bypass** security features, licensing, or
usage restrictions.
- All modifications are local to the user's machine and affect only the
client-side UI behavior.
## Interoperability
Where applicable, this project relies on the right to achieve interoperability
as provided by:
- **EU Software Directive** (Directive 2009/24/EC), Article 6
- **UK Copyright, Designs and Patents Act 1988**, Section 50B
- Similar provisions in other jurisdictions
## User Responsibility
Users are responsible for ensuring their use of this software complies with
applicable terms of service and local laws. By using this software, you
acknowledge that:
1. You are applying modifications to software on your own machine at your
own risk.
2. Backups of original files are created automatically and can be restored.
3. This project may stop working after Antigravity updates — in that case,
revert and wait for an updated patch.
## Takedown
If Google or the Antigravity team requests removal of this project, we will
comply promptly. Contact: [open a GitHub issue](https://github.com/Kanezal/better-antigravity/issues).
## License
This project is released under the [GNU Affero General Public License v3.0](LICENSE).

View File

@@ -0,0 +1,644 @@
GNU AFFERO GENERAL PUBLIC LICENSE
Version 3, 19 November 2007
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU Affero General Public License is a free, copyleft license for
software and other kinds of works, specifically designed to ensure
cooperation with the community in the case of network server software.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
our General Public Licenses are intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
Developers that use our General Public Licenses protect your rights
with two steps: (1) assert copyright on the software, and (2) offer
you this License which gives you legal permission to copy, distribute
and/or modify the software.
A secondary benefit of defending all users' freedom is that
improvements made in alternate versions of the program, if they receive
widespread use, become available for other developers to incorporate.
Many developers of free software are heartened and encouraged by the
resulting cooperation. However, in the case of software used on network
servers, this result may fail to come about. The GNU General Public
License permits making a modified version and letting the public access
it on a server without ever releasing its source code to the public.
The GNU Affero General Public License is designed specifically to
ensure that, in such cases, the modified source code becomes available
to the community. It requires the operator of a network server to
provide the source code of the modified version running there to the
users of that server. Therefore, public use of a modified version, on
a publicly accessible server, gives the public access to the source
code of the modified version.
An older license, called the Affero General Public License and
published by Affero, was designed to accomplish similar goals. This is
a different license, not a version of the Affero GPL, but Affero has
released a new version of the Affero GPL which permits relicensing under
this license.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU Affero General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding Source
of the work are being offered to the general public at no charge under
subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied by
the Installation Information. But this requirement does not apply if
neither you nor any third party retains the ability to install modified
object code on the User Product (for example, the work has been
installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in source
code form), and must require no special password or key for unpacking,
reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions; the
above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Remote Network Interaction; Use with the GNU General Public License.
Notwithstanding any other provision of this License, if you modify the
Program, your modified version must prominently offer all users
interacting with it remotely through a computer network (if your version
supports such interaction) an opportunity to receive the Corresponding
Source of your version by providing access to the Corresponding Source
from a network server at no charge, through some standard or customary
means of facilitating copying of software. This Corresponding Source
shall include the Corresponding Source for any work covered by version 3
of the GNU General Public License that is incorporated pursuant to the
following paragraph.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the work with which it is combined will remain governed by version
3 of the GNU General Public License.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU Affero General Public License from time to time. Such new versions
will be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU Affero General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU Affero General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU Affero General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE
OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR
DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR
A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH
HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
Better Antigravity
Copyright (C) 2026 Kanezal
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.

View File

@@ -0,0 +1,209 @@
<div align="center">
# Better Antigravity
**Community-driven fixes and improvements for [Antigravity IDE](https://antigravity.dev)**
[![Open VSX](https://img.shields.io/open-vsx/v/kanezal/better-antigravity)](https://open-vsx.org/extension/kanezal/better-antigravity)
[![npm](https://img.shields.io/npm/v/better-antigravity)](https://www.npmjs.com/package/better-antigravity)
[![License: AGPL-3.0](https://img.shields.io/badge/License-AGPL--3.0-blue.svg)](LICENSE)
[![Antigravity](https://img.shields.io/badge/Antigravity-v1.107.0+-blue.svg)](https://antigravity.dev)
[![Sponsor](https://img.shields.io/badge/Sponsor-Support%20this%20project-ff69b4?logo=githubsponsors&logoColor=white)](https://github.com/Kanezal/better-antigravity#support)
*Antigravity is great. We just make it a little better.*
</div>
---
## What is this?
Better Antigravity is both a **VS Code extension** and an **npm CLI tool** that fixes known bugs and adds quality-of-life features to Antigravity IDE.
| Channel | What it does | Install |
|---------|-------------|---------|
| **Extension** | Auto-applies fixes on startup + chat rename + SDK features | [Open VSX](https://open-vsx.org/extension/kanezal/better-antigravity) |
| **CLI** | Quick one-off patching via `npx` (no extension install needed) | `npx better-antigravity auto-run` |
> [!NOTE]
> The extension includes everything the CLI does, plus extra features powered by the [Antigravity SDK](https://www.npmjs.com/package/antigravity-sdk). If you install the extension, you don't need the CLI.
---
## Install (Extension)
Search for **"Better Antigravity"** in the Extensions panel, or install from [Open VSX](https://open-vsx.org/extension/kanezal/better-antigravity).
Manual install:
```bash
antigravity --install-extension better-antigravity-0.5.0.vsix --force
```
On activation the extension will:
1. **Auto-apply the auto-run fix** (silent, no prompt)
2. **Initialize the SDK** for chat rename and future features
3. **Install the integration script** (prompts for reload on first install, auto-reloads on updates)
4. **Suppress integrity warnings** ("corrupt installation" notification silenced automatically)
---
## Install (CLI only)
If you just want the auto-run fix without installing an extension:
```bash
npx better-antigravity auto-run # apply fix
npx better-antigravity auto-run --check # check status
npx better-antigravity auto-run --revert # revert to original
```
Custom install path (if Antigravity is not in the default location):
```bash
npx better-antigravity auto-run --path "D:\Antigravity"
```
---
## Features
### Auto-Run Fix
**The problem:** You set **Settings -> Agent -> Terminal Execution -> "Always Proceed"**, but Antigravity **still asks you to click "Run"** on every terminal command.
**Root cause:** The `run_command` step renderer has an `onChange` handler that auto-confirms when you switch the dropdown, but there's **no `useEffect`** that checks the saved policy at mount time.
```javascript
// What exists (only fires on dropdown CHANGE):
onChange = useCallback(_ => {
setPolicy(_), _ === EAGER && confirm(true)
}, [])
// What's MISSING (should fire on mount):
useEffect(() => {
if (policy === EAGER && !secureMode) confirm(true)
}, [])
```
**The fix:** Our patcher adds the missing `useEffect`. It uses **structural regex matching** (not hardcoded variable names) so it works across Antigravity versions.
> For the full root cause analysis, pattern matching explanation, and example output, see **[FIXES.md](FIXES.md)**.
### Chat Rename (Extension only)
Rename conversations to custom titles via the [Antigravity SDK](https://www.npmjs.com/package/antigravity-sdk) title proxy. Custom titles override the auto-generated summaries in the sidebar.
### Integrity Check Suppression (Extension only)
When the SDK patches workbench.html, Antigravity shows a sticky "Your installation appears to be corrupt" warning with no dismiss button. As of v0.4.0, the extension automatically updates the checksum in `product.json` after patching so IntegrityService sees `isPure = true`. No warnings on next restart.
Multiple SDK-based extensions are coordinated automatically -- the original checksum is restored only when the last extension uninstalls.
### Status Command (Extension only)
`Ctrl+Shift+P` -> **"Better Antigravity: Show Status"** to see:
- SDK initialization state
- Language Server connection
- Integration script status
- Auto-run fix status per file
---
## Commands
| Command | Description |
|---------|-------------|
| `Better Antigravity: Show Status` | Show extension and fix status |
| `Better Antigravity: Revert Auto-Run Fix` | Restore original files from backup |
---
## Safety
- **Automatic backups** -- original files saved as `.ba-backup` before patching
- **One-command revert** -- CLI `--revert` or extension command
- **Non-destructive** -- patches only add code, never remove existing logic
- **Version-resilient** -- structural regex matching, not hardcoded variable names
- **Async I/O** -- file operations don't block the extension host
---
## Compatibility
| Antigravity Version | Status |
|---------------------|--------|
| 1.107.0 | Tested |
| Other versions | Should work (dynamic pattern matching) |
---
## Project Structure
```
better-antigravity/
├── src/
│ ├── extension.ts # Extension entry point (thin orchestrator)
│ ├── auto-run.ts # Auto-run fix logic (async, no vscode dependency)
│ └── commands.ts # VS Code command handlers
├── fixes/
│ └── auto-run-fix/
│ └── patch.js # Standalone CLI patcher
├── cli.js # npx entry point
├── build.mjs # esbuild config
├── publish-ovsx.mjs # Open VSX publish script
└── package.json # Dual: npm package + VS Code extension
```
---
## Development
```bash
npm install
npm run build # Compile extension
npm run watch # Watch mode
npm run package # Build VSIX -> out/
npm run publish:ovsx # Publish to Open VSX (reads .env)
```
The extension depends on [antigravity-sdk](https://www.npmjs.com/package/antigravity-sdk) from the monorepo sibling directory. The build script aliases it automatically.
---
## Contributing
Found another Antigravity bug? Have a fix? PRs are welcome.
### Adding a new fix:
1. Create a folder under `fixes/` with a descriptive name
2. Include a `patch.js` that supports `--check` and `--revert` flags
3. Use structural pattern matching, not hardcoded variable names
4. Update this README's feature table
---
## Disclaimer
> [!WARNING]
> This project is not affiliated with Google or the Antigravity team. These are community patches and improvements. If Antigravity updates and the patches break, simply revert and re-apply (or wait for an updated patch).
**Always report bugs officially** at [antigravity.google/support](https://antigravity.google/support) -- community patches are temporary solutions, not replacements for official fixes.
---
## ❤️ Support
If you find this project useful and want to support its development, you can send **USDT** to:
| Network | Address |
|---------|---------|
| **TON** | `UQCjVh3C3mZc44GjT2IDsS4pmeOoUgRNxWMcb85NS5Bz_v1d` |
| **TRON (TRC20)** | `TH3JKGjNrSDCsjkkSuneaSMZoJYF7CNTXD` |
---
## License
[AGPL-3.0-or-later](LICENSE)

View File

@@ -0,0 +1,57 @@
import * as esbuild from 'esbuild';
import * as fs from 'fs';
import * as path from 'path';
const isWatch = process.argv.includes('--watch');
/** @type {esbuild.BuildOptions} */
const config = {
entryPoints: ['src/extension.ts'],
bundle: true,
outfile: 'dist/extension.js',
external: ['vscode'],
format: 'cjs',
platform: 'node',
target: 'es2020',
sourcemap: true,
minify: false,
// Resolve antigravity-sdk from monorepo sibling
alias: {
'antigravity-sdk': path.resolve('..', 'antigravity-sdk', 'dist', 'index.js'),
},
};
// Ensure dist/ exists
if (!fs.existsSync('dist')) fs.mkdirSync('dist');
// Copy sql-wasm.wasm AND sql-wasm.js to dist/ (required by antigravity-sdk's StateBridge)
const sqlFiles = ['sql-wasm.wasm', 'sql-wasm.js'];
for (const sqlFile of sqlFiles) {
const searchPaths = [
path.join('node_modules', 'sql.js', 'dist', sqlFile),
path.join('..', 'antigravity-sdk', 'node_modules', 'sql.js', 'dist', sqlFile),
];
let copied = false;
for (const src of searchPaths) {
if (fs.existsSync(src)) {
fs.copyFileSync(src, path.join('dist', sqlFile));
console.log(`Copied ${sqlFile} from ${src}`);
copied = true;
break;
}
}
if (!copied) {
console.error(`ERROR: ${sqlFile} not found. Run "npm install" first.`);
process.exit(1);
}
}
if (isWatch) {
const ctx = await esbuild.context(config);
await ctx.watch();
console.log('Watching...');
} else {
await esbuild.build(config);
console.log('Build complete');
}

View File

@@ -0,0 +1,65 @@
#!/usr/bin/env node
/**
* better-antigravity CLI
* Usage:
* npx better-antigravity — list available fixes
* npx better-antigravity auto-run — apply auto-run fix
* npx better-antigravity auto-run --check — check status
* npx better-antigravity auto-run --revert — revert fix
*/
const path = require('path');
const fs = require('fs');
const fixes = {
'auto-run': {
script: path.join(__dirname, 'fixes', 'auto-run-fix', 'patch.js'),
description: '"Always Proceed" terminal policy doesn\'t auto-execute commands'
}
};
const args = process.argv.slice(2);
const fixName = args[0];
const flags = args.slice(1);
// Header
console.log('');
console.log(' better-antigravity — community fixes for Antigravity IDE');
console.log(' https://github.com/Kanezal/better-antigravity');
console.log('');
if (!fixName || fixName === '--help' || fixName === '-h') {
console.log(' Available fixes:');
console.log('');
for (const [name, fix] of Object.entries(fixes)) {
console.log(` ${name.padEnd(15)} ${fix.description}`);
}
console.log('');
console.log(' Usage:');
console.log(' npx better-antigravity <fix-name> Apply fix');
console.log(' npx better-antigravity <fix-name> --check Check status');
console.log(' npx better-antigravity <fix-name> --revert Revert fix');
console.log(' npx better-antigravity <fix-name> --path <dir> Use custom install path');
console.log('');
console.log(' The tool auto-detects Antigravity in: CWD, PATH, Registry, default locations.');
console.log(' Use --path if auto-detection fails (e.g. custom install on another drive).');
console.log('');
process.exit(0);
}
const fix = fixes[fixName];
if (!fix) {
console.log(` Unknown fix: "${fixName}"`);
console.log(` Available: ${Object.keys(fixes).join(', ')}`);
process.exit(1);
}
if (!fs.existsSync(fix.script)) {
console.log(` Fix script not found: ${fix.script}`);
process.exit(1);
}
// Forward to the fix script with flags
process.argv = [process.argv[0], fix.script, ...flags];
require(fix.script);

View File

@@ -0,0 +1,400 @@
#!/usr/bin/env node
/**
* Antigravity "Always Proceed" Auto-Run Fix
* ==========================================
*
* Fixes a bug where the "Always Proceed" terminal execution policy doesn't
* actually auto-execute commands. Uses regex patterns to find code structures
* regardless of minified variable names — works across versions.
*
* Usage:
* node patch.js - Apply patch
* node patch.js --revert - Restore original files
* node patch.js --check - Check patch status
*
* License: MIT
*/
const fs = require('fs');
const path = require('path');
const os = require('os');
// ─── Installation Detection ─────────────────────────────────────────────────
/**
* Validates that a candidate directory is a real Antigravity installation
* by checking for the workbench main JS file.
*/
function isAntigravityDir(dir) {
if (!dir) return false;
try {
const workbench = path.join(dir, 'resources', 'app', 'out', 'vs', 'workbench', 'workbench.desktop.main.js');
return fs.existsSync(workbench);
} catch { return false; }
}
/**
* Checks if a directory looks like the Antigravity installation root
* (contains Antigravity.exe or antigravity binary).
*/
function looksLikeAntigravityRoot(dir) {
if (!dir) return false;
try {
const exe = process.platform === 'win32' ? 'Antigravity.exe' : 'antigravity';
return fs.existsSync(path.join(dir, exe));
} catch { return false; }
}
/**
* Tries to find Antigravity installation path from Windows Registry.
* InnoSetup writes uninstall info to HKCU or HKLM.
*/
function findFromRegistry() {
if (process.platform !== 'win32') return null;
try {
const { execSync } = require('child_process');
// InnoSetup typically writes to this key; try HKCU first, then HKLM
const regPaths = [
'HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\Antigravity_is1',
'HKLM\\Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\Antigravity_is1',
'HKLM\\Software\\WOW6432Node\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\Antigravity_is1',
];
for (const regPath of regPaths) {
try {
const output = execSync(
`reg query "${regPath}" /v InstallLocation`,
{ encoding: 'utf8', timeout: 3000, stdio: ['pipe', 'pipe', 'pipe'] }
);
const match = output.match(/InstallLocation\s+REG_SZ\s+(.+)/i);
if (match) {
const dir = match[1].trim().replace(/\\$/, '');
if (isAntigravityDir(dir)) return dir;
}
} catch { /* key not found, try next */ }
}
} catch { /* child_process failed */ }
return null;
}
/**
* Tries to find Antigravity by looking at PATH entries for the executable.
*/
function findFromPath() {
try {
const pathDirs = (process.env.PATH || '').split(path.delimiter);
const exe = process.platform === 'win32' ? 'Antigravity.exe' : 'antigravity';
for (const dir of pathDirs) {
if (!dir) continue;
if (fs.existsSync(path.join(dir, exe))) {
// The exe could be in the root or in a bin/ subdirectory
if (isAntigravityDir(dir)) return dir;
const parent = path.dirname(dir);
if (isAntigravityDir(parent)) return parent;
}
}
} catch { /* PATH parsing failed */ }
return null;
}
function findAntigravityPath() {
// 1. Check CWD and its ancestors (user may run from install dir or a subdir)
let dir = process.cwd();
const root = path.parse(dir).root;
while (dir && dir !== root) {
if (looksLikeAntigravityRoot(dir) && isAntigravityDir(dir)) return dir;
dir = path.dirname(dir);
}
// 2. Check PATH
const fromPath = findFromPath();
if (fromPath) return fromPath;
// 3. Check Windows Registry (InnoSetup uninstall keys)
const fromReg = findFromRegistry();
if (fromReg) return fromReg;
// 4. Hardcoded well-known locations
const candidates = [];
if (process.platform === 'win32') {
candidates.push(
path.join(process.env.LOCALAPPDATA || '', 'Programs', 'Antigravity'),
path.join(process.env.PROGRAMFILES || '', 'Antigravity'),
);
} else if (process.platform === 'darwin') {
candidates.push(
'/Applications/Antigravity.app/Contents/Resources',
path.join(os.homedir(), 'Applications', 'Antigravity.app', 'Contents', 'Resources')
);
} else {
candidates.push('/usr/share/antigravity', '/opt/antigravity',
path.join(os.homedir(), '.local', 'share', 'antigravity'));
}
for (const c of candidates) {
if (isAntigravityDir(c)) return c;
}
return null;
}
// ─── Smart Pattern Matching ─────────────────────────────────────────────────
/**
* Finds the onChange handler for terminalAutoExecutionPolicy and extracts
* variable names from context, regardless of minification.
*
* Pattern we're looking for (structure, not exact names):
* <VAR_CONFIRM>=<useCallback>((<ARG>)=>{
* <stepHandler>?.setTerminalAutoExecutionPolicy?.(<ARG>),
* <ARG>===<ENUM>.EAGER&&<CONFIRM_FN>(!0)
* },[...])
*
* From the surrounding context we also extract:
* <POLICY_VAR> = <stepHandler>?.terminalAutoExecutionPolicy ?? <ENUM>.OFF
* <SECURE_VAR> = <stepHandler>?.secureModeEnabled ?? !1
*/
function analyzeFile(content, label) {
// 1. Find the onChange handler: contains setTerminalAutoExecutionPolicy AND .EAGER
// Pattern: VARNAME=CALLBACK(ARG=>{...setTerminalAutoExecutionPolicy...,ARG===ENUM.EAGER&&CONFIRM(!0)},[...])
const onChangeRe = /(\w+)=(\w+)\((\w+)=>\{\w+\?\.setTerminalAutoExecutionPolicy\?\.\(\3\),\3===(\w+)\.EAGER&&(\w+)\(!0\)\},\[[\w,]*\]\)/;
const onChangeMatch = content.match(onChangeRe);
if (!onChangeMatch) {
console.log(` ❌ [${label}] Could not find onChange handler pattern`);
return null;
}
const [fullMatch, assignVar, callbackAlias, argName, enumAlias, confirmFn] = onChangeMatch;
const matchIndex = content.indexOf(fullMatch);
console.log(` 📋 [${label}] Found onChange at offset ${matchIndex}`);
console.log(` callback=${callbackAlias}, enum=${enumAlias}, confirm=${confirmFn}`);
// 2. Find policy variable: VARNAME=HANDLER?.terminalAutoExecutionPolicy??ENUM.OFF
const policyRe = new RegExp(`(\\w+)=\\w+\\?\\.terminalAutoExecutionPolicy\\?\\?${enumAlias}\\.OFF`);
const policyMatch = content.substring(Math.max(0, matchIndex - 2000), matchIndex).match(policyRe);
if (!policyMatch) {
console.log(` ❌ [${label}] Could not find policy variable`);
return null;
}
const policyVar = policyMatch[1];
console.log(` policyVar=${policyVar}`);
// 3. Find secureMode variable: VARNAME=HANDLER?.secureModeEnabled??!1
const secureRe = /(\w+)=\w+\?\.secureModeEnabled\?\?!1/;
const secureMatch = content.substring(Math.max(0, matchIndex - 2000), matchIndex).match(secureRe);
if (!secureMatch) {
console.log(` ❌ [${label}] Could not find secureMode variable`);
return null;
}
const secureVar = secureMatch[1];
console.log(` secureVar=${secureVar}`);
// 4. Find useEffect alias: look for ALIAS(()=>{...},[...]) calls nearby (not useCallback/useMemo)
const nearbyCode = content.substring(Math.max(0, matchIndex - 5000), matchIndex + 5000);
const effectCandidates = {};
const effectRe = /\b(\w{2,3})\(\(\)=>\{[^}]{3,80}\},\[/g;
let m;
while ((m = effectRe.exec(nearbyCode)) !== null) {
const alias = m[1];
if (alias !== callbackAlias && alias !== 'var' && alias !== 'new') {
effectCandidates[alias] = (effectCandidates[alias] || 0) + 1;
}
}
// Also check broader file for common useEffect patterns (with cleanup return)
const cleanupRe = /\b(\w{2,3})\(\(\)=>\{[^}]*return\s*\(\)=>/g;
while ((m = cleanupRe.exec(content)) !== null) {
const alias = m[1];
if (alias !== callbackAlias) {
effectCandidates[alias] = (effectCandidates[alias] || 0) + 5; // higher weight
}
}
// Remove known non-useEffect aliases (useMemo patterns)
// useMemo: alias(()=>EXPRESSION,[deps]) — returns a value, often assigned
// useEffect: alias(()=>{STATEMENTS},[deps]) — no return value
// Pick the most common candidate
let useEffectAlias = null;
let maxCount = 0;
for (const [alias, count] of Object.entries(effectCandidates)) {
if (count > maxCount) {
maxCount = count;
useEffectAlias = alias;
}
}
if (!useEffectAlias) {
console.log(` ❌ [${label}] Could not determine useEffect alias`);
return null;
}
console.log(` useEffect=${useEffectAlias} (confidence: ${maxCount} hits)`);
// 5. Build patch
const patchCode = `_aep=${useEffectAlias}(()=>{${policyVar}===${enumAlias}.EAGER&&!${secureVar}&&${confirmFn}(!0)},[]),`;
return {
target: fullMatch,
replacement: patchCode + fullMatch,
patchMarker: `_aep=${useEffectAlias}(()=>{${policyVar}===${enumAlias}.EAGER`,
label
};
}
// ─── File Operations ────────────────────────────────────────────────────────
function patchFile(filePath, label) {
if (!fs.existsSync(filePath)) {
console.log(` ❌ [${label}] File not found: ${filePath}`);
return false;
}
const content = fs.readFileSync(filePath, 'utf8');
// Check if already patched
if (content.includes('_aep=')) {
const existingPatch = content.match(/_aep=\w+\(\(\)=>\{[^}]+EAGER[^}]+\},\[\]\)/);
if (existingPatch) {
console.log(` ⏭️ [${label}] Already patched`);
return true;
}
}
const analysis = analyzeFile(content, label);
if (!analysis) return false;
// Verify target is unique
const count = content.split(analysis.target).length - 1;
if (count !== 1) {
console.log(` ❌ [${label}] Target found ${count} times (expected 1)`);
return false;
}
// Backup
if (!fs.existsSync(filePath + '.bak')) {
fs.copyFileSync(filePath, filePath + '.bak');
console.log(` 📦 [${label}] Backup created`);
}
// Apply
const patched = content.replace(analysis.target, analysis.replacement);
fs.writeFileSync(filePath, patched, 'utf8');
const diff = fs.statSync(filePath).size - fs.statSync(filePath + '.bak').size;
console.log(` ✅ [${label}] Patched (+${diff} bytes)`);
return true;
}
function revertFile(filePath, label) {
const bak = filePath + '.bak';
if (!fs.existsSync(bak)) {
console.log(` ⏭️ [${label}] No backup, skipping`);
return;
}
fs.copyFileSync(bak, filePath);
console.log(` ✅ [${label}] Restored`);
}
function checkFile(filePath, label) {
if (!fs.existsSync(filePath)) {
console.log(` ❌ [${label}] Not found`);
return false;
}
const content = fs.readFileSync(filePath, 'utf8');
const patched = content.includes('_aep=') && /_aep=\w+\(\(\)=>\{[^}]+EAGER/.test(content);
const hasBak = fs.existsSync(filePath + '.bak');
if (patched) {
console.log(` ✅ [${label}] PATCHED` + (hasBak ? ' (backup exists)' : ''));
} else {
const analysis = analyzeFile(content, label);
if (analysis) {
console.log(` ⬜ [${label}] NOT PATCHED (patchable)`);
} else {
console.log(` ⚠️ [${label}] NOT PATCHED (may be incompatible)`);
}
}
return patched;
}
// ─── Version Info ───────────────────────────────────────────────────────────
function getVersion(basePath) {
try {
const pkg = JSON.parse(fs.readFileSync(path.join(basePath, 'resources', 'app', 'package.json'), 'utf8'));
const product = JSON.parse(fs.readFileSync(path.join(basePath, 'resources', 'app', 'product.json'), 'utf8'));
return `${pkg.version} (IDE ${product.ideVersion})`;
} catch { return 'unknown'; }
}
// ─── Main ───────────────────────────────────────────────────────────────────
function main() {
const args = process.argv.slice(2);
const action = args.includes('--revert') ? 'revert' : args.includes('--check') ? 'check' : 'apply';
// Parse --path flag
let explicitPath = null;
const pathIdx = args.indexOf('--path');
if (pathIdx !== -1 && args[pathIdx + 1]) {
explicitPath = path.resolve(args[pathIdx + 1]);
}
console.log('');
console.log('╔══════════════════════════════════════════════════╗');
console.log('║ Antigravity "Always Proceed" Auto-Run Fix ║');
console.log('╚══════════════════════════════════════════════════╝');
let basePath;
if (explicitPath) {
if (!isAntigravityDir(explicitPath)) {
console.log(`\n\u274C --path "${explicitPath}" does not look like an Antigravity installation.`);
console.log(' Expected to find: resources/app/out/vs/workbench/workbench.desktop.main.js');
process.exit(1);
}
basePath = explicitPath;
} else {
basePath = findAntigravityPath();
}
if (!basePath) {
console.log('\n\u274C Antigravity installation not found!');
console.log('');
console.log(' Try one of:');
console.log(' 1. Run from the Antigravity install directory:');
console.log(' cd "C:\\Path\\To\\Antigravity" && npx better-antigravity auto-run');
console.log(' 2. Specify the path explicitly:');
console.log(' npx better-antigravity auto-run --path "D:\\Antigravity"');
process.exit(1);
}
console.log(`\n📍 ${basePath}`);
console.log(`📦 Version: ${getVersion(basePath)}`);
console.log('');
const files = [
{ path: path.join(basePath, 'resources', 'app', 'out', 'vs', 'workbench', 'workbench.desktop.main.js'), label: 'workbench' },
{ path: path.join(basePath, 'resources', 'app', 'out', 'jetskiAgent', 'main.js'), label: 'jetskiAgent' },
];
switch (action) {
case 'check':
files.forEach(f => checkFile(f.path, f.label));
break;
case 'revert':
files.forEach(f => revertFile(f.path, f.label));
console.log('\n✨ Restored! Restart Antigravity.');
break;
case 'apply':
const ok = files.every(f => patchFile(f.path, f.label));
console.log(ok
? '\n✨ Done! Restart Antigravity.\n💡 Run with --revert to undo.\n⚠ Re-run after Antigravity updates.'
: '\n⚠ Some patches failed.');
break;
}
}
main();

503
better-antigravity-main/package-lock.json generated Normal file
View File

@@ -0,0 +1,503 @@
{
"name": "better-antigravity",
"version": "0.2.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "better-antigravity",
"version": "0.2.0",
"license": "AGPL-3.0-or-later",
"dependencies": {
"antigravity-sdk": "^1.3.0",
"sql.js": "^1.14.0"
},
"bin": {
"better-antigravity": "cli.js"
},
"devDependencies": {
"@types/node": "^20.0.0",
"@types/vscode": "^1.85.0",
"esbuild": "^0.20.0"
},
"engines": {
"node": ">=16.0.0",
"vscode": "^1.85.0"
}
},
"node_modules/@esbuild/aix-ppc64": {
"version": "0.20.2",
"resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.20.2.tgz",
"integrity": "sha512-D+EBOJHXdNZcLJRBkhENNG8Wji2kgc9AZ9KiPr1JuZjsNtyHzrsfLRrY0tk2H2aoFu6RANO1y1iPPUCDYWkb5g==",
"cpu": [
"ppc64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"aix"
],
"engines": {
"node": ">=12"
}
},
"node_modules/@esbuild/android-arm": {
"version": "0.20.2",
"resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.20.2.tgz",
"integrity": "sha512-t98Ra6pw2VaDhqNWO2Oph2LXbz/EJcnLmKLGBJwEwXX/JAN83Fym1rU8l0JUWK6HkIbWONCSSatf4sf2NBRx/w==",
"cpu": [
"arm"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"android"
],
"engines": {
"node": ">=12"
}
},
"node_modules/@esbuild/android-arm64": {
"version": "0.20.2",
"resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.20.2.tgz",
"integrity": "sha512-mRzjLacRtl/tWU0SvD8lUEwb61yP9cqQo6noDZP/O8VkwafSYwZ4yWy24kan8jE/IMERpYncRt2dw438LP3Xmg==",
"cpu": [
"arm64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"android"
],
"engines": {
"node": ">=12"
}
},
"node_modules/@esbuild/android-x64": {
"version": "0.20.2",
"resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.20.2.tgz",
"integrity": "sha512-btzExgV+/lMGDDa194CcUQm53ncxzeBrWJcncOBxuC6ndBkKxnHdFJn86mCIgTELsooUmwUm9FkhSp5HYu00Rg==",
"cpu": [
"x64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"android"
],
"engines": {
"node": ">=12"
}
},
"node_modules/@esbuild/darwin-arm64": {
"version": "0.20.2",
"resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.20.2.tgz",
"integrity": "sha512-4J6IRT+10J3aJH3l1yzEg9y3wkTDgDk7TSDFX+wKFiWjqWp/iCfLIYzGyasx9l0SAFPT1HwSCR+0w/h1ES/MjA==",
"cpu": [
"arm64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"darwin"
],
"engines": {
"node": ">=12"
}
},
"node_modules/@esbuild/darwin-x64": {
"version": "0.20.2",
"resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.20.2.tgz",
"integrity": "sha512-tBcXp9KNphnNH0dfhv8KYkZhjc+H3XBkF5DKtswJblV7KlT9EI2+jeA8DgBjp908WEuYll6pF+UStUCfEpdysA==",
"cpu": [
"x64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"darwin"
],
"engines": {
"node": ">=12"
}
},
"node_modules/@esbuild/freebsd-arm64": {
"version": "0.20.2",
"resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.20.2.tgz",
"integrity": "sha512-d3qI41G4SuLiCGCFGUrKsSeTXyWG6yem1KcGZVS+3FYlYhtNoNgYrWcvkOoaqMhwXSMrZRl69ArHsGJ9mYdbbw==",
"cpu": [
"arm64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"freebsd"
],
"engines": {
"node": ">=12"
}
},
"node_modules/@esbuild/freebsd-x64": {
"version": "0.20.2",
"resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.20.2.tgz",
"integrity": "sha512-d+DipyvHRuqEeM5zDivKV1KuXn9WeRX6vqSqIDgwIfPQtwMP4jaDsQsDncjTDDsExT4lR/91OLjRo8bmC1e+Cw==",
"cpu": [
"x64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"freebsd"
],
"engines": {
"node": ">=12"
}
},
"node_modules/@esbuild/linux-arm": {
"version": "0.20.2",
"resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.20.2.tgz",
"integrity": "sha512-VhLPeR8HTMPccbuWWcEUD1Az68TqaTYyj6nfE4QByZIQEQVWBB8vup8PpR7y1QHL3CpcF6xd5WVBU/+SBEvGTg==",
"cpu": [
"arm"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=12"
}
},
"node_modules/@esbuild/linux-arm64": {
"version": "0.20.2",
"resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.20.2.tgz",
"integrity": "sha512-9pb6rBjGvTFNira2FLIWqDk/uaf42sSyLE8j1rnUpuzsODBq7FvpwHYZxQ/It/8b+QOS1RYfqgGFNLRI+qlq2A==",
"cpu": [
"arm64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=12"
}
},
"node_modules/@esbuild/linux-ia32": {
"version": "0.20.2",
"resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.20.2.tgz",
"integrity": "sha512-o10utieEkNPFDZFQm9CoP7Tvb33UutoJqg3qKf1PWVeeJhJw0Q347PxMvBgVVFgouYLGIhFYG0UGdBumROyiig==",
"cpu": [
"ia32"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=12"
}
},
"node_modules/@esbuild/linux-loong64": {
"version": "0.20.2",
"resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.20.2.tgz",
"integrity": "sha512-PR7sp6R/UC4CFVomVINKJ80pMFlfDfMQMYynX7t1tNTeivQ6XdX5r2XovMmha/VjR1YN/HgHWsVcTRIMkymrgQ==",
"cpu": [
"loong64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=12"
}
},
"node_modules/@esbuild/linux-mips64el": {
"version": "0.20.2",
"resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.20.2.tgz",
"integrity": "sha512-4BlTqeutE/KnOiTG5Y6Sb/Hw6hsBOZapOVF6njAESHInhlQAghVVZL1ZpIctBOoTFbQyGW+LsVYZ8lSSB3wkjA==",
"cpu": [
"mips64el"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=12"
}
},
"node_modules/@esbuild/linux-ppc64": {
"version": "0.20.2",
"resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.20.2.tgz",
"integrity": "sha512-rD3KsaDprDcfajSKdn25ooz5J5/fWBylaaXkuotBDGnMnDP1Uv5DLAN/45qfnf3JDYyJv/ytGHQaziHUdyzaAg==",
"cpu": [
"ppc64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=12"
}
},
"node_modules/@esbuild/linux-riscv64": {
"version": "0.20.2",
"resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.20.2.tgz",
"integrity": "sha512-snwmBKacKmwTMmhLlz/3aH1Q9T8v45bKYGE3j26TsaOVtjIag4wLfWSiZykXzXuE1kbCE+zJRmwp+ZbIHinnVg==",
"cpu": [
"riscv64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=12"
}
},
"node_modules/@esbuild/linux-s390x": {
"version": "0.20.2",
"resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.20.2.tgz",
"integrity": "sha512-wcWISOobRWNm3cezm5HOZcYz1sKoHLd8VL1dl309DiixxVFoFe/o8HnwuIwn6sXre88Nwj+VwZUvJf4AFxkyrQ==",
"cpu": [
"s390x"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=12"
}
},
"node_modules/@esbuild/linux-x64": {
"version": "0.20.2",
"resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.20.2.tgz",
"integrity": "sha512-1MdwI6OOTsfQfek8sLwgyjOXAu+wKhLEoaOLTjbijk6E2WONYpH9ZU2mNtR+lZ2B4uwr+usqGuVfFT9tMtGvGw==",
"cpu": [
"x64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=12"
}
},
"node_modules/@esbuild/netbsd-x64": {
"version": "0.20.2",
"resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.20.2.tgz",
"integrity": "sha512-K8/DhBxcVQkzYc43yJXDSyjlFeHQJBiowJ0uVL6Tor3jGQfSGHNNJcWxNbOI8v5k82prYqzPuwkzHt3J1T1iZQ==",
"cpu": [
"x64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"netbsd"
],
"engines": {
"node": ">=12"
}
},
"node_modules/@esbuild/openbsd-x64": {
"version": "0.20.2",
"resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.20.2.tgz",
"integrity": "sha512-eMpKlV0SThJmmJgiVyN9jTPJ2VBPquf6Kt/nAoo6DgHAoN57K15ZghiHaMvqjCye/uU4X5u3YSMgVBI1h3vKrQ==",
"cpu": [
"x64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"openbsd"
],
"engines": {
"node": ">=12"
}
},
"node_modules/@esbuild/sunos-x64": {
"version": "0.20.2",
"resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.20.2.tgz",
"integrity": "sha512-2UyFtRC6cXLyejf/YEld4Hajo7UHILetzE1vsRcGL3earZEW77JxrFjH4Ez2qaTiEfMgAXxfAZCm1fvM/G/o8w==",
"cpu": [
"x64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"sunos"
],
"engines": {
"node": ">=12"
}
},
"node_modules/@esbuild/win32-arm64": {
"version": "0.20.2",
"resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.20.2.tgz",
"integrity": "sha512-GRibxoawM9ZCnDxnP3usoUDO9vUkpAxIIZ6GQI+IlVmr5kP3zUq+l17xELTHMWTWzjxa2guPNyrpq1GWmPvcGQ==",
"cpu": [
"arm64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"win32"
],
"engines": {
"node": ">=12"
}
},
"node_modules/@esbuild/win32-ia32": {
"version": "0.20.2",
"resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.20.2.tgz",
"integrity": "sha512-HfLOfn9YWmkSKRQqovpnITazdtquEW8/SoHW7pWpuEeguaZI4QnCRW6b+oZTztdBnZOS2hqJ6im/D5cPzBTTlQ==",
"cpu": [
"ia32"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"win32"
],
"engines": {
"node": ">=12"
}
},
"node_modules/@esbuild/win32-x64": {
"version": "0.20.2",
"resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.20.2.tgz",
"integrity": "sha512-N49X4lJX27+l9jbLKSqZ6bKNjzQvHaT8IIFUy+YIqmXQdjYCToGWwOItDrfby14c78aDd5NHQl29xingXfCdLQ==",
"cpu": [
"x64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"win32"
],
"engines": {
"node": ">=12"
}
},
"node_modules/@types/node": {
"version": "20.19.35",
"resolved": "https://registry.npmjs.org/@types/node/-/node-20.19.35.tgz",
"integrity": "sha512-Uarfe6J91b9HAUXxjvSOdiO2UPOKLm07Q1oh0JHxoZ1y8HoqxDAu3gVrsrOHeiio0kSsoVBt4wFrKOm0dKxVPQ==",
"dev": true,
"license": "MIT",
"dependencies": {
"undici-types": "~6.21.0"
}
},
"node_modules/@types/vscode": {
"version": "1.109.0",
"resolved": "https://registry.npmjs.org/@types/vscode/-/vscode-1.109.0.tgz",
"integrity": "sha512-0Pf95rnwEIwDbmXGC08r0B4TQhAbsHQ5UyTIgVgoieDe4cOnf92usuR5dEczb6bTKEp7ziZH4TV1TRGPPCExtw==",
"license": "MIT"
},
"node_modules/antigravity-sdk": {
"version": "1.3.0",
"resolved": "https://registry.npmjs.org/antigravity-sdk/-/antigravity-sdk-1.3.0.tgz",
"integrity": "sha512-AonqXNmtnkYYib/pSCcDlxnVxLsNIafIbBQxwTV0zHt6RZBjG8ejknkJAhd8hRyilMefMTOE28oPzTblby2K2A==",
"license": "AGPL-3.0-or-later",
"dependencies": {
"sql.js": "^1.14.0"
},
"engines": {
"node": ">=16.0.0"
},
"peerDependencies": {
"@types/vscode": "^1.85.0"
}
},
"node_modules/esbuild": {
"version": "0.20.2",
"resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.20.2.tgz",
"integrity": "sha512-WdOOppmUNU+IbZ0PaDiTst80zjnrOkyJNHoKupIcVyU8Lvla3Ugx94VzkQ32Ijqd7UhHJy75gNWDMUekcrSJ6g==",
"dev": true,
"hasInstallScript": true,
"license": "MIT",
"bin": {
"esbuild": "bin/esbuild"
},
"engines": {
"node": ">=12"
},
"optionalDependencies": {
"@esbuild/aix-ppc64": "0.20.2",
"@esbuild/android-arm": "0.20.2",
"@esbuild/android-arm64": "0.20.2",
"@esbuild/android-x64": "0.20.2",
"@esbuild/darwin-arm64": "0.20.2",
"@esbuild/darwin-x64": "0.20.2",
"@esbuild/freebsd-arm64": "0.20.2",
"@esbuild/freebsd-x64": "0.20.2",
"@esbuild/linux-arm": "0.20.2",
"@esbuild/linux-arm64": "0.20.2",
"@esbuild/linux-ia32": "0.20.2",
"@esbuild/linux-loong64": "0.20.2",
"@esbuild/linux-mips64el": "0.20.2",
"@esbuild/linux-ppc64": "0.20.2",
"@esbuild/linux-riscv64": "0.20.2",
"@esbuild/linux-s390x": "0.20.2",
"@esbuild/linux-x64": "0.20.2",
"@esbuild/netbsd-x64": "0.20.2",
"@esbuild/openbsd-x64": "0.20.2",
"@esbuild/sunos-x64": "0.20.2",
"@esbuild/win32-arm64": "0.20.2",
"@esbuild/win32-ia32": "0.20.2",
"@esbuild/win32-x64": "0.20.2"
}
},
"node_modules/sql.js": {
"version": "1.14.0",
"resolved": "https://registry.npmjs.org/sql.js/-/sql.js-1.14.0.tgz",
"integrity": "sha512-NXYh+kFqLiYRCNAaHD0PcbjFgXyjuolEKLMk5vRt2DgPENtF1kkNzzMlg42dUk5wIsH8MhUzsRhaUxIisoSlZQ==",
"license": "MIT"
},
"node_modules/undici-types": {
"version": "6.21.0",
"resolved": "https://registry.npmjs.org/undici-types/-/undici-types-6.21.0.tgz",
"integrity": "sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ==",
"dev": true,
"license": "MIT"
}
}
}

View File

@@ -0,0 +1,94 @@
{
"name": "better-antigravity",
"displayName": "Better Antigravity",
"description": "Community-driven fixes and improvements for Antigravity IDE — auto-run fix, chat rename, and more",
"version": "0.6.0",
"publisher": "kanezal",
"icon": "static/BA-background.png",
"galleryBanner": {
"color": "#1a1a1a",
"theme": "dark"
},
"markdown": "github",
"badges": [
{
"url": "https://img.shields.io/npm/v/better-antigravity",
"href": "https://www.npmjs.com/package/better-antigravity",
"description": "npm version"
},
{
"url": "https://img.shields.io/badge/License-AGPL--3.0-blue.svg",
"href": "https://github.com/Kanezal/better-antigravity/blob/main/LICENSE",
"description": "License: AGPL-3.0"
},
{
"url": "https://img.shields.io/badge/Antigravity-v1.107.0+-blue.svg",
"href": "https://antigravity.dev",
"description": "Antigravity compatibility"
}
],
"engines": {
"vscode": "^1.85.0",
"node": ">=16.0.0"
},
"categories": [
"Other"
],
"activationEvents": [
"onStartupFinished"
],
"main": "./dist/extension.js",
"bin": {
"better-antigravity": "cli.js"
},
"contributes": {
"commands": [
{
"command": "better-antigravity.status",
"title": "Better Antigravity: Show Status"
},
{
"command": "better-antigravity.revertAutoRun",
"title": "Better Antigravity: Revert Auto-Run Fix"
}
]
},
"scripts": {
"build": "node build.mjs",
"watch": "node build.mjs --watch",
"prepackage": "node -e \"require('fs').mkdirSync('out',{recursive:true})\"",
"package": "npm run prepackage && npx @vscode/vsce package --no-dependencies --out out/better-antigravity.vsix",
"publish:ovsx": "node publish-ovsx.mjs",
"fix:auto-run": "node fixes/auto-run-fix/patch.js",
"fix:auto-run:check": "node fixes/auto-run-fix/patch.js --check",
"fix:auto-run:revert": "node fixes/auto-run-fix/patch.js --revert"
},
"repository": {
"type": "git",
"url": "https://github.com/Kanezal/better-antigravity"
},
"homepage": "https://github.com/Kanezal/better-antigravity#readme",
"bugs": {
"url": "https://github.com/Kanezal/better-antigravity/issues"
},
"author": "Kanezal",
"license": "AGPL-3.0-or-later",
"keywords": [
"antigravity",
"antigravity-ide",
"google-antigravity",
"fix",
"auto-run",
"rename-chat",
"community"
],
"devDependencies": {
"@types/node": "^20.0.0",
"@types/vscode": "^1.85.0",
"esbuild": "^0.20.0"
},
"dependencies": {
"antigravity-sdk": "^1.5.0",
"sql.js": "^1.14.0"
}
}

View File

@@ -0,0 +1,44 @@
#!/usr/bin/env node
/**
* Publish to Open VSX using token from .env
*
* Usage:
* node publish-ovsx.mjs — publish VSIX
* node publish-ovsx.mjs create-namespace — create publisher namespace (first time only)
*/
import { readFileSync } from 'fs';
import { execSync } from 'child_process';
import { createRequire } from 'module';
const require = createRequire(import.meta.url);
const pkg = require('./package.json');
const cmd = process.argv[2] || 'publish';
// Read token from .env
let pat;
try {
const env = readFileSync('.env', 'utf8');
const match = env.match(/OVSX_PAT=(.+)/);
if (!match) throw new Error('OVSX_PAT not found in .env');
pat = match[1].trim();
} catch (err) {
console.error('ERROR: Could not read .env file. Create .env with OVSX_PAT=<token>');
process.exit(1);
}
try {
if (cmd === 'create-namespace') {
console.log(`Creating namespace "${pkg.publisher}" on Open VSX...`);
execSync(`npx ovsx create-namespace ${pkg.publisher} --pat ${pat}`, { stdio: 'inherit' });
console.log('Namespace created!');
} else {
const vsixFile = `out/better-antigravity.vsix`;
console.log(`Publishing ${vsixFile} to Open VSX...`);
execSync(`npx ovsx publish ${vsixFile} --pat ${pat}`, { stdio: 'inherit' });
console.log('Done!');
}
} catch {
process.exit(1);
}

View File

@@ -0,0 +1,235 @@
/**
* Auto-Run Fix — Patches the "Always Proceed" terminal policy to actually auto-execute.
*
* Uses structural regex matching to find the onChange handler in minified code
* and injects a missing useEffect that auto-confirms commands when policy is EAGER.
*
* Works across AG versions because it matches code STRUCTURE, not variable NAMES.
*
* @module auto-run
*/
import * as path from 'path';
import * as fs from 'fs';
import * as fsp from 'fs/promises';
/** Marker comment to identify our patches */
const PATCH_MARKER = '/*BA:autorun*/';
/**
* Resolve the Antigravity workbench directory.
*/
export function getWorkbenchDir(): string | null {
const appData = process.env.LOCALAPPDATA || '';
const dir = path.join(
appData,
'Programs', 'Antigravity', 'resources', 'app', 'out',
'vs', 'code', 'electron-browser', 'workbench',
);
return fs.existsSync(dir) ? dir : null;
}
/**
* Target files that need the auto-run patch.
*/
export function getTargetFiles(workbenchDir: string): Array<{ path: string; label: string }> {
return [
{ path: path.join(workbenchDir, 'workbench.desktop.main.js'), label: 'workbench' },
{ path: path.join(workbenchDir, 'jetskiAgent.js'), label: 'jetskiAgent' },
].filter(f => fs.existsSync(f.path));
}
/**
* Check if a file already has the auto-run patch applied.
*/
export async function isPatched(filePath: string): Promise<boolean> {
try {
// Read only first 50 bytes of the marker area via a small buffer scan
// The marker is injected mid-file, so we must read the full file.
// Use async to avoid blocking extension host.
const content = await fsp.readFile(filePath, 'utf8');
return content.includes(PATCH_MARKER);
} catch {
return false;
}
}
/**
* Analyze a file to find the onChange handler and extract variable names.
*
* Returns null if pattern not found (file may already be fixed by AG update).
*/
function analyzeFile(content: string): AnalysisResult | null {
// Find onChange handler for terminalAutoExecutionPolicy
// Pattern: <callback>=<useCallback>((<arg>)=>{<setFn>(<arg>),<arg>===<ENUM>.EAGER&&<confirm>(true)},[...])
const onChangeRegex = /(\w+)=(\w+)\((\(\w+\))=>\{(\w+)\(\w+\),\w+===(\w+)\.EAGER&&(\w+)\(!0\)\},\[/g;
const match = onChangeRegex.exec(content);
if (!match) return null;
const [fullMatch, , , , , enumName, confirmFn] = match;
const insertPos = match.index + fullMatch.length;
// Extract context variables from surrounding code
const contextStart = Math.max(0, match.index - 3000);
const contextEnd = Math.min(content.length, match.index + 3000);
const context = content.substring(contextStart, contextEnd);
// policyVar: <var>=<something>?.terminalAutoExecutionPolicy??<ENUM>.OFF
const policyMatch = /(\w+)=\w+\?\.terminalAutoExecutionPolicy\?\?(\w+)\.OFF/.exec(context);
// secureVar: <var>=<something>?.secureModeEnabled??!1
const secureMatch = /(\w+)=\w+\?\.secureModeEnabled\?\?!1/.exec(context);
if (!policyMatch || !secureMatch) return null;
const policyVar = policyMatch[1];
const secureVar = secureMatch[1];
// Find useEffect — most frequently used short-named function in the scope
const useEffectFn = findUseEffect(context, [confirmFn]);
if (!useEffectFn) return null;
// Find insertion point: after the useCallback closing
const afterOnChange = content.indexOf('])', insertPos);
if (afterOnChange === -1) return null;
const insertAt = content.indexOf(';', afterOnChange);
if (insertAt === -1) return null;
return {
enumName,
confirmFn,
policyVar,
secureVar,
useEffectFn,
insertAt: insertAt + 1,
};
}
/**
* Find the useEffect function name by frequency analysis.
*/
function findUseEffect(context: string, exclude: string[]): string | null {
const candidates: Record<string, number> = {};
const regex = /(\w{1,3})\(\(\)=>\{/g;
let m;
while ((m = regex.exec(context)) !== null) {
const fn = m[1];
if (fn.length <= 3 && !exclude.includes(fn)) {
candidates[fn] = (candidates[fn] || 0) + 1;
}
}
let best = '';
let maxCount = 0;
for (const [fn, count] of Object.entries(candidates)) {
if (count > maxCount) {
best = fn;
maxCount = count;
}
}
return best || null;
}
interface AnalysisResult {
enumName: string;
confirmFn: string;
policyVar: string;
secureVar: string;
useEffectFn: string;
insertAt: number;
}
/**
* Apply the auto-run patch to a single file.
*
* @returns Patch status message
*/
export async function patchFile(filePath: string, label: string): Promise<PatchResult> {
try {
let content = await fsp.readFile(filePath, 'utf8');
if (content.includes(PATCH_MARKER)) {
return { success: true, label, status: 'already-patched' };
}
const analysis = analyzeFile(content);
if (!analysis) {
return { success: false, label, status: 'pattern-not-found' };
}
const { enumName, confirmFn, policyVar, secureVar, useEffectFn, insertAt } = analysis;
// Build the patch
const patch = `${PATCH_MARKER}${useEffectFn}(()=>{${policyVar}===${enumName}.EAGER&&!${secureVar}&&${confirmFn}(!0)},[])`;
// Create backup (only if one doesn't exist)
const backup = filePath + '.ba-backup';
try { await fsp.access(backup); } catch {
await fsp.copyFile(filePath, backup);
}
// Insert
content = content.substring(0, insertAt) + patch + content.substring(insertAt);
await fsp.writeFile(filePath, content, 'utf8');
return { success: true, label, status: 'patched', bytesAdded: patch.length };
} catch (err: any) {
return { success: false, label, status: 'error', error: err.message };
}
}
/**
* Revert the auto-run patch on a single file.
*/
export function revertFile(filePath: string, label: string): PatchResult {
const backup = filePath + '.ba-backup';
if (!fs.existsSync(backup)) {
return { success: false, label, status: 'no-backup' };
}
try {
fs.copyFileSync(backup, filePath);
fs.unlinkSync(backup);
return { success: true, label, status: 'reverted' };
} catch (err: any) {
return { success: false, label, status: 'error', error: err.message };
}
}
export interface PatchResult {
success: boolean;
label: string;
status: 'patched' | 'already-patched' | 'pattern-not-found' | 'reverted' | 'no-backup' | 'error';
bytesAdded?: number;
error?: string;
}
/**
* Auto-apply the fix to all target files.
*
* @returns Array of results for each file
*/
export async function autoApply(): Promise<PatchResult[]> {
const dir = getWorkbenchDir();
if (!dir) return [];
const files = getTargetFiles(dir);
return Promise.all(files.map(f => patchFile(f.path, f.label)));
}
/**
* Revert all target files from backups.
*
* @returns Number of files reverted
*/
export function revertAll(): PatchResult[] {
const dir = getWorkbenchDir();
if (!dir) return [];
const files = getTargetFiles(dir);
return files.map(f => revertFile(f.path, f.label));
}

View File

@@ -0,0 +1,81 @@
/**
* Better Antigravity — VS Code command handlers.
*
* Each exported function is a command handler registered in extension.ts.
*
* @module commands
*/
import * as vscode from 'vscode';
import * as path from 'path';
import * as fsp from 'fs/promises';
import { AntigravitySDK } from 'antigravity-sdk';
import { getWorkbenchDir, getTargetFiles, isPatched, revertAll } from './auto-run';
/**
* Show extension status in the output channel.
*/
export async function status(sdk: AntigravitySDK | null, output: vscode.OutputChannel): Promise<void> {
const lines = [
'=== Better Antigravity ===',
'',
`SDK: ${sdk?.isInitialized ? `v${sdk.version}` : 'not initialized'}`,
`LS: ${sdk?.ls?.isReady ? `port ${sdk.ls.port}` : 'not ready'}`,
`UI: ${sdk?.integration.isInstalled() ? 'installed' : 'not installed'}`,
`Titles: ${sdk?.integration.titles.count ?? 0} custom`,
];
const dir = getWorkbenchDir();
if (dir) {
const files = getTargetFiles(dir);
for (const f of files) {
const patched = await isPatched(f.path);
lines.push(`AutoRun: ${f.label} = ${patched ? 'fixed' : 'not fixed'}`);
}
} else {
lines.push('AutoRun: workbench directory not found');
}
output.appendLine(lines.join('\n'));
output.show(true);
}
/**
* Revert the auto-run fix and prompt for reload.
*
* Also clears V8 Code Cache to prevent stale cached patched code
* from being loaded by Electron (which causes grey screen).
*/
export async function revertAutoRun(): Promise<void> {
const dir = getWorkbenchDir();
if (!dir) {
vscode.window.showErrorMessage('Workbench directory not found.');
return;
}
const results = revertAll();
const reverted = results.filter(r => r.status === 'reverted').length;
if (reverted > 0) {
// Clear V8 Code Cache — stale cache after revert causes grey screen
const appData = process.env.APPDATA || '';
const cacheDirs = [
path.join(appData, 'Antigravity', 'CachedData'),
path.join(appData, 'Antigravity', 'GPUCache'),
path.join(appData, 'Antigravity', 'Code Cache'),
];
for (const d of cacheDirs) {
try { await fsp.rm(d, { recursive: true, force: true }); } catch { /* may not exist */ }
}
const action = await vscode.window.showInformationMessage(
`Auto-run fix reverted (${reverted} file(s)). Caches cleared. Reload to apply.`,
'Reload Now',
);
if (action === 'Reload Now') {
vscode.commands.executeCommand('workbench.action.reloadWindow');
}
} else {
vscode.window.showInformationMessage('No backups found. Nothing to revert.');
}
}

View File

@@ -0,0 +1,72 @@
/**
* Better Antigravity — Extension entry point.
*
* Thin orchestrator: wires up modules, no business logic here.
*
* @module extension
*/
import * as vscode from 'vscode';
import { AntigravitySDK } from 'antigravity-sdk';
import { autoApply } from './auto-run';
import { status, revertAutoRun } from './commands';
let sdk: AntigravitySDK | null = null;
let output: vscode.OutputChannel;
function log(msg: string): void {
const ts = new Date().toISOString().substring(11, 19);
output?.appendLine(`[${ts}] ${msg}`);
}
export async function activate(context: vscode.ExtensionContext) {
output = vscode.window.createOutputChannel('Better Antigravity');
context.subscriptions.push(output);
log('Activating...');
// ── Commands ──────────────────────────────────────────────────────
context.subscriptions.push(
vscode.commands.registerCommand('better-antigravity.status', () => status(sdk, output)),
vscode.commands.registerCommand('better-antigravity.revertAutoRun', revertAutoRun),
);
// ── Auto-Run Fix (async, non-blocking, no prompt) ─────────────────
autoApply().then(fixResults => {
for (const r of fixResults) {
log(`[auto-run] ${r.label}: ${r.status}${r.bytesAdded ? ` (+${r.bytesAdded}b)` : ''}${r.error ? ` -- ${r.error}` : ''}`);
}
});
// ── SDK Init ─────────────────────────────────────────────────────
try {
sdk = new AntigravitySDK(context);
await sdk.initialize();
log(`SDK v${sdk.version} initialized`);
// Title proxy for chat rename
sdk.integration.enableTitleProxy();
// Seamless install (handles first-time prompt + auto-reload on update)
await sdk.integration.installSeamless(
(cmd) => vscode.commands.executeCommand(cmd),
(msg, ...items) => vscode.window.showInformationMessage(msg, ...items),
);
// Heartbeat (keeps renderer script alive)
const hbTimer = setInterval(() => sdk?.integration.signalActive(), 30_000);
context.subscriptions.push({ dispose: () => clearInterval(hbTimer) });
// Auto-repair (re-patch after AG updates)
sdk.integration.enableAutoRepair();
log('Active');
} catch (err: any) {
log(`SDK init failed: ${err.message}`);
log('Running in degraded mode (auto-run fix only)');
}
}
export function deactivate() {
sdk?.dispose();
sdk = null;
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 16 KiB

View File

@@ -0,0 +1,26 @@
{
"compilerOptions": {
"target": "ES2020",
"module": "commonjs",
"lib": [
"ES2020"
],
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true,
"rootDir": "src",
"outDir": "dist",
"declaration": false,
"sourceMap": true,
"resolveJsonModule": true
},
"include": [
"src/**/*.ts"
],
"exclude": [
"node_modules",
"dist",
"fixes"
]
}

View File

@@ -13,3 +13,4 @@
| 9 | 07:50 | SDK EventMonitor 제거 — ERR_CONNECTION_REFUSED 원인 차단 (-404 lines) | `f6ae9c8` | ✅ | | 9 | 07:50 | SDK EventMonitor 제거 — ERR_CONNECTION_REFUSED 원인 차단 (-404 lines) | `f6ae9c8` | ✅ |
| 10 | 08:00 | GetCascadeTrajectorySteps 완전 제거 + stall-based WAITING 감지 | `9b9c9c7` | ✅ | | 10 | 08:00 | GetCascadeTrajectorySteps 완전 제거 + stall-based WAITING 감지 | `9b9c9c7` | ✅ |
| 11 | 08:10 | Stall 감지 calibration + VS Code 명령어 기반 승인 핸들러 | `f1f9a0b` | 🔧 | | 11 | 08:10 | Stall 감지 calibration + VS Code 명령어 기반 승인 핸들러 | `f1f9a0b` | 🔧 |
| 12 | 11:30~14:35 | 승인 로직 정밀 디버깅: IDLE→stall 전환, lastModifiedTime 구분, RPC/Commands 전수 테스트, ResolveOutstandingSteps cancel 발견 | - | 🔧 |

View File

@@ -0,0 +1,14 @@
# Discord Bridge 승인 로직 정밀 디버깅
- **시간**: 2026-03-08 11:30~14:35
## 결정 사항
- IDLE 기반 감지 → stall 기반 (RUNNING+delta=0) 전환
- `ResolveOutstandingSteps` → step cancel 발견 → 제거
- VS Code accept commands → 무효과 (webview focus 의존) → OS 레벨 필요
## 미완료
- Accept 프로그래밍: OS 레벨 UI Automation 접근 필요
- Thinking/생성 중 false stall: 추가 discriminator 필요

View File

@@ -53,14 +53,18 @@ const os = __importStar(require("os"));
const cp = __importStar(require("child_process")); const cp = __importStar(require("child_process"));
// ─── File-based logging (AI can read directly) ─── // ─── File-based logging (AI can read directly) ───
function logToFile(msg) { function logToFile(msg) {
const ts = new Date().toISOString().replace('T', ' ').substring(0, 19);
const line = `${ts} ${msg}`;
console.log(`Gravity Bridge: ${msg}`);
try { try {
if (!bridgePath) if (!bridgePath)
return; return;
const logFile = path.join(bridgePath, 'extension.log'); const logFile = path.join(bridgePath, 'extension.log');
const ts = new Date().toISOString().replace('T', ' ').substring(0, 19); fs.appendFileSync(logFile, line + '\n', 'utf-8');
fs.appendFileSync(logFile, `${ts} ${msg}\n`, 'utf-8'); }
catch (e) {
console.error(`Gravity Bridge LOG WRITE FAIL: ${e.message}`);
} }
catch { }
} }
// antigravity-sdk embedded locally (src/sdk/) // antigravity-sdk embedded locally (src/sdk/)
let AntigravitySDK; let AntigravitySDK;
@@ -229,6 +233,314 @@ async function initSDK(context) {
return false; return false;
} }
} }
// ─── Approval Observer via SDK IntegrationManager ───
async function setupApprovalObserver() {
if (!sdk) {
logToFile('[OBSERVER] no SDK');
return;
}
try {
const integration = sdk.integration;
if (!integration) {
logToFile('[OBSERVER] sdk.integration unavailable');
return;
}
// 1. Start HTTP bridge server in Extension Host
const bridgePort = await startObserverHttpBridge();
if (!bridgePort) {
logToFile('[OBSERVER] HTTP bridge failed');
return;
}
// 2. Register a TOP_BAR button so build() works
try {
integration.register({
id: 'gravity_bridge_status',
point: 'topBar',
icon: '🌉',
tooltip: 'Gravity Bridge Active',
});
}
catch { /* already registered */ }
// 3. Write renderer script with HTTP fetch() approach
const observerJS = generateApprovalObserverScript(bridgePort);
const patcher = integration._patcher;
if (patcher && typeof patcher.getScriptPath === 'function') {
let baseScript = '';
try {
baseScript = integration.build();
}
catch {
baseScript = '';
}
const combinedScript = baseScript + '\n' + observerJS;
const scriptPath = patcher.getScriptPath();
fs.writeFileSync(scriptPath, combinedScript, 'utf8');
logToFile(`[OBSERVER] script written → ${scriptPath} (port=${bridgePort})`);
if (!integration.isInstalled()) {
patcher.install(combinedScript);
logToFile('[OBSERVER] workbench.html patched (needs reload)');
}
// Also patch workbench-jetski-agent.html (Antigravity's actual entry point!)
const scriptDir = path.dirname(scriptPath);
const jetskiHtml = path.join(scriptDir, 'workbench-jetski-agent.html');
const scriptBasename = path.basename(scriptPath);
try {
if (fs.existsSync(jetskiHtml)) {
let html = fs.readFileSync(jetskiHtml, 'utf8');
if (!html.includes(scriptBasename)) {
html = html.replace('</html>', `\n<!-- AG SDK [variet-gravity-bridge] -->\n<script src="./${scriptBasename}"></script>\n<!-- /AG SDK [variet-gravity-bridge] -->\n</html>`);
fs.writeFileSync(jetskiHtml, html, 'utf8');
logToFile('[OBSERVER] workbench-jetski-agent.html PATCHED');
}
else {
logToFile('[OBSERVER] workbench-jetski-agent.html already has script tag');
}
}
}
catch (e) {
logToFile(`[OBSERVER] jetski patch error: ${e.message}`);
}
}
try {
integration.enableAutoRepair();
}
catch { }
setInterval(() => { try {
integration.signalActive();
}
catch { } }, 30_000);
logToFile(`[OBSERVER] setup complete (HTTP bridge on port ${bridgePort})`);
console.log(`Gravity Bridge: ✅ Approval observer installed (port ${bridgePort})`);
}
catch (err) {
logToFile(`[OBSERVER] setup error: ${err.message}`);
}
}
// ─── HTTP Bridge Server (Extension Host → Renderer communication) ───
let observerHttpServer = null;
const pendingResponses = new Map();
function startObserverHttpBridge() {
return new Promise((resolve) => {
try {
const http = require('http');
const server = http.createServer((req, res) => {
// CORS headers for renderer fetch()
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS');
res.setHeader('Access-Control-Allow-Headers', 'Content-Type');
if (req.method === 'OPTIONS') {
res.writeHead(200);
res.end();
return;
}
const url = new URL(req.url, `http://127.0.0.1`);
// POST /pending — renderer reports a detected approval button
if (req.method === 'POST' && url.pathname === '/pending') {
let body = '';
req.on('data', (c) => body += c);
req.on('end', () => {
try {
const data = JSON.parse(body);
const rid = data.request_id || Date.now().toString();
// Write pending file for Discord bot
const pendingDir = path.join(bridgePath, 'pending');
if (!fs.existsSync(pendingDir))
fs.mkdirSync(pendingDir, { recursive: true });
const pending = {
...data,
request_id: rid,
timestamp: Date.now() / 1000,
status: 'pending',
project_name: projectName,
auto_detected: true,
source: 'dom_observer',
};
fs.writeFileSync(path.join(pendingDir, `${rid}.json`), JSON.stringify(pending, null, 2));
logToFile(`[HTTP] pending created: ${rid} cmd="${data.command}" ctx="${(data.description || '').substring(0, 50)}"`);
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ ok: true, request_id: rid }));
}
catch (e) {
logToFile(`[HTTP] pending error: ${e.message}`);
res.writeHead(400);
res.end(JSON.stringify({ error: e.message }));
}
});
return;
}
// GET /response/:rid — renderer polls for Discord approval
if (req.method === 'GET' && url.pathname.startsWith('/response/')) {
const rid = url.pathname.split('/')[2];
const respFile = path.join(bridgePath, 'response', `${rid}.json`);
if (fs.existsSync(respFile)) {
try {
const data = JSON.parse(fs.readFileSync(respFile, 'utf8'));
fs.unlinkSync(respFile);
logToFile(`[HTTP] response sent: ${rid} approved=${data.approved}`);
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify(data));
}
catch {
res.writeHead(200);
res.end(JSON.stringify({ waiting: true }));
}
}
else {
res.writeHead(200);
res.end(JSON.stringify({ waiting: true }));
}
return;
}
// GET /ping — health check
if (url.pathname === '/ping') {
res.writeHead(200);
res.end('pong');
return;
}
res.writeHead(404);
res.end('not found');
});
// Listen on random port
server.listen(0, '127.0.0.1', () => {
const port = server.address().port;
observerHttpServer = server;
logToFile(`[HTTP] bridge server started on port ${port}`);
// Write port to workbench dir so renderer can read it via XHR
const patcher = sdk.integration?._patcher;
if (patcher && typeof patcher.getWorkbenchDir === 'function') {
const portFile = path.join(patcher.getWorkbenchDir(), 'ag-bridge-port');
fs.writeFileSync(portFile, port.toString(), 'utf8');
logToFile(`[HTTP] port written → ${portFile}`);
}
resolve(port);
});
server.on('error', (e) => {
logToFile(`[HTTP] server error: ${e.message}`);
resolve(0);
});
}
catch (e) {
logToFile(`[HTTP] server failed: ${e.message}`);
resolve(0);
}
});
}
// ─── Renderer Script (uses fetch() — no Node.js APIs) ───
function generateApprovalObserverScript(_port) {
// Port is NOT hardcoded — renderer reads it dynamically from ag-bridge-port file via XHR
return `
// ── Gravity Bridge: Approval Observer (renderer-side, dynamic port) ──
(function(){
'use strict';
var BASE='',_lastTs=0,_obs=false,_sent={},_ready=false;
function log(m){console.log('[GB Observer] '+m);}
log('Script loaded — discovering bridge port...');
// ── Dynamic Port Discovery (like SDK heartbeat) ──
function discoverPort(cb){
var attempts=0;
var timer=setInterval(function(){
attempts++;
if(attempts>30){clearInterval(timer);log('Port discovery timeout');return;}
try{
var xhr=new XMLHttpRequest();
xhr.open('GET','./ag-bridge-port?t='+Date.now(),false);
xhr.send();
if(xhr.status===200){
var port=parseInt(xhr.responseText.trim(),10);
if(port>0&&port<65536){
clearInterval(timer);
log('Port discovered: '+port);
cb(port);
}
}
}catch(e){}
},2000);
}
discoverPort(function(port){
BASE='http://127.0.0.1:'+port;
// Verify bridge is alive
fetch(BASE+'/ping').then(function(r){return r.text();}).then(function(t){
if(t==='pong'){log('Bridge connected on port '+port);_ready=true;startObserver();}
else log('Bridge ping failed: '+t);
}).catch(function(e){log('Bridge unreachable: '+e.message);});
});
var PATS=[
{sel:'button',re:/^Run$/i,type:'terminal_command'},
{sel:'button',re:/^Accept/i,type:'agent_step'},
{sel:'button',re:/^Allow/i,type:'permission'},
{sel:'button',re:/^Continue$/i,type:'continue'},
];
function ctx(b){
var p=b.closest('[class*="step"]')||b.closest('[class*="action"]')||b.parentElement;
if(!p)return '';
var c=p.querySelector('pre,code,[class*="command"],[class*="terminal"]');
if(c)return(c.textContent||'').trim().substring(0,200);
return(p.textContent||'').replace((b.textContent||''),'').trim().substring(0,200);
}
function scan(){
if(!_ready)return;
var now=Date.now();if(now-_lastTs<1000)return;
var panel=document.querySelector('#jetski-agent-panel,.antigravity-agent-side-panel,[class*="agent-panel"]');
if(!panel)return;
for(var i=0;i<PATS.length;i++){
var pat=PATS[i],btns=panel.querySelectorAll(pat.sel);
for(var j=0;j<btns.length;j++){
var b=btns[j],txt=(b.textContent||'').trim();
if(!pat.re.test(txt)||b.disabled)continue;
var bid=pat.type+'_'+txt+'_'+Math.round(b.getBoundingClientRect().top);
if(_sent[bid])continue;
var desc=ctx(b),rid=now.toString();
_sent[bid]=rid;_lastTs=now;
log('FOUND '+pat.type+': "'+txt+'" → sending to bridge');
(function(rid2,b2,bid2){
fetch(BASE+'/pending',{
method:'POST',
headers:{'Content-Type':'application/json'},
body:JSON.stringify({request_id:rid2,command:txt,description:desc,step_type:pat.type})
}).then(function(r){return r.json();}).then(function(d){
log('Pending created: '+d.request_id);
pollResp(d.request_id,b2,bid2);
}).catch(function(e){log('POST error: '+e.message);delete _sent[bid2];});
})(rid,b,bid);
return;
}
}
}
function pollResp(rid,b,bid){
var n=0,t=setInterval(function(){
n++;if(n>600){clearInterval(t);delete _sent[bid];return;}
fetch(BASE+'/response/'+rid).then(function(r){return r.json();}).then(function(d){
if(d.waiting)return;
clearInterval(t);
if(d.approved){log('APPROVED '+rid+' → clicking');b.click();}
else{
log('REJECTED '+rid);
var p=b.closest('[class*="step"]')||b.parentElement;
if(p){var rb=p.querySelectorAll('button');
for(var k=0;k<rb.length;k++){var rt=(rb[k].textContent||'').trim().toLowerCase();
if(rt==='reject'||rt==='cancel'||rt==='deny'){rb[k].click();break;}}}
}
delete _sent[bid];
}).catch(function(){});
},500);
}
function startObserver(){
if(_obs)return;
new MutationObserver(function(){scan();}).observe(document.body,{childList:true,subtree:true});
setInterval(scan,2000);
_obs=true;log('Observer active — watching for approval buttons');
}
})();
`;
}
// Track last seen step per session to avoid re-fetching // Track last seen step per session to avoid re-fetching
const lastSeenStep = new Map(); const lastSeenStep = new Map();
const lastSnapshotText = new Map(); const lastSnapshotText = new Map();
@@ -287,12 +599,22 @@ function setupMonitor() {
let lastNotifyStepIndex = -1; let lastNotifyStepIndex = -1;
let lastTaskStepIndex = -1; let lastTaskStepIndex = -1;
let lastPendingStepIndex = -1; // dedup: don't re-create pending for same step let lastPendingStepIndex = -1; // dedup: don't re-create pending for same step
let consecutiveIdleCount = 0; // debounce: require N consecutive stall polls
let lastPendingTime = 0; // cooldown: minimum gap between pendings
let sawRunningAfterPending = true; // gate: must see delta>0 before next pending
let lastModTime = ''; // track lastModifiedTime to distinguish thinking vs approval
setInterval(async () => { setInterval(async () => {
pollCount++; pollCount++;
if (pollCount <= 3 || pollCount % 12 === 0) {
logToFile(`[POLL#${pollCount}] alive`);
}
try { try {
const allTraj = await sdk.ls.rawRPC('GetAllCascadeTrajectories', {}); const allTraj = await sdk.ls.rawRPC('GetAllCascadeTrajectories', {});
if (!allTraj?.trajectorySummaries) if (!allTraj?.trajectorySummaries) {
if (pollCount <= 3)
logToFile('[POLL] no trajectorySummaries');
return; return;
}
let bestSession = null; let bestSession = null;
let bestSessionId = ''; let bestSessionId = '';
let bestModTime = ''; let bestModTime = '';
@@ -326,129 +648,72 @@ function setupMonitor() {
if (delta > 0) { if (delta > 0) {
console.log(`Gravity Bridge: [POLL#${pollCount}] +${delta} steps (${currentCount}) "${currentTitle}"`); console.log(`Gravity Bridge: [POLL#${pollCount}] +${delta} steps (${currentCount}) "${currentTitle}"`);
} }
// ── IMMEDIATE PENDING DETECTION ── // Log session state on EVERY poll for diagnostics
// On EVERY poll: check last 3 steps for non-DONE status const statusStr = String(bestSession.status || 'UNKNOWN');
// This catches: file review, file access permission, command approval if (pollCount <= 10 || pollCount % 6 === 0 || delta > 0) {
if (isRunning) { logToFile(`[POLL#${pollCount}] status=${statusStr} steps=${currentCount} delta=${delta}`);
try { }
const stepsResp = await sdk.ls.rawRPC('GetCascadeTrajectorySteps', { cascadeId: bestSessionId }); // ── Stall-based approval detection ──
const steps = stepsResp?.steps || []; // INSIGHT: Both thinking and approval show RUNNING+delta=0.
if (steps.length > 0) { // DIFFERENTIATOR: lastModifiedTime
// Check last 3 steps (some may be in-flight) // - Thinking: lastModifiedTime KEEPS CHANGING (server actively processing)
const checkCount = Math.min(3, steps.length); // - Approval wait: lastModifiedTime FROZEN (server idle, waiting for user)
for (let i = steps.length - checkCount; i < steps.length; i++) { // DEBUG: dump session keys on first poll to find modTime field
const step = steps[i]; if (pollCount === 1) {
const stepStatus = (step.status || '').replace('CORTEX_STEP_STATUS_', ''); const keys = Object.keys(bestSession).filter(k => !['latestNotifyUserStep', 'latestTaskBoundaryStep', 'latestToolCallStep'].includes(k));
const stepType = (step.type || '').replace('CORTEX_STEP_TYPE_', ''); logToFile(`[DEBUG] session keys: ${keys.join(', ')}`);
const stepIdx = step.metadata?.sourceTrajectoryStepInfo?.stepIndex ?? i; logToFile(`[DEBUG] lastModifiedTime=${bestSession.lastModifiedTime}, lastModifiedTimestamp=${bestSession.lastModifiedTimestamp}, modifiedTime=${bestSession.modifiedTime}`);
// Skip already-handled steps }
if (stepIdx <= lastPendingStepIndex) const currentModTime = bestSession.lastModifiedTime || bestSession.lastModifiedTimestamp || bestSession.modifiedTime || '';
continue; const modTimeChanged = currentModTime !== lastModTime;
// Skip completed/rejected steps const isStall = isRunning && delta === 0;
if (stepStatus === 'DONE' || stepStatus === 'REJECTED') // Log modTime on stalls for debugging
continue; if (isStall && consecutiveIdleCount < 8) {
// ── Non-DONE step found! Create pending based on type ── logToFile(`[STALL-DBG] idle=${consecutiveIdleCount} modTime='${currentModTime}' changed=${modTimeChanged}`);
let cmd = ''; }
let desc = ''; if (delta > 0) {
const toolName = step.metadata?.toolCall?.name || ''; consecutiveIdleCount = 0;
let argsJson = ''; sawRunningAfterPending = true;
try { lastModTime = currentModTime;
argsJson = step.metadata?.toolCall?.argumentsJson || ''; }
} else if (isStall) {
catch { } if (modTimeChanged) {
if (toolName === 'run_command' || toolName === 'send_command_input') { // lastModifiedTime is still changing = AI is thinking, NOT approval
// Command execution approval consecutiveIdleCount = 0; // Reset!
try { if (pollCount <= 10 || pollCount % 12 === 0) {
const args = JSON.parse(argsJson || '{}'); logToFile(`[THINK] step=${currentCount} modTime changing → not stall`);
cmd = args.CommandLine || args.command || args.Input || toolName;
}
catch {
cmd = toolName;
}
desc = `명령어 실행 승인 (${stepType})`;
}
else if (toolName === 'browser_subagent') {
// Browser subagent
try {
const args = JSON.parse(argsJson || '{}');
cmd = args.Task?.substring(0, 150) || 'browser task';
}
catch {
cmd = 'browser_subagent';
}
desc = `브라우저 서브에이전트 실행`;
}
else if (stepType === 'CODE_ACTION' || toolName === 'replace_file_content' || toolName === 'multi_replace_file_content' || toolName === 'write_to_file') {
// File modification review
try {
const args = JSON.parse(argsJson || '{}');
cmd = args.TargetFile || args.target_file || toolName;
}
catch {
cmd = toolName;
}
desc = `파일 수정 검토 요청`;
}
else if (toolName === 'view_file' || toolName === 'view_file_outline' || toolName === 'view_code_item') {
// File access (usually auto-approved, but handle if pending)
try {
const args = JSON.parse(argsJson || '{}');
cmd = args.AbsolutePath || args.File || toolName;
}
catch {
cmd = toolName;
}
desc = `파일 접근 권한 요청`;
}
else if (toolName === 'notify_user') {
// AI asking for user feedback — this needs a different response
try {
const args = JSON.parse(argsJson || '{}');
cmd = args.Message?.substring(0, 200) || 'notify_user';
}
catch {
cmd = 'notify_user';
}
desc = `사용자 피드백 요청`;
}
else if (toolName) {
cmd = toolName;
desc = `도구 실행: ${toolName}`;
}
else {
cmd = stepType || 'unknown';
desc = `${stepType} (${stepStatus})`;
}
// Create pending for Discord
const rid = Date.now().toString();
const pending = {
request_id: rid,
conversation_id: bestSessionId,
command: cmd.substring(0, 500),
description: desc.substring(0, 200),
timestamp: Date.now() / 1000,
status: 'pending',
project_name: projectName,
step_index: stepIdx,
step_type: stepType,
step_status: stepStatus,
tool_name: toolName,
auto_detected: true,
};
const pendingDir = path.join(bridgePath, 'pending');
fs.writeFileSync(path.join(pendingDir, `${rid}.json`), JSON.stringify(pending, null, 2));
lastPendingStepIndex = stepIdx;
logToFile(`[PENDING] step=${stepIdx} type=${stepType} status=${stepStatus} tool=${toolName} cmd=${cmd.substring(0, 60)}`);
console.log(`Gravity Bridge: [POLL#${pollCount}] PENDING! step=${stepIdx} ${toolName || stepType} → pending/${rid}.json`);
}
} }
} }
catch (e) { else {
// Only log occasionally to avoid spam // lastModifiedTime frozen = real stall (approval waiting)
if (pollCount % 10 === 0) { consecutiveIdleCount++;
logToFile(`[PENDING] step query error: ${e.message}`);
}
} }
lastModTime = currentModTime;
const now = Date.now();
const cooldownOk = (now - lastPendingTime) > 60_000;
if (consecutiveIdleCount >= 6 && sawRunningAfterPending && cooldownOk) {
// 6 polls × 5s = 30 seconds of FROZEN stall = approval waiting
lastPendingStepIndex = currentCount;
lastPendingTime = now;
sawRunningAfterPending = false;
const command = `Stall at step ${currentCount}`;
const description = `승인 대기 감지 (${consecutiveIdleCount * 5}초 정지), Title: "${currentTitle}"`;
logToFile(`[STALL] step=${currentCount} frozenCount=${consecutiveIdleCount} → pending`);
writePendingApproval({ conversation_id: activeSessionId, command, description });
}
else if (consecutiveIdleCount === 6) {
const reasons = [];
if (!sawRunningAfterPending)
reasons.push('needDelta>0');
if (!cooldownOk)
reasons.push(`cooldown(${Math.round((60000 - (now - lastPendingTime)) / 1000)}s)`);
if (reasons.length > 0)
logToFile(`[STALL] SKIP: ${reasons.join(', ')}`);
}
}
else if (!isRunning) {
consecutiveIdleCount = 0;
lastModTime = currentModTime;
} }
// ── Process latestNotifyUserStep ── // ── Process latestNotifyUserStep ──
const notifyStep = bestSession.latestNotifyUserStep; const notifyStep = bestSession.latestNotifyUserStep;
@@ -519,48 +784,79 @@ async function processResponseFile(filePath) {
} }
catch { } catch { }
} }
if (resp.approved) { // ═══ APPROVAL STRATEGY (VS Code Commands Only) ═══
// Step 1: Focus Antigravity panel — webview MUST be active for commands to work // Phase 0 ResolveOutstandingSteps: REMOVED — confirmed it CANCELS steps!
// acceptAgentStep dispatches via postMessage to Chat Client webview // Phase 1 HandleCascadeUserInteraction: REMOVED — always gets "socket hang up"
// Phase 2: ALL VS Code commands sequentially (no break on "success")
const approved = resp.approved;
// Focus panel with multiple attempts + longer delay
for (let i = 0; i < 2; i++) {
try { try {
await vscode.commands.executeCommand('antigravity.agentPanel.focus'); await vscode.commands.executeCommand('antigravity.agentPanel.focus');
logToFile('[RESPONSE] panel focused'); if (i === 0)
logToFile('[RESPONSE] panel focus attempt 1');
} }
catch (e) { catch (e) {
logToFile(`[RESPONSE] panel focus failed: ${e.message}`); logToFile(`[RESPONSE] panel focus attempt ${i + 1} failed: ${e.message}`);
} }
// Wait for webview to initialize
await new Promise(r => setTimeout(r, 500)); await new Promise(r => setTimeout(r, 500));
// Step 2: Accept — only acceptAgentStep (the universal approval command) }
try { // Phase 2: Sequential VS Code commands (MUST try ALL — no break!)
await vscode.commands.executeCommand('antigravity.agent.acceptAgentStep'); // Focus panel first
logToFile('[RESPONSE] acceptAgentStep sent'); try {
await vscode.commands.executeCommand('antigravity.agentPanel.focus');
logToFile('[RESPONSE] panel focused');
}
catch (e) {
logToFile(`[RESPONSE] panel focus failed: ${e.message}`);
}
await new Promise(r => setTimeout(r, 500));
if (approved) {
const approveCommands = [
'antigravity.interactiveCascade.acceptSuggestedAction',
'antigravity.terminalCommand.run',
'antigravity.terminalCommand.accept',
'antigravity.command.accept',
'antigravity.agent.acceptAgentStep',
];
for (const cmd of approveCommands) {
try {
await vscode.commands.executeCommand(cmd);
logToFile(`[RESPONSE] cmd OK: ${cmd}`);
}
catch (e) {
logToFile(`[RESPONSE] cmd FAIL: ${cmd}${e.message}`);
}
} }
catch (e) {
logToFile(`[RESPONSE] acceptAgentStep failed: ${e.message}`);
}
logToFile('[RESPONSE] approve done');
} }
else { else {
// REJECT — same pattern: focus first, then reject const rejectCommands = [
try { 'antigravity.interactiveCascade.rejectSuggestedAction',
await vscode.commands.executeCommand('antigravity.agentPanel.focus'); 'antigravity.terminalCommand.reject',
'antigravity.command.reject',
'antigravity.agent.rejectAgentStep',
];
for (const cmd of rejectCommands) {
try {
await vscode.commands.executeCommand(cmd);
logToFile(`[RESPONSE] cmd OK: ${cmd}`);
}
catch (e) {
logToFile(`[RESPONSE] cmd FAIL: ${cmd}${e.message}`);
}
} }
catch { }
await new Promise(r => setTimeout(r, 500));
try {
await vscode.commands.executeCommand('antigravity.agent.rejectAgentStep');
logToFile('[RESPONSE] rejectAgentStep sent');
}
catch (e) {
logToFile(`[RESPONSE] rejectAgentStep failed: ${e.message}`);
}
logToFile('[RESPONSE] reject done');
} }
logToFile(`[RESPONSE] ${approved ? 'approve' : 'reject'} done`);
// Cleanup
try { try {
fs.unlinkSync(filePath); fs.unlinkSync(filePath);
} }
catch { } catch { }
try {
if (fs.existsSync(pendingFile))
fs.unlinkSync(pendingFile);
}
catch { }
} }
catch (e) { catch (e) {
const log = `[RESPONSE] error: ${e.message}`; const log = `[RESPONSE] error: ${e.message}`;
@@ -693,8 +989,9 @@ async function activate(context) {
const sdkReady = await initSDK(context); const sdkReady = await initSDK(context);
if (sdkReady) { if (sdkReady) {
setupMonitor(); // Now just logs that monitor is disabled setupMonitor(); // Now just logs that monitor is disabled
setupApprovalObserver(); // DOM observer via SDK IntegrationManager
statusBar.text = '$(check) Bridge'; statusBar.text = '$(check) Bridge';
statusBar.tooltip = `Gravity Bridge: ${projectName} (POLL active)`; statusBar.tooltip = `Gravity Bridge: ${projectName} (POLL + Observer active)`;
// Register SDK-powered commands // Register SDK-powered commands
context.subscriptions.push(vscode.commands.registerCommand('gravityBridge.approve', async () => { context.subscriptions.push(vscode.commands.registerCommand('gravityBridge.approve', async () => {
try { try {

File diff suppressed because one or more lines are too long

View File

@@ -18,12 +18,16 @@ import * as cp from 'child_process';
// ─── File-based logging (AI can read directly) ─── // ─── File-based logging (AI can read directly) ───
function logToFile(msg: string) { function logToFile(msg: string) {
const ts = new Date().toISOString().replace('T', ' ').substring(0, 19);
const line = `${ts} ${msg}`;
console.log(`Gravity Bridge: ${msg}`);
try { try {
if (!bridgePath) return; if (!bridgePath) return;
const logFile = path.join(bridgePath, 'extension.log'); const logFile = path.join(bridgePath, 'extension.log');
const ts = new Date().toISOString().replace('T', ' ').substring(0, 19); fs.appendFileSync(logFile, line + '\n', 'utf-8');
fs.appendFileSync(logFile, `${ts} ${msg}\n`, 'utf-8'); } catch (e: any) {
} catch { } console.error(`Gravity Bridge LOG WRITE FAIL: ${e.message}`);
}
} }
// antigravity-sdk embedded locally (src/sdk/) // antigravity-sdk embedded locally (src/sdk/)
@@ -201,6 +205,299 @@ async function initSDK(context: vscode.ExtensionContext): Promise<boolean> {
} }
} }
// ─── Approval Observer via SDK IntegrationManager ───
async function setupApprovalObserver() {
if (!sdk) { logToFile('[OBSERVER] no SDK'); return; }
try {
const integration = sdk.integration;
if (!integration) { logToFile('[OBSERVER] sdk.integration unavailable'); return; }
// 1. Start HTTP bridge server in Extension Host
const bridgePort = await startObserverHttpBridge();
if (!bridgePort) { logToFile('[OBSERVER] HTTP bridge failed'); return; }
// 2. Register a TOP_BAR button so build() works
try {
integration.register({
id: 'gravity_bridge_status',
point: 'topBar',
icon: '🌉',
tooltip: 'Gravity Bridge Active',
});
} catch { /* already registered */ }
// 3. Write renderer script with HTTP fetch() approach
const observerJS = generateApprovalObserverScript(bridgePort);
const patcher = (integration as any)._patcher;
if (patcher && typeof patcher.getScriptPath === 'function') {
let baseScript = '';
try { baseScript = integration.build(); } catch { baseScript = ''; }
const combinedScript = baseScript + '\n' + observerJS;
const scriptPath = patcher.getScriptPath();
fs.writeFileSync(scriptPath, combinedScript, 'utf8');
logToFile(`[OBSERVER] script written → ${scriptPath} (port=${bridgePort})`);
if (!integration.isInstalled()) {
patcher.install(combinedScript);
logToFile('[OBSERVER] workbench.html patched (needs reload)');
}
// Also patch workbench-jetski-agent.html (Antigravity's actual entry point!)
const scriptDir = path.dirname(scriptPath);
const jetskiHtml = path.join(scriptDir, 'workbench-jetski-agent.html');
const scriptBasename = path.basename(scriptPath);
try {
if (fs.existsSync(jetskiHtml)) {
let html = fs.readFileSync(jetskiHtml, 'utf8');
if (!html.includes(scriptBasename)) {
html = html.replace('</html>',
`\n<!-- AG SDK [variet-gravity-bridge] -->\n<script src="./${scriptBasename}"></script>\n<!-- /AG SDK [variet-gravity-bridge] -->\n</html>`);
fs.writeFileSync(jetskiHtml, html, 'utf8');
logToFile('[OBSERVER] workbench-jetski-agent.html PATCHED');
} else {
logToFile('[OBSERVER] workbench-jetski-agent.html already has script tag');
}
}
} catch (e: any) {
logToFile(`[OBSERVER] jetski patch error: ${e.message}`);
}
}
try { integration.enableAutoRepair(); } catch { }
setInterval(() => { try { integration.signalActive(); } catch { } }, 30_000);
logToFile(`[OBSERVER] setup complete (HTTP bridge on port ${bridgePort})`);
console.log(`Gravity Bridge: ✅ Approval observer installed (port ${bridgePort})`);
} catch (err: any) {
logToFile(`[OBSERVER] setup error: ${err.message}`);
}
}
// ─── HTTP Bridge Server (Extension Host → Renderer communication) ───
let observerHttpServer: any = null;
const pendingResponses = new Map<string, { approved: boolean } | null>();
function startObserverHttpBridge(): Promise<number> {
return new Promise((resolve) => {
try {
const http = require('http');
const server = http.createServer((req: any, res: any) => {
// CORS headers for renderer fetch()
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS');
res.setHeader('Access-Control-Allow-Headers', 'Content-Type');
if (req.method === 'OPTIONS') { res.writeHead(200); res.end(); return; }
const url = new URL(req.url, `http://127.0.0.1`);
// POST /pending — renderer reports a detected approval button
if (req.method === 'POST' && url.pathname === '/pending') {
let body = '';
req.on('data', (c: string) => body += c);
req.on('end', () => {
try {
const data = JSON.parse(body);
const rid = data.request_id || Date.now().toString();
// Write pending file for Discord bot
const pendingDir = path.join(bridgePath, 'pending');
if (!fs.existsSync(pendingDir)) fs.mkdirSync(pendingDir, { recursive: true });
const pending = {
...data,
request_id: rid,
timestamp: Date.now() / 1000,
status: 'pending',
project_name: projectName,
auto_detected: true,
source: 'dom_observer',
};
fs.writeFileSync(path.join(pendingDir, `${rid}.json`), JSON.stringify(pending, null, 2));
logToFile(`[HTTP] pending created: ${rid} cmd="${data.command}" ctx="${(data.description || '').substring(0, 50)}"`);
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ ok: true, request_id: rid }));
} catch (e: any) {
logToFile(`[HTTP] pending error: ${e.message}`);
res.writeHead(400); res.end(JSON.stringify({ error: e.message }));
}
});
return;
}
// GET /response/:rid — renderer polls for Discord approval
if (req.method === 'GET' && url.pathname.startsWith('/response/')) {
const rid = url.pathname.split('/')[2];
const respFile = path.join(bridgePath, 'response', `${rid}.json`);
if (fs.existsSync(respFile)) {
try {
const data = JSON.parse(fs.readFileSync(respFile, 'utf8'));
fs.unlinkSync(respFile);
logToFile(`[HTTP] response sent: ${rid} approved=${data.approved}`);
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify(data));
} catch {
res.writeHead(200); res.end(JSON.stringify({ waiting: true }));
}
} else {
res.writeHead(200); res.end(JSON.stringify({ waiting: true }));
}
return;
}
// GET /ping — health check
if (url.pathname === '/ping') {
res.writeHead(200); res.end('pong');
return;
}
res.writeHead(404); res.end('not found');
});
// Listen on random port
server.listen(0, '127.0.0.1', () => {
const port = server.address().port;
observerHttpServer = server;
logToFile(`[HTTP] bridge server started on port ${port}`);
// Write port to workbench dir so renderer can read it via XHR
const patcher = (sdk.integration as any)?._patcher;
if (patcher && typeof patcher.getWorkbenchDir === 'function') {
const portFile = path.join(patcher.getWorkbenchDir(), 'ag-bridge-port');
fs.writeFileSync(portFile, port.toString(), 'utf8');
logToFile(`[HTTP] port written → ${portFile}`);
}
resolve(port);
});
server.on('error', (e: any) => {
logToFile(`[HTTP] server error: ${e.message}`);
resolve(0);
});
} catch (e: any) {
logToFile(`[HTTP] server failed: ${e.message}`);
resolve(0);
}
});
}
// ─── Renderer Script (uses fetch() — no Node.js APIs) ───
function generateApprovalObserverScript(_port: number): string {
// Port is NOT hardcoded — renderer reads it dynamically from ag-bridge-port file via XHR
return `
// ── Gravity Bridge: Approval Observer (renderer-side, dynamic port) ──
(function(){
'use strict';
var BASE='',_lastTs=0,_obs=false,_sent={},_ready=false;
function log(m){console.log('[GB Observer] '+m);}
log('Script loaded — discovering bridge port...');
// ── Dynamic Port Discovery (like SDK heartbeat) ──
function discoverPort(cb){
var attempts=0;
var timer=setInterval(function(){
attempts++;
if(attempts>30){clearInterval(timer);log('Port discovery timeout');return;}
try{
var xhr=new XMLHttpRequest();
xhr.open('GET','./ag-bridge-port?t='+Date.now(),false);
xhr.send();
if(xhr.status===200){
var port=parseInt(xhr.responseText.trim(),10);
if(port>0&&port<65536){
clearInterval(timer);
log('Port discovered: '+port);
cb(port);
}
}
}catch(e){}
},2000);
}
discoverPort(function(port){
BASE='http://127.0.0.1:'+port;
// Verify bridge is alive
fetch(BASE+'/ping').then(function(r){return r.text();}).then(function(t){
if(t==='pong'){log('Bridge connected on port '+port);_ready=true;startObserver();}
else log('Bridge ping failed: '+t);
}).catch(function(e){log('Bridge unreachable: '+e.message);});
});
var PATS=[
{sel:'button',re:/^Run$/i,type:'terminal_command'},
{sel:'button',re:/^Accept/i,type:'agent_step'},
{sel:'button',re:/^Allow/i,type:'permission'},
{sel:'button',re:/^Continue$/i,type:'continue'},
];
function ctx(b){
var p=b.closest('[class*="step"]')||b.closest('[class*="action"]')||b.parentElement;
if(!p)return '';
var c=p.querySelector('pre,code,[class*="command"],[class*="terminal"]');
if(c)return(c.textContent||'').trim().substring(0,200);
return(p.textContent||'').replace((b.textContent||''),'').trim().substring(0,200);
}
function scan(){
if(!_ready)return;
var now=Date.now();if(now-_lastTs<1000)return;
var panel=document.querySelector('#jetski-agent-panel,.antigravity-agent-side-panel,[class*="agent-panel"]');
if(!panel)return;
for(var i=0;i<PATS.length;i++){
var pat=PATS[i],btns=panel.querySelectorAll(pat.sel);
for(var j=0;j<btns.length;j++){
var b=btns[j],txt=(b.textContent||'').trim();
if(!pat.re.test(txt)||b.disabled)continue;
var bid=pat.type+'_'+txt+'_'+Math.round(b.getBoundingClientRect().top);
if(_sent[bid])continue;
var desc=ctx(b),rid=now.toString();
_sent[bid]=rid;_lastTs=now;
log('FOUND '+pat.type+': "'+txt+'" → sending to bridge');
(function(rid2,b2,bid2){
fetch(BASE+'/pending',{
method:'POST',
headers:{'Content-Type':'application/json'},
body:JSON.stringify({request_id:rid2,command:txt,description:desc,step_type:pat.type})
}).then(function(r){return r.json();}).then(function(d){
log('Pending created: '+d.request_id);
pollResp(d.request_id,b2,bid2);
}).catch(function(e){log('POST error: '+e.message);delete _sent[bid2];});
})(rid,b,bid);
return;
}
}
}
function pollResp(rid,b,bid){
var n=0,t=setInterval(function(){
n++;if(n>600){clearInterval(t);delete _sent[bid];return;}
fetch(BASE+'/response/'+rid).then(function(r){return r.json();}).then(function(d){
if(d.waiting)return;
clearInterval(t);
if(d.approved){log('APPROVED '+rid+' → clicking');b.click();}
else{
log('REJECTED '+rid);
var p=b.closest('[class*="step"]')||b.parentElement;
if(p){var rb=p.querySelectorAll('button');
for(var k=0;k<rb.length;k++){var rt=(rb[k].textContent||'').trim().toLowerCase();
if(rt==='reject'||rt==='cancel'||rt==='deny'){rb[k].click();break;}}}
}
delete _sent[bid];
}).catch(function(){});
},500);
}
function startObserver(){
if(_obs)return;
new MutationObserver(function(){scan();}).observe(document.body,{childList:true,subtree:true});
setInterval(scan,2000);
_obs=true;log('Observer active — watching for approval buttons');
}
})();
`;
}
// Track last seen step per session to avoid re-fetching // Track last seen step per session to avoid re-fetching
const lastSeenStep = new Map<string, number>(); const lastSeenStep = new Map<string, number>();
const lastSnapshotText = new Map<string, string>(); const lastSnapshotText = new Map<string, string>();
@@ -255,12 +552,22 @@ function setupMonitor() {
let lastNotifyStepIndex = -1; let lastNotifyStepIndex = -1;
let lastTaskStepIndex = -1; let lastTaskStepIndex = -1;
let lastPendingStepIndex = -1; // dedup: don't re-create pending for same step let lastPendingStepIndex = -1; // dedup: don't re-create pending for same step
let consecutiveIdleCount = 0; // debounce: require N consecutive stall polls
let lastPendingTime = 0; // cooldown: minimum gap between pendings
let sawRunningAfterPending = true; // gate: must see delta>0 before next pending
let lastModTime = ''; // track lastModifiedTime to distinguish thinking vs approval
setInterval(async () => { setInterval(async () => {
pollCount++; pollCount++;
if (pollCount <= 3 || pollCount % 12 === 0) {
logToFile(`[POLL#${pollCount}] alive`);
}
try { try {
const allTraj = await sdk.ls.rawRPC('GetAllCascadeTrajectories', {}); const allTraj = await sdk.ls.rawRPC('GetAllCascadeTrajectories', {});
if (!allTraj?.trajectorySummaries) return; if (!allTraj?.trajectorySummaries) {
if (pollCount <= 3) logToFile('[POLL] no trajectorySummaries');
return;
}
let bestSession: any = null; let bestSession: any = null;
let bestSessionId = ''; let bestSessionId = '';
@@ -299,106 +606,74 @@ function setupMonitor() {
console.log(`Gravity Bridge: [POLL#${pollCount}] +${delta} steps (${currentCount}) "${currentTitle}"`); console.log(`Gravity Bridge: [POLL#${pollCount}] +${delta} steps (${currentCount}) "${currentTitle}"`);
} }
// ── IMMEDIATE PENDING DETECTION ── // Log session state on EVERY poll for diagnostics
// On EVERY poll: check last 3 steps for non-DONE status const statusStr = String(bestSession.status || 'UNKNOWN');
// This catches: file review, file access permission, command approval if (pollCount <= 10 || pollCount % 6 === 0 || delta > 0) {
if (isRunning) { logToFile(`[POLL#${pollCount}] status=${statusStr} steps=${currentCount} delta=${delta}`);
try { }
const stepsResp = await sdk.ls.rawRPC('GetCascadeTrajectorySteps', { cascadeId: bestSessionId });
const steps = stepsResp?.steps || [];
if (steps.length > 0) {
// Check last 3 steps (some may be in-flight)
const checkCount = Math.min(3, steps.length);
for (let i = steps.length - checkCount; i < steps.length; i++) {
const step = steps[i];
const stepStatus = (step.status || '').replace('CORTEX_STEP_STATUS_', '');
const stepType = (step.type || '').replace('CORTEX_STEP_TYPE_', '');
const stepIdx = step.metadata?.sourceTrajectoryStepInfo?.stepIndex ?? i;
// Skip already-handled steps // ── Stall-based approval detection ──
if (stepIdx <= lastPendingStepIndex) continue; // INSIGHT: Both thinking and approval show RUNNING+delta=0.
// Skip completed/rejected steps // DIFFERENTIATOR: lastModifiedTime
if (stepStatus === 'DONE' || stepStatus === 'REJECTED') continue; // - Thinking: lastModifiedTime KEEPS CHANGING (server actively processing)
// - Approval wait: lastModifiedTime FROZEN (server idle, waiting for user)
// ── Non-DONE step found! Create pending based on type ── // DEBUG: dump session keys on first poll to find modTime field
let cmd = ''; if (pollCount === 1) {
let desc = ''; const keys = Object.keys(bestSession).filter(k => !['latestNotifyUserStep', 'latestTaskBoundaryStep', 'latestToolCallStep'].includes(k));
const toolName = step.metadata?.toolCall?.name || ''; logToFile(`[DEBUG] session keys: ${keys.join(', ')}`);
let argsJson = ''; logToFile(`[DEBUG] lastModifiedTime=${bestSession.lastModifiedTime}, lastModifiedTimestamp=${(bestSession as any).lastModifiedTimestamp}, modifiedTime=${(bestSession as any).modifiedTime}`);
try { argsJson = step.metadata?.toolCall?.argumentsJson || ''; } catch { } }
if (toolName === 'run_command' || toolName === 'send_command_input') { const currentModTime = bestSession.lastModifiedTime || (bestSession as any).lastModifiedTimestamp || (bestSession as any).modifiedTime || '';
// Command execution approval const modTimeChanged = currentModTime !== lastModTime;
try { const isStall = isRunning && delta === 0;
const args = JSON.parse(argsJson || '{}');
cmd = args.CommandLine || args.command || args.Input || toolName;
} catch { cmd = toolName; }
desc = `명령어 실행 승인 (${stepType})`;
} else if (toolName === 'browser_subagent') {
// Browser subagent
try {
const args = JSON.parse(argsJson || '{}');
cmd = args.Task?.substring(0, 150) || 'browser task';
} catch { cmd = 'browser_subagent'; }
desc = `브라우저 서브에이전트 실행`;
} else if (stepType === 'CODE_ACTION' || toolName === 'replace_file_content' || toolName === 'multi_replace_file_content' || toolName === 'write_to_file') {
// File modification review
try {
const args = JSON.parse(argsJson || '{}');
cmd = args.TargetFile || args.target_file || toolName;
} catch { cmd = toolName; }
desc = `파일 수정 검토 요청`;
} else if (toolName === 'view_file' || toolName === 'view_file_outline' || toolName === 'view_code_item') {
// File access (usually auto-approved, but handle if pending)
try {
const args = JSON.parse(argsJson || '{}');
cmd = args.AbsolutePath || args.File || toolName;
} catch { cmd = toolName; }
desc = `파일 접근 권한 요청`;
} else if (toolName === 'notify_user') {
// AI asking for user feedback — this needs a different response
try {
const args = JSON.parse(argsJson || '{}');
cmd = args.Message?.substring(0, 200) || 'notify_user';
} catch { cmd = 'notify_user'; }
desc = `사용자 피드백 요청`;
} else if (toolName) {
cmd = toolName;
desc = `도구 실행: ${toolName}`;
} else {
cmd = stepType || 'unknown';
desc = `${stepType} (${stepStatus})`;
}
// Create pending for Discord // Log modTime on stalls for debugging
const rid = Date.now().toString(); if (isStall && consecutiveIdleCount < 8) {
const pending = { logToFile(`[STALL-DBG] idle=${consecutiveIdleCount} modTime='${currentModTime}' changed=${modTimeChanged}`);
request_id: rid, }
conversation_id: bestSessionId,
command: cmd.substring(0, 500), if (delta > 0) {
description: desc.substring(0, 200), consecutiveIdleCount = 0;
timestamp: Date.now() / 1000, sawRunningAfterPending = true;
status: 'pending', lastModTime = currentModTime;
project_name: projectName, } else if (isStall) {
step_index: stepIdx, if (modTimeChanged) {
step_type: stepType, // lastModifiedTime is still changing = AI is thinking, NOT approval
step_status: stepStatus, consecutiveIdleCount = 0; // Reset!
tool_name: toolName, if (pollCount <= 10 || pollCount % 12 === 0) {
auto_detected: true, logToFile(`[THINK] step=${currentCount} modTime changing → not stall`);
};
const pendingDir = path.join(bridgePath, 'pending');
fs.writeFileSync(path.join(pendingDir, `${rid}.json`), JSON.stringify(pending, null, 2));
lastPendingStepIndex = stepIdx;
logToFile(`[PENDING] step=${stepIdx} type=${stepType} status=${stepStatus} tool=${toolName} cmd=${cmd.substring(0, 60)}`);
console.log(`Gravity Bridge: [POLL#${pollCount}] PENDING! step=${stepIdx} ${toolName || stepType} → pending/${rid}.json`);
}
}
} catch (e: any) {
// Only log occasionally to avoid spam
if (pollCount % 10 === 0) {
logToFile(`[PENDING] step query error: ${e.message}`);
} }
} else {
// lastModifiedTime frozen = real stall (approval waiting)
consecutiveIdleCount++;
} }
lastModTime = currentModTime;
const now = Date.now();
const cooldownOk = (now - lastPendingTime) > 60_000;
if (consecutiveIdleCount >= 6 && sawRunningAfterPending && cooldownOk) {
// 6 polls × 5s = 30 seconds of FROZEN stall = approval waiting
lastPendingStepIndex = currentCount;
lastPendingTime = now;
sawRunningAfterPending = false;
const command = `Stall at step ${currentCount}`;
const description = `승인 대기 감지 (${consecutiveIdleCount * 5}초 정지), Title: "${currentTitle}"`;
logToFile(`[STALL] step=${currentCount} frozenCount=${consecutiveIdleCount} → pending`);
writePendingApproval({ conversation_id: activeSessionId, command, description });
} else if (consecutiveIdleCount === 6) {
const reasons = [];
if (!sawRunningAfterPending) reasons.push('needDelta>0');
if (!cooldownOk) reasons.push(`cooldown(${Math.round((60000 - (now - lastPendingTime)) / 1000)}s)`);
if (reasons.length > 0) logToFile(`[STALL] SKIP: ${reasons.join(', ')}`);
}
} else if (!isRunning) {
consecutiveIdleCount = 0;
lastModTime = currentModTime;
} }
// ── Process latestNotifyUserStep ── // ── Process latestNotifyUserStep ──
@@ -475,42 +750,72 @@ async function processResponseFile(filePath: string) {
} catch { } } catch { }
} }
if (resp.approved) { // ═══ APPROVAL STRATEGY (VS Code Commands Only) ═══
// Step 1: Focus Antigravity panel — webview MUST be active for commands to work // Phase 0 ResolveOutstandingSteps: REMOVED — confirmed it CANCELS steps!
// acceptAgentStep dispatches via postMessage to Chat Client webview // Phase 1 HandleCascadeUserInteraction: REMOVED — always gets "socket hang up"
try { // Phase 2: ALL VS Code commands sequentially (no break on "success")
await vscode.commands.executeCommand('antigravity.agentPanel.focus');
logToFile('[RESPONSE] panel focused');
} catch (e: any) {
logToFile(`[RESPONSE] panel focus failed: ${e.message}`);
}
// Wait for webview to initialize
await new Promise(r => setTimeout(r, 500));
// Step 2: Accept — only acceptAgentStep (the universal approval command) const approved = resp.approved;
try {
await vscode.commands.executeCommand('antigravity.agent.acceptAgentStep'); // Focus panel with multiple attempts + longer delay
logToFile('[RESPONSE] acceptAgentStep sent'); for (let i = 0; i < 2; i++) {
} catch (e: any) {
logToFile(`[RESPONSE] acceptAgentStep failed: ${e.message}`);
}
logToFile('[RESPONSE] approve done');
} else {
// REJECT — same pattern: focus first, then reject
try { try {
await vscode.commands.executeCommand('antigravity.agentPanel.focus'); await vscode.commands.executeCommand('antigravity.agentPanel.focus');
} catch { } if (i === 0) logToFile('[RESPONSE] panel focus attempt 1');
await new Promise(r => setTimeout(r, 500));
try {
await vscode.commands.executeCommand('antigravity.agent.rejectAgentStep');
logToFile('[RESPONSE] rejectAgentStep sent');
} catch (e: any) { } catch (e: any) {
logToFile(`[RESPONSE] rejectAgentStep failed: ${e.message}`); logToFile(`[RESPONSE] panel focus attempt ${i + 1} failed: ${e.message}`);
} }
logToFile('[RESPONSE] reject done'); await new Promise(r => setTimeout(r, 500));
} }
// Phase 2: Sequential VS Code commands (MUST try ALL — no break!)
// Focus panel first
try {
await vscode.commands.executeCommand('antigravity.agentPanel.focus');
logToFile('[RESPONSE] panel focused');
} catch (e: any) {
logToFile(`[RESPONSE] panel focus failed: ${e.message}`);
}
await new Promise(r => setTimeout(r, 500));
if (approved) {
const approveCommands = [
'antigravity.interactiveCascade.acceptSuggestedAction',
'antigravity.terminalCommand.run',
'antigravity.terminalCommand.accept',
'antigravity.command.accept',
'antigravity.agent.acceptAgentStep',
];
for (const cmd of approveCommands) {
try {
await vscode.commands.executeCommand(cmd);
logToFile(`[RESPONSE] cmd OK: ${cmd}`);
} catch (e: any) {
logToFile(`[RESPONSE] cmd FAIL: ${cmd}${e.message}`);
}
}
} else {
const rejectCommands = [
'antigravity.interactiveCascade.rejectSuggestedAction',
'antigravity.terminalCommand.reject',
'antigravity.command.reject',
'antigravity.agent.rejectAgentStep',
];
for (const cmd of rejectCommands) {
try {
await vscode.commands.executeCommand(cmd);
logToFile(`[RESPONSE] cmd OK: ${cmd}`);
} catch (e: any) {
logToFile(`[RESPONSE] cmd FAIL: ${cmd}${e.message}`);
}
}
}
logToFile(`[RESPONSE] ${approved ? 'approve' : 'reject'} done`);
// Cleanup
try { fs.unlinkSync(filePath); } catch { } try { fs.unlinkSync(filePath); } catch { }
try { if (fs.existsSync(pendingFile)) fs.unlinkSync(pendingFile); } catch { }
} catch (e: any) { } catch (e: any) {
const log = `[RESPONSE] error: ${e.message}`; const log = `[RESPONSE] error: ${e.message}`;
console.log(`Gravity Bridge: ${log}`); console.log(`Gravity Bridge: ${log}`);
@@ -638,8 +943,9 @@ export async function activate(context: vscode.ExtensionContext) {
if (sdkReady) { if (sdkReady) {
setupMonitor(); // Now just logs that monitor is disabled setupMonitor(); // Now just logs that monitor is disabled
setupApprovalObserver(); // DOM observer via SDK IntegrationManager
statusBar.text = '$(check) Bridge'; statusBar.text = '$(check) Bridge';
statusBar.tooltip = `Gravity Bridge: ${projectName} (POLL active)`; statusBar.tooltip = `Gravity Bridge: ${projectName} (POLL + Observer active)`;
// Register SDK-powered commands // Register SDK-powered commands
context.subscriptions.push( context.subscriptions.push(